Sending token and Id to Server

岁酱吖の 提交于 2021-01-29 06:12:04

问题


I am trying to develop a webview app that uses JSinterface to get the user_id. what I am trying to do is send two values to my server, user_id and FCM token,onpause(). i am getting and saving the fcm token inside my onCreate() like that.

FirebaseInstanceId.getInstance().getInstanceId()
            .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                @Override
                public void onComplete(@NonNull Task<InstanceIdResult> task) {
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "Failed", task.getException());

                        return;
                    }

                    String token = task.getResult().getToken();
                    SharedPreferences sharedPreferences
                            = getSharedPreferences("info",
                            MODE_PRIVATE);
                    SharedPreferences.Editor myEdit
                            = sharedPreferences.edit();
                    myEdit.putString("token",
                            token);
                    myEdit.commit();
                    Log.i("FCM", "Current token=" + token);

                }
            });

i am getting the user id with this class.

public class JsInterface {
private Context mcontext;


public JsInterface(Context c) {
    this.mcontext = c;
}

@JavascriptInterface
public void getid(String userid){
    int id;
    try {
        id = Integer.parseInt(userid);
    }
    catch (NumberFormatException e)
    {
        id = -1;
    }
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mcontext);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt("userid", id);
    editor.commit();
}

public int LoadId(){
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mcontext);
    int userid = sharedPreferences.getInt("userid", -1);
    return userid;

}}

What i've tried regarding sending the values to the server:

 class AsyncT extends AsyncTask<Void,Void,Void> {

    @Override
    protected Void doInBackground(Void...params) {

        try {
            URL url = new URL("Myurl"); //Enter URL here
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.connect();
            SharedPreferences sh
                    = getSharedPreferences("info",MODE_APPEND);

            String token = sh.getString("token", "");
            int id = sh.getInt("userid", -1);

            JSONObject jsonObject = new JSONObject();


            DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
            wr.writeBytes(jsonObject.toString());
            wr.flush();
            wr.close();
            Log.i("Token", "Current token=" + token); //the logs dont have the correct values
            Log.i("id", "Current id=" + id);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

 @Override
protected void onPause()
{
    AsyncT asyncT = new AsyncT();
    asyncT.execute();
    super.onPause();
}

i am not experienced with sharedPrefs at all and i cant understand the context part on the JSinteface so thats why i think this doesnt work.


回答1:


try to make one class for updating and getting value from your default sharedpreference, this will help you avoid confusion:

    public class sharedpref {
    
        private SharedPreferences mysharedpref;
    
        public sharedpref(Context cntx) { // pass context of activity you are using this
          
            mysharedpref = PreferenceManager.getDefaultSharedPreferences(cntx);
        }
    
        public void setuserid(String userid) {
            prefs.edit().putString("userid", userid).commit();
        }
     public  String getuserid(){
            String userid = prefs.getString("userid","");
            return  userid;
        }
      public void settoken(String token) {
            prefs.edit().putString("token", token).commit();
        }
     public  String gettoken(){
            String token = prefs.getString("token","");
            return  token;
        }
}

Now in any activity just call:

private sharedpref sp = new sharedpref(this.getApplicationContext());
// then simply perform your operations

sp.settoken(value);
sp.getuserid();


来源:https://stackoverflow.com/questions/63299783/sending-token-and-id-to-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!