-1

I have a "MainActivity" containing a fragment "fragment1", this fragment shows a loader until data is fetched using Volley library. After this fragment1 gets the JSONResponse, it has to pass the data to the second fragment fragment2. My data from JSON are as follows:

{ "city": ["Moscow", "Istanbul"],
 "Moscow":["Moscow Kremlin", "Red Square", "Gorky Park", "Saint Pittsburgh"],
"Istanbul":["Taksim Square", "Hagia Sophia", "Grand Bazaar", "Spice Bazaar"]}

The problem here is that the number of cities and places are not fixed. Information keeps adding up. I've completed the data retrieval process on fragment1 but I'm unsure how to send it to the second fragment are retrieve the information there. Do I use Bundle or the onFragmentInteractionListener? And since there are no associative arrays in Java, how to I accomplish this?

1 Answers1

1

From below i will show you how to save and get values,

           Gson gson = new Gson();
           Example profile = new Example();
           Type listType = new TypeToken<Example>() {
                }.getType(); 
           profile = gson.fromJson(yourjson, listType);
           List<String> city = profile.getCity();

Example Class :

        package com.example;

    import java.util.List;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    public class Example {

    @SerializedName("city")
    @Expose
    private List<String> city = null;
    @SerializedName("Moscow")
    @Expose
    private List<String> moscow = null;
    @SerializedName("Istanbul")
    @Expose
    private List<String> istanbul = null;

    public List<String> getCity() {
    return city;
    }

    public void setCity(List<String> city) {
    this.city = city;
    }

    public List<String> getMoscow() {
    return moscow;
    }

    public void setMoscow(List<String> moscow) {
    this.moscow = moscow;
    }

    public List<String> getIstanbul() {
    return istanbul;
    }

    public void setIstanbul(List<String> istanbul) {
    this.istanbul = istanbul;
    }

}
MSD
  • 81
  • 8
  • I considered it before asking this question. But, if you look at my data structure, the array is of "one to many" type and I think Map doesn't allow you to do that. – Ashish Neupane Feb 21 '18 at 15:04
  • @AshishNeupane see the updated code. – MSD Feb 22 '18 at 05:36
  • You got a idea @AshishNeupane – MSD Feb 22 '18 at 06:02
  • As I already mentioned, the problem here is that the number of cities and places are not fixed. What if there's a new city `NewDelhi`? Then, I'd have to go to the source code and add that function `setDelhi()` and `getDelhi()`. – Ashish Neupane Feb 22 '18 at 07:21
  • Then use json as string and pass to fragment and convert there and get what you want. And also refer https://stackoverflow.com/questions/27371630/what-is-best-way-to-pass-json-data-one-fragment-to-another-fragment – MSD Feb 22 '18 at 07:32