Android:在关机后将值保留在列表中

时间:2014-06-01 23:21:15

标签: android

我目前正在尝试开发一个充当购物清单的应用,用户在其中输入文字EditText,按下Button,然后将值保存到{{1然后,使用其值更新List。该应用程序运行良好,除非用户退出应用程序,在这种情况下,用户输入的所有值都不会保存。这是我到目前为止试图存储ListView

List

并在我的public class MainActivity extends ListActivity { private static final String SHARED_PREFS_NAME = "MY_SHARED_PREF"; ArrayList<String> mylist = new ArrayList<String>(); ArrayAdapter<String> adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listview = (ListView) findViewById(android.R.id.list); Button btn = (Button) findViewById(R.id.button); mylist = (ArrayList<String>) getArray(); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mylist); OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { EditText edit = (EditText) findViewById(R.id.edittext); mylist.add(edit.getText().toString()); edit.setText(""); adapter.notifyDataSetChanged(); } }; btn.setOnClickListener(listener); listview.setAdapter(adapter); } public boolean saveArray() { SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE); SharedPreferences.Editor mEdit1 = sp.edit(); Set<String> set = new HashSet<String>(); set.addAll(mylist); mEdit1.putStringSet("list", set); return mEdit1.commit(); } public List<String> getArray() { SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE); Set<String> set = sp.getStringSet("list", new HashSet<String>()); return new ArrayList<String>(set); } } 布局文件中

.xml

我拥有它以便可以正确地将值输入<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/edittext" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/edittext" android:text="Button" /> <ListView android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/button" > </ListView> </RelativeLayout> ,但在退出并重新打开应用后,ListView不会保存其值。有谁知道为什么会这样?

4 个答案:

答案 0 :(得分:3)

您的问题的解决方案如下:

由于link

,我尝试并重新编写了代码
public class MainActivity extends ListActivity {

    private static final String SHARED_PREFS_NAME = "MY_SHARED_PREF";
    ArrayList<String> mylist = new ArrayList<String>();
    ArrayAdapter<String> adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView listview = (ListView) findViewById(R.id.list);
        Button btn = (Button) findViewById(R.id.button);

        //NOTE: acquire array from shared preferences
        mylist = getArray();

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mylist);

        OnClickListener listener = new OnClickListener() {          
            @Override
            public void onClick(View v) {                               
                EditText edit = (EditText) findViewById(R.id.edittext);
                mylist.add(edit.getText().toString());
                edit.setText("");               
                adapter.notifyDataSetChanged();
            }
        };
        btn.setOnClickListener(listener);
        listview.setAdapter(adapter);        
    }

    public boolean saveArray() {
        SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
        SharedPreferences.Editor mEdit1 = sp.edit();
        Set<String> set = new HashSet<String>();
        set.addAll(mylist);
        mEdit1.putStringSet("list", set);
        return mEdit1.commit();
    }

    public ArrayList<String> getArray() {
        SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);

        //NOTE: if shared preference is null, the method return empty Hashset and not null          
        Set<String> set = sp.getStringSet("list", new HashSet<String>());

        return new ArrayList<String>(set);
    }
}

..并在关闭应用程序之前调用SaveArray()

public void onStop() {
    saveArray();
    super.onStop();
}

或者,每次添加元素时保存数组(所有&#39; onclick按钮覆盖当前列表中的共享首选项)

答案 1 :(得分:1)

由于您使用的列表视图不是自定义的,即是 android.R.layout.simple_list_item_1

我建议将列表视图中的项目保存为列表,然后将其保存到SharedPreferences。如果您只想在SharedPreferences中保存字符串,以下函数将有助于在 List和String&amp;之间进行转换。反之亦然

private String converttoStringfromList(List<String> list) {
    String convertedString;     
    convertedString = TextUtils.join(",", list);        
    return convertedString;
}



private List<String> converttoListfromString(String serialized) {
    List<String> convertedList = null;      
    convertedList = TextUtils.split(serialized, ",");       
    return convertedList;
}

从评论中的讨论更新: 它也应该更有效地在 ArrayList&lt;&gt; String 之间进行转换,以下线程将有助于如何执行此操作:

Best way to convert an ArrayList to a string

&安培;

How to convert a String into an ArrayList?

答案 2 :(得分:0)

在您的代码中,您会错过保存/恢复数据集的逻辑。由于ArrayList和String为Serializable,因此您可以在文件中序列化List。逻辑可能是这样的:

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     mylist = getList(fileName); 
     // other code
}

private void saveList(String fileName, List<String> values) {
 FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
 ObjectOutputStream os = new ObjectOutputStream(fos);
 os.writeObject(values);
 os.close();

}

private List<String> getList(String fileName) {
  FileInputStream fis = context.openFileInput(fileName);
  ObjectInputStream is = new ObjectInputStream(fis);
  List<String> values = (List<String>) is.readObject();
  is.close();
  if (values == null)
       values = new List<String>();
  return values;
}

@Override
protected void onDestroy() {
    super.onDestroy();
    saveList(fileName, values);
}

我是在飞行中写的,你应该检查异常,拼写错误等。

答案 3 :(得分:-1)

如果数据不复杂,我建议您使用共享首选项,否则,sqlite将是您的不错选择。