0

我正在使用通过菜单添加新项目的选项创建此 ListView,但我已经阅读了 Stackoverflow 中的所有代码/示例,我无法使用它们调整我的代码。

我尝试使用,onSaveInstanceState但是当我尝试使用 in 时无法启动应用程序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();
    }
4

1 回答 1

0

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

请参阅 Android 开发文档说明。在 onSaveInstanceState 中存储什么:

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

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

于 2013-05-25T21:53:14.840 回答