I'm trying to use SharedPreferences
here is what i do
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Log.d
result is like this
Setup --> {"nameValuePairs":{"userData":{"nameValuePairs":{"phone":"089688xxxxxxx",
"username":"username of User","flag":1,"Email":"mymail@mail.com",
"tipe":"TP001","Deskripsi":"Ini tentang gua","user_id":"USER001",
"password":"c83e4046a7c5d3c4bf4c292e1e6ec681","fullname":My fullname"}},"status":"true"}}
then i'm trying to retrieve it, in other activity here is what i do
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}
and here how i open my other activity
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
With my script above, the result from my logcat
, i only see like Log.d
above. So my question is, how can i retrieve it ?
Try to add a key on your SharedPreferences
:
public void StoreToshared(Object userData){
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(userData);
Log.d("data", " Setup --> "+json);
prefsEditor.putString("userinfo", json);
prefsEditor.commit();
}
Retrieval:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences mPrefs = getSharedPreferences("your_sp_key", MODE_PRIVATE); //add key
SharedPreferences.Editor prefsEditor = mPrefs.edit();
String data = mPrefs.getString("userinfo", null);
Log.i("Text", "Here is the retrieve");
Log.i("data", " retrieve --> "+data);
}