Reputation: 61
I have two instances of shared preferences in my activity class. One instance I'm using to retrieve data that is already stored in shared preferences. The other instances I'm trying to store new sets of data, into a different file, that I'm retrieving from api. Can we do that because null values are being stored in the shared preferences.
Here is a part of my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);){
..........
SharedPreferences sharedPreferences = getSharedPreferences("User",Context.MODE_PRIVATE);
email = sharedPreferences.getString("email",DEFAULT);
//some piece of code........
setdata();//in this method I'm initializing the variables
SharedPreferences sharedPreferences2 = getSharedPreferences("File",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences2.edit();
editor.putString("a",a);
editor.putString("b",b);
editor.putString("c",c);
editor.putString("d",d);
editor.putString("e",e);
editor.commit();
}
public void setData(){
a="hello";
b="world";
c="hello";
d="world";
e="hello";
}
All these are in my onCreate method of my activity class. a,b,c,d,e are global variable which I'm initializing in some other method of the class. I'm making the method call in onCreate method before implementing the shared preferences. But null values are being stored.
Upvotes: 0
Views: 166
Reputation: 431
You have answered you question... The code you have posted is in onCreate method of your activity and a,b,c,d,e are global variables.
So they have null values when the activity starts.
You need to execute the code to save the values after you have initialized the value of a,b,c,d,e which is after receiving data from the API.
Upvotes: 1