Previously added items are added again when saving an ArrayList using SharedPreferences

丶灬走出姿态 提交于 2019-12-12 00:28:40

问题


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.

Here is part of my code: In Activity A:

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 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);
                    }

                }
            });
        }

    }
}

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();
}

In onPause the ArrayList's value is saved.

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.


回答1:


A previous comment:

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.

Lets get into your problem.

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();
}

So what you are doing,

  1. from A to B: you pass the array and add the elements in saved preferences.
  2. from B to A: save all the elements to shared preferences (now you have the elements from the array coming from A, and also the previous elements from shared preferences, so your shared preferences is bigger)
  3. from A to B: you pass the array again, and adds the elements from that bigger sharedpreferences, that as we saw in point 2, already contains all the elements, also the ones form the array, so you are duplicating them.

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



来源:https://stackoverflow.com/questions/20943651/previously-added-items-are-added-again-when-saving-an-arraylist-using-sharedpref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!