Hi im stuck with how to store server TOKEN to the Shared Preferences and use it on 2nd activity, anyone help?
if (response.isSuccessful()) {
String myResponse = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject obj = new JSONObject(myResponse);
System.out.println(obj.getString("status"));
System.out.println(obj.getString("status_desc"));
System.out.println(obj.getString("login_token"));
if (obj.optString("status").equals("Y")) {
class Preferences {
public void setAccessToken(@NonNull Context context, String token) {
SharedPreferences sharedPreferences = context.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(obj.optString("login_token"), token);
editor.apply(); }
}
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
intent.putExtra("AccessToken", (obj.getString("login_token")));
startActivity(intent);
}
else {
new AlertDialog.Builder(MainActivity.this)
.setTitle("WARNING!")
.setMessage((obj.getString("status_desc")))
.setPositiveButton(android.R.string.ok, null)
.show();
}
}
these my coding on 1st activity
class Preferences {
public void setAccessToken(@NonNull Context context, String token) {
SharedPreferences sharedPreferences = context.getSharedPreferences("MySharedPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(obj.optString("login_token"), token);
editor.apply(); }
}
tried this, but didnt found any token stored on my shared preferences.
any suggestion?
CodePudding user response:
You can replace the "obj.optString("login_token")" with a simple string like "token"
and it should work fine.
For example:
To save editor.putString("token", token).apply()
To get the token sharedPreferences.getString("token")