previously节省添加使用共享preferences一个ArrayList的项目时,再加入 [英] Previously added items are added again when saving an ArrayList using SharedPreferences

查看:108
本文介绍了previously节省添加使用共享preferences一个ArrayList的项目时,再加入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我有3个活动A,B和C.在活动A当按钮为pressed启动活动B和一个空的ArrayList是通过它使用putExtra来。在活动B,如果ArrayList是空的启动活动Ç这在ArrayList中增加了一个项目,并将其传递到活动B.活动B,则显示和ArrayList中。在活动B有​​哪些时pressed重新启动活动A.在活动A,显示ArrayList中的项目数的返回按钮,并在一个EditText为pressed,开始活动B.活动B现在显示ArrayList中的项目,因为ArrayList是不是空的。这工作正常,但一些奇怪的事情发生。当ArrayList中显示项目previous项目/ s的/在某种程度上得到再次添加。如果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.

下面是我的code的一部分:
在活动答:

Here is part of my code: In Activity A:

下面活动B开始。

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中的项目数和点击时开始活动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);
                    }

                }
            });
        }

    }
}

EditText上启动活动B时,ArrayList的大小> 0,否则,它开始活动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,其中包含的类型人的对象。
请帮我尽快解决这个问题。请让我知道是否需要更多的细节。

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.

推荐答案

一个previous评论:

A previous comment:

您不应该在变量名的开头使用大写字母。这是令人困惑,因为它看起来像一个类名,也可以带你到一些麻烦。您应该重命名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.

让我们进入您的问题。

林不知道如果我理解你的code,但我所看到的(看我的评析:)

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. 从A到B:你通过数组,并添加保存preferences的元素。

  2. 从B到A:保存所有要素共享preferences(现在你必须从阵列从A来的元素,也可以从共享preferences的previous元素,让您的共享preferences越大)

  3. 从A到B:你再次通过阵列,并增加了从更大的共享preferences的元素,这正如我们在2点看到,已经包含了所有的元素,也是成员组成的阵列,所以你正在复制它们。

这样想想你需要什么,可能你没有传递数组A和B之间,或者你没有将它保存到共享preferences,或者你必须检查你保存哪些项目。想想你真正需要的,问题是出在那些行

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

这篇关于previously节省添加使用共享preferences一个ArrayList的项目时,再加入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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