如何在共享首选项的列表项中保存“项目”?

时间:2013-11-19 09:53:49

标签: android listview sharedpreferences

我有以下列表。是否可以在listview中以共享首选项保存“项目”并再次将其检索回创建?这样做的原因是检索listview的状态,该状态在重启电话时变为空白。以下是我的清单项目代码:

    public class LogListView extends ListActivity {
    /** Called when the activity is first created. */
    private static String newString;
    private static EntryAdapter adapter;
    int clickCounter = 0;
    static ArrayList<Item> items = new ArrayList<Item>();
    static SharedPreferences preferences = null;
    private static Context context = null;
    static StringTokenizer tokens;
    private static String first;
    private static String second;
    private Gson gson;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;
        adapter = new EntryAdapter(this, items);
        // items.add(new SectionItem("Log Report"));
        setListAdapter(adapter);

        if (adapter.getCount() != 0) {
            // Do nothing Adapter has value
        } else {
            Toast.makeText(LogListView.this, "No Items Available",Toast.LENGTH_SHORT).show();
            //Get Saved ListItems
        }

    }

    // Method which will handle dynamic insertion
    public static void addItems() {

        preferences = context.getSharedPreferences("LOG",android.content.Context.MODE_PRIVATE);
        newString = preferences.getString("log", "");

        tokens = new StringTokenizer(newString, ",");
        first = tokens.nextToken();
        second = tokens.nextToken();

        items.add(new EntryItem(first, second));
        adapter.notifyDataSetChanged();

    }
    // Method which will handle dynamic insertion ends

    // Save ListItems if restarted 
    protected void saveList(){
        String value = gson.toJson(items);
        SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
        Editor e = prefs.edit();
        e.putString("list", value);
        e.commit();
    }
    // Save ListItems if restarted ends

    // Retreive ListItems if restarted
    protected void retriveList(){
    SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
    String value = prefs.getString("list", null);

    GsonBuilder gsonb = new GsonBuilder();
    Gson gson = gsonb.create();
    MyObject[] list = gson.fromJson(value, MyObject[].class);
    }
    // Retreive ListItems if restarted ends

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {

        if (!items.get(position).isSection()) {

            items.get(position);
            // Toast.makeText(this, "You clicked " + item.title ,
            // Toast.LENGTH_SHORT).show();
            Toast.makeText(this, "You clicked " + position, Toast.LENGTH_SHORT)
                    .show();

        }

        if (position == 9) {

        }

        super.onListItemClick(l, v, position, id);
    }
}

2 个答案:

答案 0 :(得分:2)

我发现存储和检索SharedPreferences中的项目列表的最简单的解决方案是简单地将数组序列化/去除JSON中的数据并将其存储到字符串设置中。

Gson 非常方便。

READ:

SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
String value = prefs.getString("list", null);

GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
MyObject[] list = gson.fromJson(value, MyObject[].class);

WRITE:

String value = gson.toJson(list);
SharedPreferences prefs = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
Editor e = prefs.edit();
e.putString("list", value);
e.commit();

答案 1 :(得分:0)

使用以下示例代码初始化共享首选项中的列表值

private static ArrayList<String> DROP_BOX_IMAGES_PATH_LIST11;
private static String HAS_INITIALIZED_DROPBOX = "HAS_INITIALIZED_DROPBOX11";
private static String DROP_BOX_IMAGES_SHARED_PREF = "DROP_BOX_IMAGES_SHARED_PREF11";
private static String DROP_BOX_CURSOR="DROP_BOX_CURSOR11";
private static String HAS_INITIALIZED_DROP_BOX_CURSOR="HAS_INITIALIZED_DROP_BOX_CURSOR11";
private static String IS_LOGGED_IN="IS_LOGGED_IN";

public static void initializePathList(Context context) {
    if (context == null)
        return;

    SharedPreferences prefs = context.getSharedPreferences(
            MY_APP_SHARED_PREF, 0);
    SharedPreferences.Editor editor=prefs.edit();
    String HAS_DROP_BOX_IMAGES = prefs.getString(
            App.HAS_INITIALIZED_DROPBOX, "false");
    if (!HAS_DROP_BOX_IMAGES.equals("true")) {
        //createDropBoxImagePathList(context,images);
        editor.putString(App.HAS_INITIALIZED_DROPBOX, "true");
        editor.commit();
    }

}

public static void createPathList(Context context, ArrayList<String> pathList) {
    SharedPreferences prefs = context.getSharedPreferences(MY_APP_SHARED_PREF, 0);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("PathListSize", pathList.size());
    for (int i = 0; i < pathList.size(); i++) {
        editor.putString("path" + i, pathList.get(i));
    }
    editor.commit();


}   
public static void updatePathList(Context context,ArrayList<String> newPaths){
    SharedPreferences prefs=context.getSharedPreferences(MY_APP_SHARED_PREF, 0);
    SharedPreferences.Editor editor=prefs.edit();
    int size=prefs.getInt("PathListSize", 0);
    for(int i=0;i<(newPaths.size());i++){   
        editor.putString("path"+(size+i),newPaths.get(i) );
    }
    editor.putInt("PathListSize", (size+newPaths.size()));
    editor.commit();

    //new path testint
    Log.i("new list path App2","new list path app"+prefs.getInt("PathListSize", 0));        
}

public static void reInitializePathList(Context context,ArrayList<String> newPaths){
    SharedPreferences prefs=context.getSharedPreferences(MY_APP_SHARED_PREF, 0);
    SharedPreferences.Editor editor=prefs.edit();
    int size=prefs.getInt("PathListSize", 0);
    //for(int i=0;i<(size+newPaths.size());i++){
    for(int i=0;i<(newPaths.size());i++){   
        editor.putString("path"+(i),newPaths.get(i) );
        //Log.d("index testing","index="+(size+i)+newPaths.get(i));
    }
    //editor.remove("PathListSize");
    editor.putInt("PathListSize", (size+newPaths.size()));
    editor.commit();

    //new path testint
    Log.i("new list path App2","new list path app"+prefs.getInt("PathListSize", 0));

}
public static ArrayList<String> loadPathList(Context context){
    SharedPreferences prefs=context.getSharedPreferences(MY_APP_SHARED_PREF,0);
    ArrayList<String> pathList=new ArrayList<String>();
    int size=prefs.getInt("PathListSize", 0);
    Log.i("path list size from App2","path list size from App2"+size+"-------------");
    for(int i=0;i<size;i++){
        pathList.add(prefs.getString("path"+i,""));
    }
    return pathList;
}

public static void removePathList(Context context,ArrayList<String> pathList) {
    SharedPreferences prefs = context.getSharedPreferences(
            MY_APP_SHARED_PREF, 0);
    SharedPreferences.Editor editor = prefs.edit();
    int size = prefs.getInt("PathListSize", 0);
    //int size=pathList.size();
    for (int i = 0; i < size; i++) {
        editor.remove("path" + i);
    }
    editor.putInt("PathListSize", 0);
    editor.commit();

    //new path testint
            Log.i("after remove list path App2","new list path app"+prefs.getInt("PathListSize", 0));
}