Save new form of custom ArrayList, SharedPreferences












0















noobie here. I have a custum ArrayAdapter with questions and answers. When one list item is longClicked, it gets removed. Now I want to save the new state of the ArrayList with the removed item, so if you go to another tab in the app and then return you will have only the remaining questions.
I looked online and found something that looks like what I need, but I can't see why it won't work.



public class OnePointQuestion extends AppCompatActivity {
ArrayList<Question> TheQuestion;
String key = "ABCD";

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);

if(TheQuestion == null){
createList();
}else{
getArrayList(key);
}

final MyAdapter adapter = new MyAdapter(this, TheQuestion);
ListView listView = findViewById(R.id.list);
listView.setAdapter(adapter);

//When the list item is clicked
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Identify the current question
Question currentQuestion = TheQuestion.get(position);

//Send the answer to a second page to be shown
Intent i = new Intent(OnePointQuestion.this, TheAnswer.class);
i.putExtra("TheAnswer", currentQuestion.getAnswer());
startActivity(i);
}
});

//When the list item is long clicked
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//Identify the current question
Question currentQuestion = TheQuestion.get(position);
//Remove this element of the list
TheQuestion.remove(currentQuestion);
adapter.notifyDataSetChanged();
Toast.makeText(OnePointQuestion.this, "Urmatoarea intrebare", Toast.LENGTH_SHORT).show();
return true;
}
});
}

//Save the ArrayList
public void saveArrayList(ArrayList<Question> list, String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
SharedPreferences.Editor editor = prefs.edit();
Gson gson = new Gson();
String json = gson.toJson(list);
editor.putString(key, json);
editor.apply(); // This line is IMPORTANT !!!
Toast.makeText(OnePointQuestion.this, "Saved", Toast.LENGTH_SHORT).show();
}

//Load the ArrayList
public ArrayList<Question> getArrayList(String key){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
Gson gson = new Gson();
String json = prefs.getString(key, null);
Type type = new TypeToken<ArrayList<Question>>() {}.getType();
Toast.makeText(OnePointQuestion.this, "Loaded", Toast.LENGTH_SHORT).show();
return gson.fromJson(json, type);
}

//Load the ArrayList when the app gets to the OnStart
@Override
protected void onStart() {
super.onStart();
getArrayList(key);
}


@Override
protected void onPause() {
super.onPause();
saveArrayList(TheQuestion, key);
}


public void createList(){
//Create the list of questions
TheQuestion = new ArrayList<>();
TheQuestion.add(new Question("Cum te cheama?", "Irelevant"));
TheQuestion.add(new Question("Cati ani ai?", "Prea multi"));
TheQuestion.add(new Question("De ce ai dat la Poli", "Asta ma intreb si eu"));

}


}



The "save" and "load" methods I'm trying to use are near the end.
If you can tell me what I am doing wrong, I would appreciate it, thanks :)










