如何在共享首选项中保存listView(android)

时间:2014-05-27 22:16:00

标签: android listview sharedpreferences

我想在sharedPreferences中保存列表元素。我知道sharedPreferences只保存了简单的数据。是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();
        }
    });

}

}

1 个答案:

答案 0 :(得分:0)

您可以将List存储为Set,然后在从SharedPreferences读取时将其转换回List。注意:如果您的字符串需要专门订购,这显然不起作用。

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

然后当你读到它时:

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