简体   繁体   English

SharedPreferences 会覆盖其他值吗?

[英]SharedPreferences overwrite other value?

I am new in android.here i make simple contacts list app.我是 android.here 的新手,我制作了简单的联系人列表应用程序。 when user click on contact items, contact add in favorite list.当用户单击联系人项目时,联系人添加到收藏夹列表中。 but problem is that when user click on first contact item to add favorite,then user click second contact,but first item was remove automatically.但问题是,当用户单击第一个联系人项目添加收藏时,然后用户单击第二个联系人,但第一个项目被自动删除。 Shared Preferences overwrite other value,i want to add item in list so what i do to add contacts in favorite List.共享首选项覆盖其他值,我想在列表中添加项目,所以我如何在收藏夹列表中添加联系人。

First Fragment:第一段:

imageViewfavourite.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                SharedPreferences.Editor editor = preferences.edit();

                editor.putString("name1", Pname);
                editor.putString("number1", Pnumber);
                editor.putString("image1", temp);
                editor.putInt("pos", position);

                Log.e("a", "name1" + Pname);
                Log.e("a", "number1" + Pnumber);
                Log.e("a", "image1" + temp);

                editor.commit();

            }
        });

Second Fragment:第二个片段:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_fragment_fv, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.favourite_list);
selectUsers = new ArrayList<DataContact>();

SharedPreferences preferences = getActivity().getPreferences(0);
String Pname = preferences.getString("name1", "");
String Pnumber = preferences.getString("number1", "");
String Pimage = preferences.getString("image1", "");

byte[] encodeByte = Base64.decode(Pimage, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);

Log.v("name1", Pname);
Log.v("number1", Pnumber);
Log.v("image1", Pimage);

DataContact selectUser = new DataContact();
selectUser.setName(Pname);
selectUser.setPhone(Pnumber);
selectUser.setThumb(bitmap);
selectUsers.add(selectUser);

adapter = new AdapterFv(getActivity(), "");
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
llm.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(llm);
adapter.setData(selectUsers);
recyclerView.setAdapter(adapter);

return view;
}

Check the api documentation before asking question.在提问之前检查api 文档

Explain解释

SharedPreferences is supported store data ( 1:1 key-value match ) therefore, a key can have only one data item. SharedPreferences支持存储数据(1:1 键值匹配),因此,一个键只能有一个数据项。

Storable Types可存储类型

  • boolean布尔值
  • float漂浮
  • int整数
  • long
  • String细绳
  • Set<String>设置<字符串>

Simple Solution简单的解决方案

// in Second Fragment 
String Pname = preferences.getString("name2", "");
String Pnumber = preferences.getString("number2", "");
String Pimage = preferences.getString("image2", "");

Reference参考

https://developer.android.com/reference/android/content/SharedPreferences.html https://developer.android.com/reference/android/content/SharedPreferences.html

in shared preference, you are putting value and editing value via KEY if you use the same key that will overwrite your value.在共享首选项中,如果您使用将覆盖您的值的相同键,则您将通过 KEY 放置值和编辑值。 because shared preference containing KEY VALUE pair if you want to store the data use SQLite database.因为如果您想使用 SQLite 数据库存储数据,则包含 KEY VALUE 对的共享首选项。 Shared Preference can hold onlysingle value for each key共享首选项只能为每个键保存一个值

You are adding the second contact with the same keys that you used for first contact.您正在添加第二个联系人,其密钥与您用于第一次联系人的密钥相同。 What you need is some sort of counter that keeps track of the number of contacts you have saved and then modifies your keys accordingly.您需要的是某种计数器来跟踪您保存的联系人数量,然后相应地修改您的密钥。

If I am not wrong then you are using如果我没有错,那么你正在使用

position位置

as the counter.作为柜台。 You just need to modify the keys.您只需要修改密钥。 A good solution would be to make separate methods to write and extract contact from shared preferences.一个好的解决方案是使用单独的方法来编写和从共享首选项中提取联系人。

public void writeContact(String Pname, String Pnumber, String temp,int position)
{
     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            SharedPreferences.Editor editor = preferences.edit();

            editor.putString("name"+position, Pname);
            editor.putString("number"+position, Pnumber);
            editor.putString("image"+position, temp);

            editor.commit();
}


public DataContact getContact(int position)
{
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());

    DataContact selectUser = new DataContact();

    selectUser.setName(preferences.getString("name"+position, ""));
    selectUser.setPhone( preferences.getString("number"+position, ""));
    selectUser.setThumb(preferences.getString("image"+position, ""));

    return selectUser;
}

This should do it.这应该这样做。 Now to save your contact you need to call writeContact method in the onClick().现在要保存您的联系人,您需要在 onClick() 中调用 writeContact 方法。 Similarly you can call getContact() with position as parameter to get the contacts.同样,您可以使用位置作为参数调用 getContact() 来获取联系人。

Better way would be to use database.But if you want to use SharedPreferences to save your data you can create Serializable class User and class Preference for managing your SharedPreferences as @AmitBhati said.更好的方法是使用数据库。但是如果你想使用 SharedPreferences 来保存你的数据,你可以创建 Serializable 类 User 和类 Preference 来管理你的 SharedPreferences 正如@AmitBhati所说。

    public class Preference {

    private static final String USER_JSON = "user_json";

    private SharedPreferences mSettings;
    private Context ctx;

    public Preference(Context context) {
        ctx = context;
        mSettings = PreferenceManager.getDefaultSharedPreferences(context);
    }

    public void setUsersJson(List<User> u){
        Gson gson = new Gson();
        String jsonStr = gson.toJson(u);
        SharedPreferences.Editor editor = mSettings.edit();
        editor.putString(USER_JSON, jsonStr);
        editor.apply();
    }
    public List<User> getUsersJson(){
        Gson gson = new Gson();
        String jsonStr = mSettings.getString(USER_JSON, null);
        Type listType = new TypeToken<List<HourlyWeather>>(){}.getType();
        return (List<User>) gson.fromJson(jsonStr, listType);
    }
}

I am using Shared preference as well and had doubt on the same topic, does it get over written.我也在使用共享偏好并且对同一主题有疑问,它是否被覆盖。 Your problem seems a bit different than mine considering the size of contact list, what i used was created a separate function in which i will be sending key value eg:key_val_, now since there will be 'n' contacts use for loop and add it with the above string.考虑到联系人列表的大小,您的问题似乎与我的有点不同,我使用的是创建了一个单独的函数,我将在其中发送键值,例如:key_val_,现在因为将有 'n' 个联系人用于循环并添加它用上面的字符串。

String string=key_val_;字符串字符串=key_val_;

for(int i=0;i < n; i++){ for(int i=0;i < n; i++){

editor.putInt(string+i, ur_value); editor.putInt(string+i, ur_value); } }

Not sure if it cause memory problems in your case.不确定它是否会导致您的情况出现内存问题。

Generally, Shared Preferences is used for small data and also in your app not store the big data.Every key keeps one value in Shared Preferences.通常,共享首选项用于小数据,并且在您的应用程序中不存储大数据。每个键在共享首选项中保留一个值。 Possibly, you can change "name" key to "name1" if the "name" key store some data but it is not easy and hard to handle exception.可能,如果“name”键存储一些数据,您可以将“name”键更改为“name1”,但处理异常并不容易和困难。 You can use Sqlite and it is more easy to control data with queries.您可以使用 Sqlite,通过查询更容易控制数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM