我有"MainActivity"
包含片段"fragment1
",此片段显示加载程序,直到使用Volley library
获取数据。在此fragment1获得JSONResponse
之后,它必须将数据传递给第二个片段fragment2
。我在JSON的数据如下:
{ "city": ["Moscow", "Istanbul"],
"Moscow":["Moscow Kremlin", "Red Square", "Gorky Park", "Saint Pittsburgh"],
"Istanbul":["Taksim Square", "Hagia Sophia", "Grand Bazaar", "Spice Bazaar"]}
这里的问题是城市和地方的数量不固定。信息不断增加。我已在fragment1
完成了数据检索过程,但我不确定如何将其发送到第二个片段,检索那里的信息。我使用Bundle
还是onFragmentInteractionListener
?由于Java
中没有关联数组,我该如何实现呢?
答案 0 :(得分:1)
从下面我将向您展示如何保存和获取值,
Gson gson = new Gson();
Example profile = new Example();
Type listType = new TypeToken<Example>() {
}.getType();
profile = gson.fromJson(yourjson, listType);
List<String> city = profile.getCity();
示例类:
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;
}
}