How to save my listview data and read again while my application pause or resume

185 views Asked by At

This is my code.I am studing a simple budget calculater application.My only purpose is how much I spend seeing in one mount ? But when I closed my application or pressed the back button on my telephone , I lost all my items. How can I fix this problem ?

 public class MainActivity extends ListActivity {
    private static final String[] items={"31.03.2017 Harcama ve Kazanç Tablosu"};
    public static final int MENU_ADD = Menu.FIRST+1;
    String ilk = "31.03.2017 Harcama ve Kazanç Tablosu";
    public static final int MENU_RESET = Menu.FIRST+2;
    public static final int MENU_REMOVE = Menu.FIRST+4 ;
     ArrayList<String> words=null;

    @Override
    public void onCreate(Bundle SavedInstanceState ) {
    super.onCreate(SavedInstanceState );

    initadapter();
    registerForContextMenu(getListView());

    }

    private void initadapter() {
        words=new ArrayList<String>();
        for (String s : items) {
        words.add(s);
        }
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, words));// TODO Auto-generated method stub

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenu.ContextMenuInfo menuInfo) {
    menu.add(Menu.NONE, MENU_ADD, Menu.NONE, "Ekle");
    menu.add(Menu.NONE, MENU_REMOVE, Menu.NONE, "Sil");
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info= (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    ArrayAdapter<String> adapter=(ArrayAdapter<String>)getListAdapter();
     {  
    }
    switch (item.getItemId()) {
    case MENU_REMOVE:
    adapter.remove(words.get(info.position));
    case MENU_ADD:
    add();
    return(true);
    }
    return(super.onContextItemSelected(item));
    }{
    }
    private void add() {

    final View addView=getLayoutInflater().inflate(R.layout.activity_main, null);
    new AlertDialog.Builder(this)
    .setTitle("Gider veya gelir ekle.")
    .setView(addView)
    .setPositiveButton("Tamam",
    new DialogInterface.OnClickListener() {
    @SuppressWarnings("unchecked")
    public void onClick(DialogInterface dialog,
    int whichButton) {
    ArrayAdapter<String> adapter=(ArrayAdapter<String>)getListAdapter();
    EditText yazı=(EditText)addView.findViewById(R.id.title);
    adapter.add(yazı.getText().toString());
    }
    })
    .setNegativeButton("Geri", null)
    .show();

    }
    }
1

There are 1 answers

4
ZexDC On BEST ANSWER

There are lots of ways to save data from your application. I suggest you take a look at the developer guidelines here first.

Shared Preferences is the most straight-forward approach with their Key-Value sets, especially for simple applications.

You usually can save the data you need in the onPause() method and load it back into the activity next time it is launched.