本文介绍了如何保存的ListView共享preferences(机器人)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要保存列表的共享preferences元素。我知道的共享preferences保存的只有简单的数据。难道posibble?

I want to save elements of list in sharedPreferences. I know sharedPreferences saved only simple data. Is it posibble?

我的活动类:

List<String> tasks;
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_sms_number);

    tasks = new ArrayList<String>();

    Button add = (Button) findViewById(R.id.button);
    final EditText editText = (EditText) findViewById(R.id.editText);

    adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,tasks);
    ListView listView = (ListView) findViewById(R.id.listView1);
    listView.setAdapter(adapter);

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, 0);

            String value = editText.getText().toString();
            tasks.add(value);

            adapter.notifyDataSetChanged();
        }
    });

}

}

推荐答案

您可以将列表作为集,然后将其转换回一个列表,当您从共享preferences阅读。注意:这不工作,如果你的字符串需要专门订购的,显然

You can store your List as a Set, and then convert it back to a List when you read from SharedPreferences. Note: this doesn't work if your Strings need to be ordered specifically, obviously.

tasksList = new ArrayList<String>();
Set<String> tasksSet = new HashSet<String>(tasksList);
PreferenceManager.getDefaultSharedPreferences(context)
    .edit()
    .putStringSet("tasks_set", tasksSet)
    .commit();

然后,当你读它:

Then when you read it:

Set<String> tasksSet = PreferenceManager.getDefaultSharedPreferences(context)
    .getStringSet("tasks_set", new HashSet<String>());
List<String> tasksList = new ArrayList<String>(tasksSet);

这篇关于如何保存的ListView共享preferences(机器人)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 12:32