Pregunta

I have some information that needs to be stored in internal memory. I will like to store in the form of key-value pairs the way its done in SharedPreferences. I was thinking of creating JsonObject and saving and retrieving in that way. Is there any other way that we can save the data in internal memory in the form of key-value pairs?

¿Fue útil?

Solución

Th standard java way of storing Object data is to use Serialization - that is what it is there for. In Most cases implementing Serializable is fairly straight forward. This Site offers a good tutorial on Serialization basics, which can be tailored to the Android environment quite easily.

By creating a HashMap you can Serialize the HashMap to file for easy retrieval of your data in key/value form. Pretty much all library Collections support Serializable so you can also store other types of Map/List.

So which to use - Serialization or JSONObject? This really depends on how important efficiency is and how complex the things you want to store are.

Generally the largest cost in either case is the actual act of writing data to file, so, as JSONObjects will nearly always be smaller and simpler, they may be a little quicker. This is fine for storing Strings or very Simple Objects that can be turned to JSON easily, If you have a very complex class with dozens of members, and many possible states, it may be simpler and as efficient to use Serialization. The actual cost difference between these options in most cases will be negligible and would only really matter if you had to preform reads and writes many many times.

So use JSON for basic types and serialization for complex types (you can even store a serialized object in a JSON Object!)

Otros consejos

A very basic SQLiteDatabase will do the Job. There's oodles of tutorials out there and all you need is a single table with 3 columns: _id, key, value.

I have personally found This Tutorial a great starting point.

DB's always need a context to get the ball rolling, so for a simple get/set situation like this, creating a small class with the following method signatures will make life real easy:

public static void set(Context context, String key, String value);
public static String get(Context context, String key);

For more complex objects, use Parcelable or Serialization:

public static void set(Context context, String key, Serializable value);
public static Serializable(Context context, String key); 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top