将数组保存到sharedpreferences并在listview中显示它

时间:2018-02-14 09:56:27

标签: android listview arraylist sharedpreferences

我需要将用户输入保存到共享首选项,并在列表视图中的共享首选项中显示它。我怎么能这样做?

现在我的代码添加到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();
        }
    });
}

3 个答案:

答案 0 :(得分:1)

首先,您必须将所有列表项存储到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);
 }

答案 1 :(得分:0)

您可以使用GSON将数组序列化为JSON String,以便您可以像往常一样将其存储在SharedPreferences中String

您可以在that post

中找到的GSON示例

答案 2 :(得分:0)

将您的字符串数组转换为逗号分隔值(csv)字符串并保存。在Java 1.8中使用String.join(",", new String[]{"A", "B"});

当检索take是一个字符串并转换回String数组时。使用yourString.split(",")