【问题标题】:How do I save an arraylist of custom objects so that when my android app is closed/restarted the arraylist stays the same如何保存自定义对象的数组列表,以便当我的 android 应用程序关闭/重新启动时,数组列表保持不变
【发布时间】:2014-07-29 19:00:08
【问题描述】:

我有一个“游泳者”对象的数组列表,我不希望每次应用关闭时都将其删除。我已经阅读了有关序列化和使用共享首选项的信息,但我不知道在哪里编写该代码或它的作用。

arraylist 目前作为公共变量存储在主活动类中,其他活动可以访问它。

public ArrayList<Swimmer> allSwimmers = new ArrayList<Swimmer>();

这是我使用列表视图显示列表中所有游泳者的活动,当单击其中一个游泳者时,它会转到一个新活动以显示游泳者信息。

一切都很好,我只想将“MyActivity.allSwimmers”(数组列表)保存在应用程序关闭并重新启动时它不是空白的地方

public class AllSwimmers extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_swimmers);

        ListAdapter theAdapter = new ArrayAdapter<Swimmer>(this, android.R.layout.simple_list_item_1,
            MyActivity.allSwimmers);

        ListView theListView = (ListView) findViewById(R.id.allSwimmersList);

        theListView.setAdapter(theAdapter);

        theListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Intent goToIndiv = new Intent(AllSwimmers.this, IndivSwimmer.class);

                final int result = 1;

                goToIndiv.putExtra("position", position);

                startActivityForResult(goToIndiv, result);
            }
        });
    }
}

【问题讨论】:

标签: java android arraylist


【解决方案1】:

为此,您必须将数据保存在 SQLiteDatabase 中。这是一个很棒的教程:

http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

【讨论】:

  • 认为使用 SharedPreferences 方法更好
【解决方案2】:

通常,为了能够将自定义数据对象存储到内存中,您想要做的是使它们可序列化。

您必须记住,运行应用程序范围之外的持久性数据需要映射到物理内存中。换句话说:

(至于)序列化您的数据结构/对象,意味着将其分解为可以存储的格式。 当然,序列化的另一个方面是能够将这些序列化的数据从内存中作为易失性对象/结构再次提取到您的环境中。

在 Java 中,这一切都是通过将自定义数据附加到 Serializable 接口来完成的。然而,由于我们正在讨论 Android,因此更建议坚持 Parcelable 接口(更好的速度、效率和安全性管理数据)

因此,起初,似乎没有其他合理的方式来完成您的要求,而不是通过 Swimmer 的序列化(使用 Parcelable 接口)以一种或另一种方式......

这是一个使用 Parcelable 对 POJO 进行数据建模的简单示例:

public class Profile implements Parcelable {

        private String id;
        private String name;
        private String category;


        public Profile(String id, String name, String category){
            this.id = id;
            this.name = name;
            this.category = category;
       }

       public Profile(Parcel in){
           String[] data = new String[3];

           in.readStringArray(data);
           this.id = data[0];
           this.name = data[1];
           this.category = data[2];
       }

       @Оverride
       public int describeContents(){
           return 0;
       }

       @Override
       public void writeToParcel(Parcel dest, int flags) {
           dest.writeStringArray(new String[] {this.id,this.name,this.category});
       }
       public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
           public Profile createFromParcel(Parcel in) {
               return new Profile(in); 
           }

           public Profile[] newArray(int size) {
               return new Profile[size];
           }
       };
   }

“问题”是,如果你想使用 SharedPreferences,它没有内置对 Parcelable 的支持,也没有任何其他形式的序列化数据映射协议,因为它仅用于设计的原始键/值映射。 (SharedPreferences 旨在存储需要持久性的应用配置值,例如声音开/关、凭据等,而不是大型数据堆)。

但是,出于方便使用 JSON 存储自定义数据对象的目的,使用 SharedPreferences 有一个相当巧妙的“解决方法”。当然,最大的优势是 JSON 数据很容易序列化为 String 原语。

使用默认 JSON api (org.json),您可以使自己的解析/转换函数对任何类型的 POJO 数据都有效。 JSON 数据管理有许多不同的 api,并且有无数种轻松操作它的方法。这是嵌套 json 数组的基本示例:

SharedPreferences prefs = this.getSharedPreferences("MyCustomDataPreferences", Context.MODE_PRIVATE);

/* Assuming this JSON from SharedPreferences: "{animals : [{familyKey:Dogs},
  {familyKey:Cats}, {familyKey:Lizards}]}" */

//Notice how JSONObject just takes a String as an argument:

JSONObject obj = new JSONObject(prefs.getString("animalsJSON", null));

List<String> list = new ArrayList<String>();
JSONArray array = obj.getJSONArray("animals");

//Store into list all values with key "familyKey":

for(int i = 0 ; i < array.length() ; i++){
    list.add(array.getJSONObject(i).getString("familyKey"));
}

如您所见,通过这种方式,您可以简单地将字符串值存储为 JSON 对象,然后使用内置的 SharedPreferences 将它们恢复为 java 对象以供使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2012-09-15
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多