无法保存ListView状态/值



我正在创建这个ListView,可以通过菜单添加新项目,但我已经在Stackoverflow中阅读了所有的代码/示例,我无法用它们来适应我的代码。

我尝试使用onSaveInstanceState,但是当我尝试在onCreate中使用时,我无法启动应用程序。

在输入新值时保存此列表的最佳方法是什么?

我试图使用的代码:

protect void onCreate(...)
{
     ...
     if (savedInstanceState.containKey(MYLISTKEY))
     {
          alllist = savedInstanceState.getStringArrayList(MYLISTKEY);
     } else {
     }
}
下面是我的代码:
public class MainActivity extends Activity {
    private static final String MYLISTKEY = "myListItems";
    final Context context = this;
    private ListView mainListView;
    private ArrayAdapter<String> listAdapter;`
    private ArrayList<String> allList = new ArrayList<String>();
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putStringArrayList(MYLISTKEY, allList);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the ListView resource.
        mainListView = (ListView) findViewById(R.id.mainListView); 
        // TODO: Populate explicitely your list
        // Create and populate a List of planet names.
        String[] listitems = new String[] { };  
        allList.addAll(Arrays.asList(listitems));
        // Create ArrayAdapter using the planet list.
        listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, allList);
        // Add more planets. If you passed a String[] instead of a List<String> 
        // into the ArrayAdapter constructor, you must not add more items. 
        // Otherwise an exception will occur.
        listAdapter.add( "Item A" );
        listAdapter.add( "Item B" );
        // Set the ArrayAdapter as the ListView's adapter.
        mainListView.setAdapter( listAdapter );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    /* (non-Javadoc)
     * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        // Action Add Item to the listview
        case R.id.action_add:
            addListItem();
            return true;
            // Save list to SharedPreferences
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    // Add new item list when choose "New Item" on menu
    private void addListItem() {
        // get prompt.xml view
        LayoutInflater li = LayoutInflater.from(context);
        View promptsView = li.inflate(R.layout.prompt, null);
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        // set prompt.xml to alertdialog builder
        alertDialogBuilder.setView(promptsView);
        final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
        // set dialog message
        alertDialogBuilder
        .setCancelable(false)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // get user input and set it to result
                // edit text
                listAdapter.add(userInput.getText().toString());
                listAdapter.notifyDataSetChanged();
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });
        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show it
        alertDialog.show();
    }

正如您的评论// Save list to SharedPreferences建议您应该将列表中的数据保存到某种持久存储,而不是依赖于savedInstanceState包。

查看Android开发文档中关于onSaveInstanceState存储内容的说明:

注意:因为onSaveInstanceState()不能保证被调用,所以您应该只使用它来记录活动(UI的状态)——永远不要用它来存储持久数据。相反,您应该使用onPause()来存储持久性数据(例如应该保存到数据库中的数据)退出活动。

http://developer.android.com/guide/components/activities.html

最新更新