使用 SharedPreferences 保存 ArrayList 时再次添加先前添加的项目 [英] Previously added items are added again when saving an ArrayList using SharedPreferences

查看:23
本文介绍了使用 SharedPreferences 保存 ArrayList 时再次添加先前添加的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有 3 个活动 A、B 和 C.在活动 A 中,当按下按钮时,它会启动活动 B,并使用 putExtra 将空数组列表传递给它.在 Activity B 中,如果 arraylist 为空,它将启动 Activity C,后者在 ArrayList 中添加一个项目并将其传递给 Activity B.然后 Activity B 显示和 arraylist.在活动 B 中,有一个后退"按钮,按下该按钮会重新启动活动 A.在活动 A 中,显示数组列表中的项目数,按下 EditText 时,将启动活动 B.活动 B 现在显示项目中的项目ArrayList 因为 ArrayList 不为空.这工作正常,但发生了一些奇怪的事情.当显示 ArrayList 中的项目时,前一个项目以某种方式再次添加.如果 ArrayList 有 1 个项目,它工作正常.但是当添加 2 个或更多时,某些项目会以某种方式添加不止一次并且可以是任何随机数.当我在活动 A 和活动 B 之间移动时,尺寸不断增加.

In my app I have 3 activities A,B and C. In Activity A when a button is pressed it starts Activity B and an empty arraylist is passed to it using putExtra. In Activity B, if the arraylist is empty it starts Activity C which adds an item in the ArrayList and passes it to Activity B. Activity B then displays and the arraylist. In Activity B there is a 'back' button which when pressed restarts the Activity A. In Activity A, the number of items in the arraylist is displayed and when an EditText is pressed, starts Activity B. Activity B now shows the items in the ArrayList since the ArrayList is not empty. This works fine but something strange happens. When displaying the items in the ArrayList the previous item/s is/are somehow getting added again. If the ArrayList has 1 item it works fine. But when 2 or more are added, somehow some items are added more than once and can be any random number. The size keeps increasing when I travel between Activity A and B.

这是我的代码的一部分:在活动 A 中:

Here is part of my code: In Activity A:

此处 Activity B 在单击按钮 btn_rec 时启动.

Here Activity B is started when button btn_rec is clicked.

btn_rec = (ImageButton) findViewById(R.id.btn_rec);
    btn_rec.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent rec_Intent = new Intent(FlipCardActivity.this,
                    RecipientsActivity.class);
            rec_Intent.putExtra("RecArray", RecipientArray);
            startActivityForResult(rec_Intent, NO_OF_RECIPIENTS);

        }
    });

EditText 显示 ArrayList 中的项目数,点击时启动 Activity B.

EditText displays the number of items in the ArrayList and when clicked starts Activity B.

protected void onActivityResult(int requestCode, int resultCode, Intent data) {     
    super.onActivityResult(requestCode, resultCode, data);
if (requestCode == NO_OF_RECIPIENTS && resultCode == RESULT_OK) {
        RecipientArray = (ArrayList<Person>) data.getSerializableExtra("RecArray");

        if (RecipientArray.size() > 0) {
edt_rec.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    Log.e("In edt onclick", "Hello");
                    if (RecipientArray.size() == 0) {
                        Intent new_rec_Intent = new Intent(
                                FlipCardActivity.this,
                                RecipientAddressActivity.class);
                        startActivity(new_rec_Intent);
                    } else {
                        Intent rec_Intent = new Intent(
                                FlipCardActivity.this,
                                RecipientsActivity.class);
                        rec_Intent.putExtra("RecArray", RecipientArray);
                        startActivityForResult(rec_Intent, NO_OF_RECIPIENTS);
                    }

                }
            });
        }

    }
}

当 ArrayList 的大小 >0 时,EditText 启动 Activity B,否则它启动 Activity C.在活动 B 中:

