Java convert ArrayList to string and back to ArrayList?












11















I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:



// Save to shared preferences
SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
editor.putString("myAppsArr", myAppsArr.toString());
editor.commit();


I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?





My array looks something like:



[item1,item2,item3]









share|improve this question





























    11















    I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:



    // Save to shared preferences
    SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
    editor.putString("myAppsArr", myAppsArr.toString());
    editor.commit();


    I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?





    My array looks something like:



    [item1,item2,item3]









    share|improve this question



























      11












      11








      11


      5






      I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:



      // Save to shared preferences
      SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
      SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
      editor.putString("myAppsArr", myAppsArr.toString());
      editor.commit();


      I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?





      My array looks something like:



      [item1,item2,item3]









      share|improve this question
















      I wanted to save an ArrayList to SharedPreferences so I need to turn it into a string and back, this is what I am doing:



      // Save to shared preferences
      SharedPreferences sharedPref = this.getPreferences(Activity.MODE_PRIVATE);
      SharedPreferences.Editor editor = this.getPreferences(Activity.MODE_PRIVATE).edit();
      editor.putString("myAppsArr", myAppsArr.toString());
      editor.commit();


      I can retrieve it with String arrayString = sharedPref.getString("yourKey", null); but I don't know how to convert arrayString back into an ArrayList. How can it be done?





      My array looks something like:



      [item1,item2,item3]






      java android string list arraylist






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jan 15 '13 at 10:54









      Eng.Fouad

      84.8k53247360




      84.8k53247360










      asked Sep 5 '12 at 7:07









      lisovaccarolisovaccaro

      6,87777212357




      6,87777212357
























          6 Answers
          6






          active

          oldest

          votes


















          30





          +50









          You have 2 choices :




          1. Manually parse the string and recreate the arraylist. This would be pretty tedious.


          2. Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,



            // How to store JSON string
            Gson gson = new Gson();
            // This can be any object. Does not have to be an arraylist.
            String json = gson.toJson(myAppsArr);

            // How to retrieve your Java object back from the string
            Gson gson = new Gson();
            DataObject obj = gson.fromJson(arrayString, ArrayList.class);







          share|improve this answer


























          • I changed the array elements to strings, I'm sure it must be a lot easier now.

            – lisovaccaro
            Jan 13 '13 at 23:51











          • It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem.

            – Dhruv Gairola
            Jan 13 '13 at 23:54



















          2














          Try this



          ArrayList<String> array = Arrays.asList(arrayString.split(","))


          This will work if comma is used as separator and none of the items have it.






          share|improve this answer































            1














            I ended up using:



            ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\s*,\s*")));


            This doesn't work for all array types though. This option differs from:



            ArrayList<String> array = Arrays.asList(arrayString.split(","));


            on that the second option creates an inmutable array.






            share|improve this answer
























            • Did you see my answer?

              – Eng.Fouad
              Jan 16 '13 at 3:32



















            1














            The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:



            Type     type  = new TypeToken<List<T>>(){}.getType();
            List<T> list = gson.fromJson(jsonString, type)


            perhaps it will be helpful.






            share|improve this answer

































              1














                    //arraylist convert into String using Gson 
              Gson gson = new Gson();
              String data = gson.toJson(myArrayList);
              Log.e(TAG, "json:" + gson);

              //String to ArrayList

              Gson gson = new Gson();
              arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
              {}.getType());





              share|improve this answer

































                0















                Update to Dhruv Gairola's answer for Kotlin




                val gson = Gson();
                val jsonString = gson.toJson(arrayList)





                share|improve this answer























                  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%2f12276205%2fjava-convert-arraylist-to-string-and-back-to-arraylist%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  6 Answers
                  6






                  active

                  oldest

                  votes








                  6 Answers
                  6






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  30





                  +50









                  You have 2 choices :




                  1. Manually parse the string and recreate the arraylist. This would be pretty tedious.


                  2. Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,



                    // How to store JSON string
                    Gson gson = new Gson();
                    // This can be any object. Does not have to be an arraylist.
                    String json = gson.toJson(myAppsArr);

                    // How to retrieve your Java object back from the string
                    Gson gson = new Gson();
                    DataObject obj = gson.fromJson(arrayString, ArrayList.class);







                  share|improve this answer


























                  • I changed the array elements to strings, I'm sure it must be a lot easier now.

                    – lisovaccaro
                    Jan 13 '13 at 23:51











                  • It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem.

                    – Dhruv Gairola
                    Jan 13 '13 at 23:54
















                  30





                  +50









                  You have 2 choices :




                  1. Manually parse the string and recreate the arraylist. This would be pretty tedious.


                  2. Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,



                    // How to store JSON string
                    Gson gson = new Gson();
                    // This can be any object. Does not have to be an arraylist.
                    String json = gson.toJson(myAppsArr);

                    // How to retrieve your Java object back from the string
                    Gson gson = new Gson();
                    DataObject obj = gson.fromJson(arrayString, ArrayList.class);







                  share|improve this answer


























                  • I changed the array elements to strings, I'm sure it must be a lot easier now.

                    – lisovaccaro
                    Jan 13 '13 at 23:51











                  • It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem.

                    – Dhruv Gairola
                    Jan 13 '13 at 23:54














                  30





                  +50







                  30





                  +50



                  30




                  +50





                  You have 2 choices :




                  1. Manually parse the string and recreate the arraylist. This would be pretty tedious.


                  2. Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,



                    // How to store JSON string
                    Gson gson = new Gson();
                    // This can be any object. Does not have to be an arraylist.
                    String json = gson.toJson(myAppsArr);

                    // How to retrieve your Java object back from the string
                    Gson gson = new Gson();
                    DataObject obj = gson.fromJson(arrayString, ArrayList.class);







                  share|improve this answer















                  You have 2 choices :




                  1. Manually parse the string and recreate the arraylist. This would be pretty tedious.


                  2. Use a JSON library like Google's Gson library to store and retrieve objects as JSON strings. This is a lightweight library, well regarded and popular. It would be an ideal solution in your case with minimal work required. e.g.,



                    // How to store JSON string
                    Gson gson = new Gson();
                    // This can be any object. Does not have to be an arraylist.
                    String json = gson.toJson(myAppsArr);

                    // How to retrieve your Java object back from the string
                    Gson gson = new Gson();
                    DataObject obj = gson.fromJson(arrayString, ArrayList.class);








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 13 '13 at 23:57

























                  answered Jan 13 '13 at 23:48









                  Dhruv GairolaDhruv Gairola

                  7,71833238




                  7,71833238













                  • I changed the array elements to strings, I'm sure it must be a lot easier now.

                    – lisovaccaro
                    Jan 13 '13 at 23:51











                  • It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem.

                    – Dhruv Gairola
                    Jan 13 '13 at 23:54



















                  • I changed the array elements to strings, I'm sure it must be a lot easier now.

                    – lisovaccaro
                    Jan 13 '13 at 23:51











                  • It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem.

                    – Dhruv Gairola
                    Jan 13 '13 at 23:54

















                  I changed the array elements to strings, I'm sure it must be a lot easier now.

                  – lisovaccaro
                  Jan 13 '13 at 23:51





                  I changed the array elements to strings, I'm sure it must be a lot easier now.

                  – lisovaccaro
                  Jan 13 '13 at 23:51













                  It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem.

                  – Dhruv Gairola
                  Jan 13 '13 at 23:54





                  It doesn't matter. With Gson, you can convert any java object to a string and then convert it back. So even if you have an arraylist of custom objects, there's no problem.

                  – Dhruv Gairola
                  Jan 13 '13 at 23:54













                  2














                  Try this



                  ArrayList<String> array = Arrays.asList(arrayString.split(","))


                  This will work if comma is used as separator and none of the items have it.






                  share|improve this answer




























                    2














                    Try this



                    ArrayList<String> array = Arrays.asList(arrayString.split(","))


                    This will work if comma is used as separator and none of the items have it.






                    share|improve this answer


























                      2












                      2








                      2







                      Try this



                      ArrayList<String> array = Arrays.asList(arrayString.split(","))


                      This will work if comma is used as separator and none of the items have it.






                      share|improve this answer













                      Try this



                      ArrayList<String> array = Arrays.asList(arrayString.split(","))


                      This will work if comma is used as separator and none of the items have it.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 14 '13 at 0:19









                      Mykhailo GaidaiMykhailo Gaidai

                      2,73011322




                      2,73011322























                          1














                          I ended up using:



                          ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\s*,\s*")));


                          This doesn't work for all array types though. This option differs from:



                          ArrayList<String> array = Arrays.asList(arrayString.split(","));


                          on that the second option creates an inmutable array.






                          share|improve this answer
























                          • Did you see my answer?

                            – Eng.Fouad
                            Jan 16 '13 at 3:32
















                          1














                          I ended up using:



                          ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\s*,\s*")));


                          This doesn't work for all array types though. This option differs from:



                          ArrayList<String> array = Arrays.asList(arrayString.split(","));


                          on that the second option creates an inmutable array.






                          share|improve this answer
























                          • Did you see my answer?

                            – Eng.Fouad
                            Jan 16 '13 at 3:32














                          1












                          1








                          1







                          I ended up using:



                          ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\s*,\s*")));


                          This doesn't work for all array types though. This option differs from:



                          ArrayList<String> array = Arrays.asList(arrayString.split(","));


                          on that the second option creates an inmutable array.






                          share|improve this answer













                          I ended up using:



                          ArrayList<String> appList = new ArrayList<String>(Arrays.asList(appsString.split("\s*,\s*")));


                          This doesn't work for all array types though. This option differs from:



                          ArrayList<String> array = Arrays.asList(arrayString.split(","));


                          on that the second option creates an inmutable array.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 15 '13 at 21:55









                          lisovaccarolisovaccaro

                          6,87777212357




                          6,87777212357













                          • Did you see my answer?

                            – Eng.Fouad
                            Jan 16 '13 at 3:32



















                          • Did you see my answer?

                            – Eng.Fouad
                            Jan 16 '13 at 3:32

















                          Did you see my answer?

                          – Eng.Fouad
                          Jan 16 '13 at 3:32





                          Did you see my answer?

                          – Eng.Fouad
                          Jan 16 '13 at 3:32











                          1














                          The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:



                          Type     type  = new TypeToken<List<T>>(){}.getType();
                          List<T> list = gson.fromJson(jsonString, type)


                          perhaps it will be helpful.






                          share|improve this answer






























                            1














                            The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:



                            Type     type  = new TypeToken<List<T>>(){}.getType();
                            List<T> list = gson.fromJson(jsonString, type)


                            perhaps it will be helpful.






                            share|improve this answer




























                              1












                              1








                              1







                              The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:



                              Type     type  = new TypeToken<List<T>>(){}.getType();
                              List<T> list = gson.fromJson(jsonString, type)


                              perhaps it will be helpful.






                              share|improve this answer















                              The page http://mjiayou.com/2015/07/22/exception-gson-internal-cannot-be-cast-to/ contains the following:



                              Type     type  = new TypeToken<List<T>>(){}.getType();
                              List<T> list = gson.fromJson(jsonString, type)


                              perhaps it will be helpful.







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jan 6 '16 at 17:14









                              John Hascall

                              7,56643560




                              7,56643560










                              answered Jan 6 '16 at 13:29









                              user5752479user5752479

                              111




                              111























                                  1














                                        //arraylist convert into String using Gson 
                                  Gson gson = new Gson();
                                  String data = gson.toJson(myArrayList);
                                  Log.e(TAG, "json:" + gson);

                                  //String to ArrayList

                                  Gson gson = new Gson();
                                  arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
                                  {}.getType());





                                  share|improve this answer






























                                    1














                                          //arraylist convert into String using Gson 
                                    Gson gson = new Gson();
                                    String data = gson.toJson(myArrayList);
                                    Log.e(TAG, "json:" + gson);

                                    //String to ArrayList

                                    Gson gson = new Gson();
                                    arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
                                    {}.getType());





                                    share|improve this answer




























                                      1












                                      1








                                      1







                                            //arraylist convert into String using Gson 
                                      Gson gson = new Gson();
                                      String data = gson.toJson(myArrayList);
                                      Log.e(TAG, "json:" + gson);

                                      //String to ArrayList

                                      Gson gson = new Gson();
                                      arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
                                      {}.getType());





                                      share|improve this answer















                                            //arraylist convert into String using Gson 
                                      Gson gson = new Gson();
                                      String data = gson.toJson(myArrayList);
                                      Log.e(TAG, "json:" + gson);

                                      //String to ArrayList

                                      Gson gson = new Gson();
                                      arrayList=gson.fromJson(data, new TypeToken<List<Friends>>()
                                      {}.getType());






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jan 9 at 6:57

























                                      answered Jun 11 '18 at 10:21









                                      bhoomikabhoomika

                                      43159




                                      43159























                                          0















                                          Update to Dhruv Gairola's answer for Kotlin




                                          val gson = Gson();
                                          val jsonString = gson.toJson(arrayList)





                                          share|improve this answer




























                                            0















                                            Update to Dhruv Gairola's answer for Kotlin




                                            val gson = Gson();
                                            val jsonString = gson.toJson(arrayList)





                                            share|improve this answer


























                                              0












                                              0








                                              0








                                              Update to Dhruv Gairola's answer for Kotlin




                                              val gson = Gson();
                                              val jsonString = gson.toJson(arrayList)





                                              share|improve this answer














                                              Update to Dhruv Gairola's answer for Kotlin




                                              val gson = Gson();
                                              val jsonString = gson.toJson(arrayList)






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Oct 9 '18 at 8:00









                                              Quick learnerQuick learner

                                              2,4861924




                                              2,4861924






























                                                  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%2f12276205%2fjava-convert-arraylist-to-string-and-back-to-arraylist%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