1

Scenario: I am sending user location (Object location with: lat, long and accuracy fields) to a web service from a Thread in a Service. If it fails because of various issues (like no network) I need to store it and try to send it next time. If it fails multiple times, multiple Location objects are stored.

I have 2 choices:

  1. Use SQLite database and an SQLiteOpenHelper which on each thread is open, retrieve records from the table, close. On successfully sending it, clear the table content.

  2. Use SharedPreferences while the location object is stored as an ArrayList (in case there are many) parsed to JSON with GSON. When needed parsed again to ArrayList.

I know that SharedPreferences has no size limit and depending on my conditions I could have like 100 rows (this is exaggerated but possible). My main concern is on SQlite having it open and closed so often, things might get messed up and end in force close. SharedPreferences would not interfere with anything but I am thinking I might get bad performance in saving/parsing such long lists. I know that SharedPreferences aren't made for this, but I want to hear opinions from you.


If you are worried about sqlite throwing exception for open and close database, you can put values in SharedPreference individually and then can iterate through all the values of SharedPreferences using

Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
     Log.d("map values",entry.getKey() + ": 
                                  "+ entry.getValue().toString());            
 }
4

1 回答 1

1

如果您担心 sqlite 在打开和关闭数据库时抛出异常,您可以将值单独放入 SharedPreference 中,然后可以遍历SharedPreferencesusing的所有值

Map<String,?> keys = prefs.getAll();
for(Map.Entry<String,?> entry : keys.entrySet()){
     Log.d("map values",entry.getKey() + ": 
                                  "+ entry.getValue().toString());            
 }
于 2012-07-11T11:03:27.497 回答