无法保存ListView状态/值

时间:2013-05-25 21:36:55

标签: android listview save

我正在创建这个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();
    }

1 个答案:

答案 0 :(得分:0)

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

请参阅Android dev docs note re。什么存储在onSaveInstanceState:

  

注意:因为不能保证调用onSaveInstanceState(),所以你应该只使用它来记录瞬态状态   活动(UI的状态) - 你永远不应该用它来存储   持久数据。相反,您应该使用onPause()来存储持久性   用户时的数据(例如应保存到数据库的数据)   离开活动。

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