EditText starts Activity B when size of ArrayList is >0 else it starts Activity C. In activity B:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    RecipientArray = (ArrayList<Person>) getIntent().getSerializableExtra(
            "RecArray");

    Log.e("Recipient Array", "size = " + RecipientArray.size());
    if (RecipientArray.size() == 0) {
        Intent rec_addr_Intent = new Intent(RecipientsActivity.this,
                RecipientAddressActivity.class);
        rec_addr_Intent.putExtra("RecArray", RecipientArray);
        startActivityForResult(rec_addr_Intent, REC_INFO);
    } else {

        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        int size = prefs.getInt("size", 0);
        for (int i = 0; i < size; i++) {
            String json = prefs.getString("RecList_" + i, "");
            Gson gson = new Gson();
            Person p = gson.fromJson(json, Person.class);
            RecipientArray.add(p);
        }
        // Log.e("RecListActivity","Size of arraylist"+RecipientArray.size());


        this.m_adapter = new CustomListAdapter(RecipientsActivity.this,
                R.layout.recipients_list, RecipientArray);

    }

    setContentView(R.layout.activity_recipients);
    list = (ListView) findViewById(R.id.rec_list);
    list.setAdapter(m_adapter);
    addListenerForButtons();
}

protected void onPause() {      
    super.onPause();
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    Editor editor = prefs.edit();
    Gson gson = new Gson();
    // String json = gson.toJson(RecipientArray);
    for (int i = 0; i < RecipientArray.size(); i++) {
        String json = gson.toJson(RecipientArray.get(i));
        editor.putString("RecList_" + i, json);
        editor.putInt("size", i);
    }

    editor.apply();
}

在 onPause 中,ArrayList 的值被保存.

In onPause the ArrayList's value is saved.

ArrayList 是RecipientArray",其中包含Person"类型的对象.请尽快帮我解决这个问题.如果需要更多详细信息,请告诉我.

The ArrayList is 'RecipientArray' which contains Objects of type 'Person'. Kindly, help me solve this problem asap. Please let me know if more details are required.

推荐答案

上一条评论:

您不应该在变量名的开头使用大写字母.它令人困惑,因为它看起来像一个类名,而且它可能会给你带来一些麻烦.你应该在任何地方将你的 RecipientArray 重命名为recipientArray.

You shouldn't use an uppercase letter at the begining of a variable name. It is confusing, since it looks like a class name, and also it can lead you to some troubles. You should rename your RecipientArray to recipientArray everywhere.

让我们进入您的问题.

我不确定我是否理解你的代码,但我能看到什么(看看我的评论:)

Im not sure if I understand your code, but what i can see (look at my coments:)

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //here you retrieve the array coming from Activity A

            RecipientArray = (ArrayList<Person>) getIntent().getSerializableExtra(
            "RecArray");
    if (RecipientArray.size() == 0) {
               ///...
    } else {
        //here, you add to the array, all the preferences from the array
        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this.getApplicationContext());
        int size = prefs.getInt("size", 0);
        for (int i = 0; i < size; i++) {
            String json = prefs.getString("RecList_" + i, "");
            Gson gson = new Gson();
            Person p = gson.fromJson(json, Person.class);
            RecipientArray.add(p);
        }
        // ...
    }
}

//here, when the activity is going to be closed, you save all the items in the array to the sharedpreferences
protected void onPause() {      
    super.onPause();
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this.getApplicationContext());
    Editor editor = prefs.edit();
    Gson gson = new Gson();
    // String json = gson.toJson(RecipientArray);
    for (int i = 0; i < RecipientArray.size(); i++) {
        String json = gson.toJson(RecipientArray.get(i));
        editor.putString("RecList_" + i, json);
        editor.putInt("size", i);
    }

    editor.apply();
}

所以你在做什么,

  1. 从 A 到 B:您传递数组并在保存的首选项中添加元素.
  2. 从 B 到 A:将所有元素保存到共享首选项(现在您拥有来自 A 的数组元素,以及来自共享首选项的先前元素,因此您的共享首选项更大)
  3. 从 A 到 B:您再次传递数组,并添加来自更大共享首选项的元素,正如我们在第 2 点中看到的那样,已经包含所有元素,也是构成数组的元素,因此您正在复制它们.

所以想想你需要什么,可能你不必在A和B之间传递数组,或者你不必保存它到共享首选项,或者你必须检查你保存了什么项目.想想你真正需要什么,问题就在那些行

so think about what do you need, probably you dont have to pass the array between A and B, or you dont have to save it to Shared preferences, or you have to check what items do you save. Think about what you really need, the problem is in those lines

这篇关于使用 SharedPreferences 保存 ArrayList 时再次添加先前添加的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