I am a junior developer and I have very little experience with how to save the instance of a screen.
Activity:
What my application does is that the user is entering in a number of completed (X) each hour. What I would like to do is that when the user leaves this page and goes to another activity, then returns, the list will retain.
I tried to use this code:
@Override
protected void onPause() {
super.onPause();
//Set the values
sharedPreferences = getSharedPreferences("MYPREFS", MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPreferences.edit();
Set<String> set = new HashSet<String>();
set.addAll(ListElementsArrayList);
editor.putStringSet("list", set);
editor.apply();
}
@Override
public void onResume() {
super.onResume();
sharedPreferences = getSharedPreferences("MYPREFS", MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPreferences.edit();
Set<String> set = sharedPreferences.getStringSet("list", null);
ListElementsArrayList.addAll(set);
listView.setAdapter(adapter);
}
Code to add to list:
handler = new Handler() ;
ListElementsArrayList = new ArrayList<String>(Arrays.asList(ListElements));
adapter = new ArrayAdapter<String>(Processing.this,
android.R.layout.simple_list_item_1,
ListElementsArrayList
);
listView.setAdapter(adapter);
btnShippersCompleted.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
shippersCompleted = textView.getText().toString();
ListElementsArrayList.add(shippersCompleted + "- Hour " + Hour++);
adapter.notifyDataSetChanged();
}
});
Although I received a null pointer on the onResume() method. So I added the code to a RELOAD button instead. It was working although now the list is going out of order (see screenshot).
How can I:
Eradicate the reload button so the list remains automatically
Reload the list in the order that it was saved.