Can't use SharedPreferences in method that doesn't get called in onCreate()?
In my app, I'm trying to save an ArrayList of Strings. I have an Activity Favourites, which has an add()
method. This method开发者_开发技巧 is called in another Activity to add something to the ArrayList. I want that each time something is added, it first gets all the values that I've stored in SharedPreferences
, checks if the value isn't already there and if it's not, adds it to the ArrayList. Finally I want it to store all the values again in SharedPreferences
. When the Activity Favourites is called, it shows a list with all the favourites (Gets each value in database and all that).
So I've made a method, but as onCreate()
is never called when an item is added to the ArrayList, I can't seem to instantiate my SharedPreferences
. Is there anyone who can give me some hints to get this to work?
Note: I don't want to work with SQLite database, because it would be for only one class in my app, and it would contain very little values.
Also, the code I used:
public void add(String v, String k){
prefs = PreferenceManager.getDefaultSharedPreferences(this);
int countvaca = prefs.getInt("vacacount", 0);
int countkantoor = prefs.getInt("kantoorcount", 0);
for(int i = 0; i <countvaca; i++){
vaca.add(prefs.getString("Vaca"+i, null));
}
for(int j = 0; j <countkantoor; j++){
kantoor.add(prefs.getString("Kantoor"+j, null));
}
boolean blnFound = vaca.contains(v);
System.out.println("Does arrayList contain vacature ? " + blnFound);
if(!blnFound){
vaca.add(v);
kantoor.add(k);
}
Editor edit = prefs.edit();
countvaca = vaca.size();
countkantoor = kantoor.size();
edit.putInt("Vacaturelijstgrootte", countvaca);
edit.putInt("Kantoorlijstgrootte", countkantoor);
for(int a = 0; a<countvaca; a++){
edit.putString("Vaca"+a, vaca.get(a));
}
for(int b = 0; b< countkantoor; b++){
edit.putString("Kantoor"+b, kantoor.get(b));
}
edit.commit();
}
If onCreate never gets called then you activity is never started, so the "this" in
prefs = PreferenceManager.getDefaultSharedPreferences(this);
doesn't refer to a properly initialized activity.
Either you should start your activity that contains your "add" method (which automatically calls the onCreate method), or you can pass a reference to the currently active Activity to your add method, i.e. something like this:
public void add(String v, String k, Activity a){
prefs = PreferenceManager.getDefaultSharedPreferences(a);
However, it is not considered good programming style to directly call methods from one activity to another. Best is to create a separate class that contains the code that the two activities have in common.
精彩评论