Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am a junior developer and I have very little experience with how to save the instance of a screen.

Activity:

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:

  1. Eradicate the reload button so the list remains automatically

  2. Reload the list in the order that it was saved.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
176 views
Welcome To Ask or Share your Answers For Others

1 Answer

Maybe this is not the answer that you are waiting for, but try using the database, because the shared preferences store in themselves an unordered list of elements (set). Or you should sort the list, and only then set it to the adapter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...