Android Saving Data to application
Is there some way in android to save objects to a place where they can b开发者_高级运维e accessed by different activities of the same application? Without having to serialize or parcel the object?
The 2 best ways for passing objects between activities is using a static field probably in a class that extends Application
, or (probably preferably) use a service and have your activities that need to share objects bind to it.
Be careful about using static fields in Activities
however, as they can be destroyed at any time and are thus not thread safe and potentially disastrous.
SharedPreferences
is the way to go. Put this in the activity
public void saveSetting(String settingName, String value){
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
Editor ed = pref.edit();
ed.putString(settingName, value);
ed.commit();
}
SharedPreference is only good for objects that SharedPreferences supports. For any long term storage of objects you will have to go down the serialized route of some sort. I am guessing you have read the Data Storage page in the docs. From there I would recommend you reading about Internal Storage. If you don't want to deal with Java's serializble interface then I suggest you check out XStream.
XStream coupled with Internal Storage may offer the solution you need.
If you are looking for a point of permanence maintaining a global application state without using serialization, databases etc, use a Service or the Application class. General tips on this issue found at android developers.
You can use SharedPreferences or create a Singleton class. I used singleton class to control the lifecycle of the attributes. If you want guaranteed persistance,store data in a sqllite db.
Using Singleton, you can store custom objects.
public class MySingleton {
private static final AlphResourceSet INSTANCE = new MySingleton ();
private MySingleton() {}
public static MySingleton getInstance() {
return INSTANCE;
}
// all your getters/setters for your variables
}
精彩评论