share|improve this question



























    0















    noobie here. I have a custum ArrayAdapter with questions and answers. When one list item is longClicked, it gets removed. Now I want to save the new state of the ArrayList with the removed item, so if you go to another tab in the app and then return you will have only the remaining questions.
    I looked online and found something that looks like what I need, but I can't see why it won't work.



    public class OnePointQuestion extends AppCompatActivity {
    ArrayList<Question> TheQuestion;
    String key = "ABCD";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.list);

    if(TheQuestion == null){
    createList();
    }else{
    getArrayList(key);
    }

    final MyAdapter adapter = new MyAdapter(this, TheQuestion);
    ListView listView = findViewById(R.id.list);
    listView.setAdapter(adapter);

    //When the list item is clicked
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    //Identify the current question
    Question currentQuestion = TheQuestion.get(position);

    //Send the answer to a second page to be shown
    Intent i = new Intent(OnePointQuestion.this, TheAnswer.class);
    i.putExtra("TheAnswer", currentQuestion.getAnswer());
    startActivity(i);
    }
    });

    //When the list item is long clicked
    listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    //Identify the current question
    Question currentQuestion = TheQuestion.get(position);
    //Remove this element of the list
    TheQuestion.remove(currentQuestion);
    adapter.notifyDataSetChanged();
    Toast.makeText(OnePointQuestion.this, "Urmatoarea intrebare", Toast.LENGTH_SHORT).show();
    return true;
    }
    });
    }

    //Save the ArrayList
    public void saveArrayList(ArrayList<Question> list, String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
    SharedPreferences.Editor editor = prefs.edit();
    Gson gson = new Gson();
    String json = gson.toJson(list);
    editor.putString(key, json);
    editor.apply(); // This line is IMPORTANT !!!
    Toast.makeText(OnePointQuestion.this, "Saved", Toast.LENGTH_SHORT).show();
    }

    //Load the ArrayList
    public ArrayList<Question> getArrayList(String key){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
    Gson gson = new Gson();
    String json = prefs.getString(key, null);
    Type type = new TypeToken<ArrayList<Question>>() {}.getType();
    Toast.makeText(OnePointQuestion.this, "Loaded", Toast.LENGTH_SHORT).show();
    return gson.fromJson(json, type);
    }

    //Load the ArrayList when the app gets to the OnStart
    @Override
    protected void onStart() {
    super.onStart();
    getArrayList(key);
    }


    @Override
    protected void onPause() {
    super.onPause();
    saveArrayList(TheQuestion, key);
    }


    public void createList(){
    //Create the list of questions
    TheQuestion = new ArrayList<>();
    TheQuestion.add(new Question("Cum te cheama?", "Irelevant"));
    TheQuestion.add(new Question("Cati ani ai?", "Prea multi"));
    TheQuestion.add(new Question("De ce ai dat la Poli", "Asta ma intreb si eu"));

    }


    }



    The "save" and "load" methods I'm trying to use are near the end.
    If you can tell me what I am doing wrong, I would appreciate it, thanks :)










    share|improve this question

























      0












      0








      0








      noobie here. I have a custum ArrayAdapter with questions and answers. When one list item is longClicked, it gets removed. Now I want to save the new state of the ArrayList with the removed item, so if you go to another tab in the app and then return you will have only the remaining questions.
      I looked online and found something that looks like what I need, but I can't see why it won't work.



      public class OnePointQuestion extends AppCompatActivity {
      ArrayList<Question> TheQuestion;
      String key = "ABCD";

      @Override
      protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.list);

      if(TheQuestion == null){
      createList();
      }else{
      getArrayList(key);
      }

      final MyAdapter adapter = new MyAdapter(this, TheQuestion);
      ListView listView = findViewById(R.id.list);
      listView.setAdapter(adapter);

      //When the list item is clicked
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      //Identify the current question
      Question currentQuestion = TheQuestion.get(position);

      //Send the answer to a second page to be shown
      Intent i = new Intent(OnePointQuestion.this, TheAnswer.class);
      i.putExtra("TheAnswer", currentQuestion.getAnswer());
      startActivity(i);
      }
      });

      //When the list item is long clicked
      listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
      //Identify the current question
      Question currentQuestion = TheQuestion.get(position);
      //Remove this element of the list
      TheQuestion.remove(currentQuestion);
      adapter.notifyDataSetChanged();
      Toast.makeText(OnePointQuestion.this, "Urmatoarea intrebare", Toast.LENGTH_SHORT).show();
      return true;
      }
      });
      }

      //Save the ArrayList
      public void saveArrayList(ArrayList<Question> list, String key){
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
      SharedPreferences.Editor editor = prefs.edit();
      Gson gson = new Gson();
      String json = gson.toJson(list);
      editor.putString(key, json);
      editor.apply(); // This line is IMPORTANT !!!
      Toast.makeText(OnePointQuestion.this, "Saved", Toast.LENGTH_SHORT).show();
      }

      //Load the ArrayList
      public ArrayList<Question> getArrayList(String key){
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
      Gson gson = new Gson();
      String json = prefs.getString(key, null);
      Type type = new TypeToken<ArrayList<Question>>() {}.getType();
      Toast.makeText(OnePointQuestion.this, "Loaded", Toast.LENGTH_SHORT).show();
      return gson.fromJson(json, type);
      }

      //Load the ArrayList when the app gets to the OnStart
      @Override
      protected void onStart() {
      super.onStart();
      getArrayList(key);
      }


      @Override
      protected void onPause() {
      super.onPause();
      saveArrayList(TheQuestion, key);
      }


      public void createList(){
      //Create the list of questions
      TheQuestion = new ArrayList<>();
      TheQuestion.add(new Question("Cum te cheama?", "Irelevant"));
      TheQuestion.add(new Question("Cati ani ai?", "Prea multi"));
      TheQuestion.add(new Question("De ce ai dat la Poli", "Asta ma intreb si eu"));

      }


      }



      The "save" and "load" methods I'm trying to use are near the end.
      If you can tell me what I am doing wrong, I would appreciate it, thanks :)










      share|improve this question














      noobie here. I have a custum ArrayAdapter with questions and answers. When one list item is longClicked, it gets removed. Now I want to save the new state of the ArrayList with the removed item, so if you go to another tab in the app and then return you will have only the remaining questions.
      I looked online and found something that looks like what I need, but I can't see why it won't work.



      public class OnePointQuestion extends AppCompatActivity {
      ArrayList<Question> TheQuestion;
      String key = "ABCD";

      @Override
      protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.list);

      if(TheQuestion == null){
      createList();
      }else{
      getArrayList(key);
      }

      final MyAdapter adapter = new MyAdapter(this, TheQuestion);
      ListView listView = findViewById(R.id.list);
      listView.setAdapter(adapter);

      //When the list item is clicked
      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      //Identify the current question
      Question currentQuestion = TheQuestion.get(position);

      //Send the answer to a second page to be shown
      Intent i = new Intent(OnePointQuestion.this, TheAnswer.class);
      i.putExtra("TheAnswer", currentQuestion.getAnswer());
      startActivity(i);
      }
      });

      //When the list item is long clicked
      listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
      @Override
      public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
      //Identify the current question
      Question currentQuestion = TheQuestion.get(position);
      //Remove this element of the list
      TheQuestion.remove(currentQuestion);
      adapter.notifyDataSetChanged();
      Toast.makeText(OnePointQuestion.this, "Urmatoarea intrebare", Toast.LENGTH_SHORT).show();
      return true;
      }
      });
      }

      //Save the ArrayList
      public void saveArrayList(ArrayList<Question> list, String key){
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
      SharedPreferences.Editor editor = prefs.edit();
      Gson gson = new Gson();
      String json = gson.toJson(list);
      editor.putString(key, json);
      editor.apply(); // This line is IMPORTANT !!!
      Toast.makeText(OnePointQuestion.this, "Saved", Toast.LENGTH_SHORT).show();
      }

      //Load the ArrayList
      public ArrayList<Question> getArrayList(String key){
      SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(OnePointQuestion.this);
      Gson gson = new Gson();
      String json = prefs.getString(key, null);
      Type type = new TypeToken<ArrayList<Question>>() {}.getType();
      Toast.makeText(OnePointQuestion.this, "Loaded", Toast.LENGTH_SHORT).show();
      return gson.fromJson(json, type);
      }

      //Load the ArrayList when the app gets to the OnStart
      @Override
      protected void onStart() {
      super.onStart();
      getArrayList(key);
      }


      @Override
      protected void onPause() {
      super.onPause();
      saveArrayList(TheQuestion, key);
      }


      public void createList(){
      //Create the list of questions
      TheQuestion = new ArrayList<>();
      TheQuestion.add(new Question("Cum te cheama?", "Irelevant"));
      TheQuestion.add(new Question("Cati ani ai?", "Prea multi"));
      TheQuestion.add(new Question("De ce ai dat la Poli", "Asta ma intreb si eu"));

      }


      }



      The "save" and "load" methods I'm trying to use are near the end.
      If you can tell me what I am doing wrong, I would appreciate it, thanks :)







      java android sharedpreferences






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 8:08









      Andrei BichirAndrei Bichir

      33




      33
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Move getArrayList(key); to onResume() method.



          @Override
          protected void onResume() {
          super.onResume();
          getArrayList(key);
          }


          see the life cycle:



          enter image description here






          share|improve this answer
























          • It still won't work. It tells me something that the return value of the getArrayList(key) is not used. I have tried to use it some how, but it would crush my app..

            – Andrei Bichir
            Nov 25 '18 at 20:13











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465714%2fsave-new-form-of-custom-arraylist-sharedpreferences%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Move getArrayList(key); to onResume() method.



          @Override
          protected void onResume() {
          super.onResume();
          getArrayList(key);
          }


          see the life cycle:



          enter image description here






          share|improve this answer
























          • It still won't work. It tells me something that the return value of the getArrayList(key) is not used. I have tried to use it some how, but it would crush my app..

            – Andrei Bichir
            Nov 25 '18 at 20:13
















          0














          Move getArrayList(key); to onResume() method.



          @Override
          protected void onResume() {
          super.onResume();
          getArrayList(key);
          }


          see the life cycle:



          enter image description here






          share|improve this answer
























          • It still won't work. It tells me something that the return value of the getArrayList(key) is not used. I have tried to use it some how, but it would crush my app..

            – Andrei Bichir
            Nov 25 '18 at 20:13














          0












          0








          0







          Move getArrayList(key); to onResume() method.



          @Override
          protected void onResume() {
          super.onResume();
          getArrayList(key);
          }


          see the life cycle:



          enter image description here






          share|improve this answer













          Move getArrayList(key); to onResume() method.



          @Override
          protected void onResume() {
          super.onResume();
          getArrayList(key);
          }


          see the life cycle:



          enter image description here







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 25 '18 at 8:14









          navylovernavylover

          3,51531119




          3,51531119













          • It still won't work. It tells me something that the return value of the getArrayList(key) is not used. I have tried to use it some how, but it would crush my app..

            – Andrei Bichir
            Nov 25 '18 at 20:13



















          • It still won't work. It tells me something that the return value of the getArrayList(key) is not used. I have tried to use it some how, but it would crush my app..

            – Andrei Bichir
            Nov 25 '18 at 20:13

















          It still won't work. It tells me something that the return value of the getArrayList(key) is not used. I have tried to use it some how, but it would crush my app..

          – Andrei Bichir
          Nov 25 '18 at 20:13





          It still won't work. It tells me something that the return value of the getArrayList(key) is not used. I have tried to use it some how, but it would crush my app..

          – Andrei Bichir
          Nov 25 '18 at 20:13




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53465714%2fsave-new-form-of-custom-arraylist-sharedpreferences%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          To store a contact into the json file from server.js file using a class in NodeJS

          Redirect URL with Chrome Remote Debugging Android Devices

          Dieringhausen