Menu
Who Do Is
  • Home
  • What
  • How
  • Is
  • Can
  • Are
  • Does
  • Do
  • Why
  • Who
  • Where
  • Which
  • Which
  • Should
  • Will
  • When
  • What’s
  • Did
Who Do Is

[ANSWERED] java – Sending token and Id to Server

Posted on November 14, 2022

Solution 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();

Problem :

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.

READ  [ANSWERED] android - FIX Xiaomi redmi series phones stuck in bootloader, system update rom for rooted phone
Powered by Inline Related Posts

Comments

Comment posted by aryanknp

where is id in sharedpreferences, you are putting

Comment posted by aryanknp

also your url is empty

Comment posted by Giannis tsiv

Yeah…i was trying some things and forgot to change that. but this is not the issue. Currently i get a error on MODE_APPEND.Error: Must be one or more of: Context.MODE_PRIVATE, Context.MODE_WORLD_READABLE, Context.MODE_WORLD_WRITEABLE, Context.MODE_MULTI_PROCESS

Comment posted by aryanknp

try private and also in your interface you use default sharedpreference , try to use one either default or the name you suggested

Comment posted by de-jcup

I think correct answer. But you should not use “sharedpref” as class name – it’s not correct java style. Java classes should always start with an uppercase character. Also I would suggest to use a more dedicated name – e.g. when your application name is “MyApp” then “MyAppSharedPreferences” sounds more precise

Recent Posts

  • How can I play with my cat without toys?
  • What is a bag pipe band called?
  • Are Honda Civics actually fast?
  • Are Yankee candles toxic?
  • How do I pair my Michael Kors smartwatch with my Android?

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuántas
  • ¿Cuánto
  • ¿Que
  • ¿Quién
  • 90” and 108” so you may have to round up to the nearest size.
  • and delete any Spotify folders from it. Once this is done
  • Android
  • Are
  • At
  • Bei
  • blink
  • C'est
  • Can
  • carbs
  • Comment
  • Did
  • Do
  • Does
  • During
  • For
  • Has
  • How
  • In
  • Is
  • Ist
  • Kann
  • Können
  • nouveau
  • On
  • or 108 inches.2020-08-03
  • Où
  • owning
  • Pourquoi
  • Puis-je
  • Quand
  • Quante
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • spiritual
  • tap the downward-facing arrow on the top left. A downward-facing arrow will appear underneath each song in the album; they'll turn green as the download completes.2020-07-28
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welcher
  • Welches
  • Welke
  • Wer
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Whose
  • Why
  • Wie
  • Will
  • Wo
  • Woher
  • you will receive two curtains each with the same measurements of width 66"" (168cm) x drop 54""(137cm).
  • you'll see a green downward-facing arrow next to each song.2021-02-26
©2023 Who Do Is | Powered by SuperbThemes & WordPress