Question

I need to stored my listview that i create dynamically by a "add" button. Of course right now if i go out of application the items disappears. I tryied in this way but something's wrong

public class MainActivity extends Activity{
    private EditText etInput;
    private Button btnAdd;
    private ListView lvItem;
    private ArrayList<String> itemArrey;
    private ArrayAdapter<String> itemAdapter;

    /* Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setUpView();

        // Eliminare un elemento al longClick con dialog di conferma
        lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View v,
                    final int position, long id) {
                // TODO Auto-generated method stub
                    AlertDialog.Builder adb = new AlertDialog.Builder(
                    MainActivity.this);
                    adb.setTitle("Are you sure");
                    adb.setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                itemArrey.remove(position);
                                itemAdapter.notifyDataSetChanged();

                            }
                        });
                adb.setNegativeButton("No",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                // TODO Auto-generated method stub
                                 dialog.dismiss();

                            }
                        });
                adb.show();

                return false;
            }
        });

        lvItem.setClickable(true);
        lvItem.setOnItemClickListener(new AdapterView.OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

            Object o = lvItem.getItemAtPosition(position);
            Intent intent2 = new Intent(getApplicationContext(), MainActivity.class); // Mettere settings.class quando creata
            MainActivity.this.startActivity(intent2); 
          }
        });
    }

    private void setUpView() {
        etInput = (EditText)this.findViewById(R.id.editText_input);
        btnAdd = (Button)this.findViewById(R.id.button_add);
        lvItem = (ListView)this.findViewById(R.id.listView_items);


        itemArrey = new ArrayList<String>();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter<String>(this, R.layout.customlistview,itemArrey);
        lvItem.setAdapter(itemAdapter);


        btnAdd.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                addItemList();
            }
        });  

    }

    protected void addItemList() {

    if (isInputValid(etInput)) {
        itemArrey.add(0,etInput.getText().toString());
        etInput.setText("");

        itemAdapter.notifyDataSetChanged();

    }   

    }

    protected boolean isInputValid(EditText etInput2) {
        // TODO Auto-generatd method stub
        if (etInput2.getText().toString().trim().length()<1) {
            etInput2.setError("Insert value");
            return false;
        } else {
            return true;
        }

    }
    // Shared preferences
    protected void SavePreferences(String key, String value) {
        // TODO Auto-generated method stub
        SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = data.edit();
        editor.putString(key, value);
        editor.commit();


    }
    protected void LoadPreferences(){
        SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
        String dataSet = data.getString("LISTS", "None Available");

         itemAdapter.add(dataSet);
         itemAdapter.notifyDataSetChanged();
    }

I don't know how "call" the shared preferences and i don't know if in this way it's correct. Right now nothing happen, nothing is saving. Someone can help me please? Thanks

Was it helpful?

Solution

You should look at this API training about activity life cycle:

http://developer.android.com/training/basics/activity-lifecycle/index.html

and also this:

http://developer.android.com/training/basics/activity-lifecycle/recreating.html

As you can see, your activity can be gone because the user actively destroy it (using the back button) or the system can destroy it. If they system destroy it you can use onSaveInstanceState to save the data and onCreate to retrieve it. In that case you do not have to use SharedPreferences - just use Bundle as described in the link.

However, if you want to persist your data when the user close it, you should save your data when the call back onDestroy() is called. And retrieve the data when onCreate() is called. onDestroy() is called before the system thinks that your activity is not needed anymore, like when the user click the "back" button. In that case you do have to use one of the storage method provided by android, including Shared preferences. Like someone else said, it requires a "key, value" mechanism, so it might not match 100% with what you do. Using sqlLite is a bit heavy weight for this task, since your data is not really of a table type either (a single column table, actually, which is still not database worthy IMO). I think the best way to store your list is to use internal file. When onDestroy() is called, grab all your data and save to a file. When onCreate() is called, read the file and repopulate your list. You can read about android file system, including internal files here:

http://developer.android.com/training/basics/data-storage/files.html

As a close note, if the user press the "Home" button, your activity will not be destroyed. If he then "Force close" your app then nothing will be saved. If you still want to save it even in that case, I suggest you to save your data when "onStop()" is called and reset your list when onStart() is called.

OTHER TIPS

Right now nothing happen, nothing is saving.

That's because you never call your SavePreferences() method.

If you want to continue using SharedPreferences to store the data in your list, you will need to call SavePreferences() on every item in the list.

However, SharedPreferences are used for storing data in a key-value format. This means that every item in your list will require a key, and you need to know that key to retrieve the data. If your list can contain a variable number of items, SharedPreferences is likely not what you want.

I recommend reading the Storage Options documentation, which provides a complete example using Shared Preferences correctly, and discusses other options which may better suit your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top