gpt4 book ai didi

java - SharedPreferences 会覆盖其他值吗?

转载 作者:行者123 更新时间:2023-11-30 06:54:40 24 4
gpt4 key购买 nike

我是 android 新手。这里我制作了简单的联系人列表应用程序。当用户单击联系人项目时,联系人会添加到 Collection 夹列表中。但问题是,当用户单击第一个联系人项目添加 Collection 夹时,然后用户单击第二个联系人,但第一个项目被自动删除。共享首选项覆盖其他值,我想在列表中添加项目,那么我如何在 Collection 夹列表中添加联系人。

第一个 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();

}
});

第二个 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;
}

最佳答案

检查 api documentation在提问之前。

解释

SharedPreferences 支持存储数据(1:1 键值匹配),因此一个键只能有一个数据项。

Storable Types

  • boolean
  • float
  • int
  • long
  • String
  • Set<String>

简单的解决方案

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

引用

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

关于java - SharedPreferences 会覆盖其他值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42083800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com