Android Saving data in the application

Is there any way in android to save objects in the place where various actions of the same application can be accessed to them? Without the need to serialize or send an object?

+4
source share
5 answers

The two best ways to pass objects between actions are to use a static field, probably in a class that extends Application or (possibly, preferably) with a service and has its own actions that objects must bind to them.

Use caution when using static fields in Activities , as they can be destroyed at any time and thus are not thread safe and potentially catastrophic.

+1
source

SharedPreferences is the way to go. Put it in action

  public void saveSetting(String settingName, String value){ SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this); Editor ed = pref.edit(); ed.putString(settingName, value); ed.commit(); } 
0
source

SharedPreference is only suitable for objects supported by SharedPreferences. For any long-term storage of objects you have to go along a serialized route. I assume that you read the Data Warehouse page in the documents . From there, I would recommend that you read Internal Storage . If you do not want to deal with the Java serializble interface, I suggest you check out XStream .

XStream combined with internal storage can offer the solution you need.

0
source

If you are looking for persistence in maintaining the state of a global application without using serialization, databases, etc., use the Service or Application class. General tips on this issue are found in Android developers .

0
source

You can use SharedPreferences or create a Singleton class. I used a singleton class to manage the attribute lifecycle. If you want guaranteed storage, store the data in sqlite 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 } 
0
source

Source: https://habr.com/ru/post/1334093/


All Articles