Android 如何在SharedReferences中保存堆栈

Android 如何在SharedReferences中保存堆栈,android,android-activity,bundle,Android,Android Activity,Bundle,我有一些书堆,想用它来保存它们。只有一些基本的东西可以放在SharedReferences中。还有什么简单的方法可以保存复杂的/自定义的数据结构吗?使用,您可以轻松地将自定义对象保存到SharedReferences 保存: 负载: 使用,您可以轻松地将自定义对象保存到SharedReferences 保存: 负载: 你可以和马库斯一起回答。以下是我在我的项目中所做的: 存储在共享首选项中: SharedPreferences prefs = PreferenceManager.g

我有一些书堆,想用它来保存它们。只有一些基本的东西可以放在SharedReferences中。还有什么简单的方法可以保存复杂的/自定义的数据结构吗?

使用,您可以轻松地将自定义对象保存到
SharedReferences

保存:

负载:

使用,您可以轻松地将自定义对象保存到
SharedReferences

保存:

负载:


你可以和马库斯一起回答。以下是我在我的项目中所做的:

存储在共享首选项中:

       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor edit = prefs.edit();

        Gson gson = new Gson();
          String json = gson.toJson(MyImages);
          edit.putString("MyImages", json);
     Gson gson = new Gson();
     String json = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("MyImages", "");
     ArrayList<String> MyImages= new ArrayList<String>();
     MyImages=gson.fromJson(json, ArrayList.class);
从共享首选项检索:

       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor edit = prefs.edit();

        Gson gson = new Gson();
          String json = gson.toJson(MyImages);
          edit.putString("MyImages", json);
     Gson gson = new Gson();
     String json = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("MyImages", "");
     ArrayList<String> MyImages= new ArrayList<String>();
     MyImages=gson.fromJson(json, ArrayList.class);

你可以和马库斯一起回答。以下是我在项目中所做的:

存储在共享首选项中:

       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor edit = prefs.edit();

        Gson gson = new Gson();
          String json = gson.toJson(MyImages);
          edit.putString("MyImages", json);
     Gson gson = new Gson();
     String json = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("MyImages", "");
     ArrayList<String> MyImages= new ArrayList<String>();
     MyImages=gson.fromJson(json, ArrayList.class);
从共享首选项检索:

       SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        SharedPreferences.Editor edit = prefs.edit();

        Gson gson = new Gson();
          String json = gson.toJson(MyImages);
          edit.putString("MyImages", json);
     Gson gson = new Gson();
     String json = PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("MyImages", "");
     ArrayList<String> MyImages= new ArrayList<String>();
     MyImages=gson.fromJson(json, ArrayList.class);

正如马库斯在他的回答中所建议的那样,您唯一的选择是将数据结构转换为
字符串形式的东西:JSON、XML等。
SharedReferences
并不是真正的通用数据存储系统——为此,请使用数据库或其他类型的文件。正如马库斯在回答中所建议的,唯一的选择是将数据结构转换成
字符串
:JSON、XML等格式。
SharedReferences
并不是真正的通用数据存储系统——为此,请使用数据库或其他类型的文件。