【问题标题】:How to send associative arrays from one fragment to another? [duplicate]如何将关联数组从一个片段发送到另一个片段? [复制]
【发布时间】:2018-02-21 13:57:43
【问题描述】:

我有一个"MainActivity" 包含一个片段"fragment1",这个片段显示一个加载器,直到使用Volley library 获取数据。在这个片段1 获得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 中没有关联数组,我该如何实现呢?

【问题讨论】:

标签: java android android-fragments


【解决方案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;
    }

}

【讨论】:

  • 我在问这个问题之前考虑过。但是,如果你看一下我的数据结构,数组是“一对多”类型的,我认为 Map 不允许你这样做。
  • @AshishNeupane 查看更新后的代码。
  • 你有个主意@AshishNeupane
  • 正如我已经提到的,这里的问题是城市和地点的数量不固定。如果有一个新城市NewDelhi 怎么办?然后,我必须转到源代码并添加该函数 setDelhi()getDelhi()
  • 然后使用 json 作为字符串并传递给片段并在那里转换并得到你想要的。也请参考stackoverflow.com/questions/27371630/…
猜你喜欢
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多