将更多值附加到“共享首选项”,而不是覆盖现有值

时间:2014-07-03 10:11:45

标签: android sharedpreferences

在我的应用程序中,我需要将值保存到Sharedpreferences文件RKs_Data中,而不会覆盖现有数据。每次,我在我的应用程序中单击“是”,我需要存储在“RKs_Data”中的所有值,而不是仅将最新的“name”和“phoneNo”输入到文件中。

  1. 是否可以通过SharedPreferences执行此操作?如果是,怎么样?
  2. 如果没有,那么下一步更好的选择是什么呢?
  3. 例如,

    • 当我第一次单击其中一个联系人(如'Brian')时,它会将SharedPreferences中的名称和手机保存为 Brian和99999299999,第一次保存在共享首选项文件'RKS_Data'
    • 当我点击其他联系人说'Monet'时,我的RKs_Data应如下所示:

      1. Brian 99999299999
      2. Monet 00010000000 等等....

    我搜索了但是到处都只提到了保存它,但没有关于附加或对数据做一些操作......

    请指导......

    代码段如下:

    -------
       public class RKsContacts_Main extends ListActivity {
    
        // private ListView listView;
        private List<ContactBean> list = new ArrayList<ContactBean>();
        SharedPreferences sp;
        File Fav_Contacts_file;
        String contact = null;
        List<String>  listOfFavoritePhrases = new ArrayList<String>();
    
        @SuppressWarnings("deprecation")
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.rks_contactslist_main);
            ListView listview = getListView();
    
            sp = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
    -------
    
    --------
    @Override
                public void onClick(DialogInterface dialog, int which) {
    
                    String serialized = sp.getString("phrases", null);
                    listOfFavoritePhrases = new ArrayList<String>(Arrays.asList(TextUtils.split(serialized, ","))); // Line 141
    
                    listOfFavoritePhrases.add(name);
                    listOfFavoritePhrases.add(phoneNo);  
    
                    SharedPreferences.Editor   editor = sp.edit();
                    editor.putString("phrases",TextUtils.join(",", listOfFavoritePhrases));
    
                    editor.commit();
    
                }
            });
            alert.show();
        }
    --------
    

    下面的LogCat:

    07-03 09:00:51.014: E/AndroidRuntime(9574): FATAL EXCEPTION: main
    07-03 09:00:51.014: E/AndroidRuntime(9574): Process: com.example.rkscontacts_list, PID: 9574
    07-03 09:00:51.014: E/AndroidRuntime(9574): java.lang.NullPointerException
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at android.text.TextUtils.split(TextUtils.java:332)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at com.example.rkscontacts_list.RKsContacts_Main$4.onClick(RKsContacts_Main.java:141)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at android.os.Handler.dispatchMessage(Handler.java:102)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at android.os.Looper.loop(Looper.java:136)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at android.app.ActivityThread.main(ActivityThread.java:5017)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at java.lang.reflect.Method.invokeNative(Native Method)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at java.lang.reflect.Method.invoke(Method.java:515)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    07-03 09:00:51.014: E/AndroidRuntime(9574):     at dalvik.system.NativeStart.main(Native Method)
    

3 个答案:

答案 0 :(得分:8)

请按照以下步骤操作:

提取SharedPreferences

中存储的值
String value = prefs.getString(<Key>, <DefaultValue>);

附加到提取的值

String appendedValue = append(value, newValue);

将结果写回SharedPreferences

editor.putString(<Key>, appendedValue).commit();

答案 1 :(得分:2)

您可以CSV格式化您的共享偏好数据。 例如,从共享首选项中获取CSV字符串并将其添加到列表中。附加到您的列表然后将其放回您的共享首选项中。代码示例

// init之前某处的字符串列表

List<String>  listOfFavoritePhrases = new ArrayList<String>();

//将数据附加到列表中

listOfFavoritePhrases.add("Brian|99999299999");
listOfFavoritePhrases.add("Monet|00010000000");

//以CSV格式

返回更改后的字符串列表
SharedPreferences prefs = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
            SharedPreferences.Editor   editor = prefs.edit();
            editor.putString("phrases",TextUtils.join(",", listOfFavoritePhrases));
            editor.commit();

//获取数据

     SharedPreferences prefs = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
    String serialized = prefs.getString("phrases", "Brian");
     listOfFavoritePhrases = new ArrayList<String>(Arrays.asList(TextUtils.split(serialized, ",")));

然后

String CurrentString = listOfFavoritePhrases.get(0); // first element
String[] separated = CurrentString.split("|");
Toast.makeText(this, separated[0], Toast.LENGTH_LONG).show(); // brian
Toast.makeText(this, separated[1], Toast.LENGTH_LONG).show(); // 99999299999

希望这有助于。

答案 2 :(得分:1)

最后我的代码如下所示:分享最终代码,因为它对像我这样的新手有用:)


protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rks_contactslist_main);
        ListView listview = getListView();

        sp = getSharedPreferences("PACKAGE", Context.MODE_PRIVATE);
        String str = sp.getString("FAV_CONTACS",
                "NO fav contacts are saved as of now");
---------

protected void onListItemClick(ListView listview, View view, int position,
            long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(listview, view, position, id);
        ContactBean bean = (ContactBean) listview.getItemAtPosition(position);

        showCallDialog(bean.getName(), bean.getPhoneNo());
    }


---------

    public void onClick(DialogInterface dialog, int which) {
                Fav_Contacts_file = getFilesDir();
                    if (count <5) {
                        SharedPreferences.Editor editor = sp.edit();

                        String new_contact = name + " " + phoneNo;


                        String existing_contact = sp.getString("CONTACTS", "");
                        /*String existing_phone = sp.getString("phoneNo", "");
                        String existing_contact = existing_name + " " +existing_phone ;*/


                        String latestfavContacts = append(existing_contact, new_contact);


                        editor.putString("CONTACTS", latestfavContacts);
                        editor.commit();
                        count++;
                        Toast.makeText(
                                getApplicationContext(),
                                "The data saved successfully to ........ : "
                                        + Fav_Contacts_file + "/PACKAGE",
                                Toast.LENGTH_SHORT).show();
                        Toast.makeText(
                                getApplicationContext(),
                                "Name : " + name + " and Phone : "
                                        + phoneNo, Toast.LENGTH_SHORT)
                                .show();
                    }
                    else {
                        Toast.makeText(
                                getApplicationContext(),
                                "More than 5 Fav Contacts are NOT allowed",                                     
                                Toast.LENGTH_SHORT).show();
                    }

                }
            });
            alert.show();
        }

        protected String append(String existing_contact, String new_contact) {
            String latestfavContacts = existing_contact + " | "+ new_contact ;
            return latestfavContacts;
        }

以及存储在SharedPreference文件中的数据&#39; PACAKAGE&#39;看起来像这样:

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
-<map>
<string name="CONTACTS"> | Alen 1 231-231-231 | Alex Zun 1 234-321-231 | Dr. S.K. Taher Ali 040-7265587 | Gazer 1 312-345-452 | Helen (432) 341-1343</string>
</map>

我还没有处理格式化,并根据我的应用需求将其呈现为UI友好模式。