我需要将用户输入保存到共享的首选项,并在列表视图中从共享的首选项显示它。我怎样才能做到这一点?
现在,我的代码添加到了listview,但是没有保存。
ListView listView;
Button AddWebsiteBtn;
EditText WebsiteName;
String[] ListOfWebsites = new String[]{};
SharedPreferences preferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
listView = (ListView) findViewById(R.id.list_of_websites);
AddWebsiteBtn = (Button) findViewById(R.id.btn_submit);
WebsiteName = (EditText) findViewById(R.id.website_name);
//using this part to add it to listview, maybe will need to remove it when shared preferences will work
final List< String > ListElementsArrayList = new ArrayList< String >
(Arrays.asList(ListOfWebsites));
final ArrayAdapter < String > adapter = new ArrayAdapter< String >
(AddActivity.this, android.R.layout.simple_list_item_1,
ListElementsArrayList);
listView.setAdapter(adapter);
AddWebsiteBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ListElementsArrayList.add(WebsiteName.getText().toString());
adapter.notifyDataSetChanged();
}
});
}
最佳答案
首先,您必须将所有列表项存储到ArrayList
,然后将ArrayList
存储到SharedPreference
变量声明
SharedPreferences shared;
ArrayList<String> arrPackage;
变量初始化:
shared = getSharedPreferences("App_settings", MODE_PRIVATE);
// add values for your ArrayList any where...
arrPackage = new ArrayList<>();
将值存储到
sharedPreference
中: private void packagesharedPreferences() {
SharedPreferences.Editor editor = shared.edit();
Set<String> set = new HashSet<String>();
set.addAll(arrPackage);
editor.putStringSet("DATE_LIST", set);
editor.apply();
Log.d("storesharedPreferences",""+set);
}
检索
sharedPreference
的值: private void retriveSharedValue() {
Set<String> set = shared.getStringSet("DATE_LIST", null);
arrPackage.addAll(set);
Log.d("retrivesharedPreferences",""+set);
}