【问题标题】:Retrofit Android: how to fetch Json data using id and display into textviewRetrofit Android:如何使用 id 获取 Json 数据并显示到 textview
【发布时间】:2017-12-21 09:22:19
【问题描述】:

我只想使用 id 从 json 对象中获取特定数据并将其显示在 textview 中。我能够在列表视图中获取数据。但我想在不使用 listview 到基本 textview 的情况下获取数据。使用每个 id。

**只需要获取 id="1" json 数据并将其显示到 textview 名称、手机、年龄、电子邮件中。点击按钮后**

Json 数据

{
"details": [
    {
        "age": "56",
        "email": "john@gmail.com",
        "id": "1",
        "mobile": "985323154",
        "name": "John"
    },
    {
        "age": "0",
        "email": "",
        "id": "26",
        "mobile": "0",
        "name": "1"
    }
]

}

显示数据类

public class DisplayData extends AppCompatActivity {

    String BASE_URL = "";


    ArrayList<String> id = new ArrayList<>();
    ArrayList<String> name = new ArrayList<>();
    ArrayList<String> age = new ArrayList<>();
    ArrayList<String> mobile = new ArrayList<>();
    ArrayList<String> email = new ArrayList<>();


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

       displayData();


    }

       public void displayData() {

        RestAdapter adapter = new RestAdapter.Builder()
                .setEndpoint(BASE_URL) //Setting the Root URL
                .build();

        AppConfig.read api = adapter.create(AppConfig.read.class);

        api.readData(new Callback<JsonElement>() {
                         @Override
                         public void success(JsonElement result, Response response) {

                             String myResponse = result.toString();
                             Log.d("response", "" + myResponse);

                             try {
                                 JSONObject jObj = new JSONObject(myResponse);

                                 int success = jObj.getInt("success");

                                 if (success == 1) {

                                     JSONArray jsonArray = jObj.getJSONArray("details");
                                     for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject jo = jsonArray.getJSONObject(i);
                                        id.add(jo.getString("id"));
                                         name.add(jo.getString("name"));
                                         age.add(jo.getString("age"));
                                         mobile.add(jo.getString("mobile"));
                                         email.add(jo.getString("email"));


                                     }

                         }

                         @Override
                         public void failure(RetrofitError error) {
                             Log.d("Failure", error.toString());
                             Toast.makeText(DisplayData.this, error.toString(), Toast.LENGTH_LONG).show();
                         }
                     }
        );
    }
}

【问题讨论】:

  • 您希望用户界面是什么样的?请提供屏幕截图或模型。
  • 您正在使用 org.json 和 Retrofit?为什么不创建一个 POJO 并让 Retrofit 为您解析响应?你也可以考虑改用 Retrofit 2。
  • 随心所欲地发布屏幕短片

标签: android arrays json retrofit retrofit2


【解决方案1】:

我可以从您的代码中看出,您对所有字段都有不同的数组,这不是存储数据的好方法, 这样做: 用你的属性制作一个 bean,如下所示:

Detail.java

public class Detail {

    @SerializedName("age")
    @Expose
    private String age;
    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("mobile")
    @Expose
    private String mobile;
    @SerializedName("name")
    @Expose
    private String name;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

MyResponse.java

public class MyResponse {

    @SerializedName("details")
    @Expose
    private List<Detail> details = null;
@SerializedName("success")
@Expose
private Integer success;
@SerializedName("message")
@Expose
private String message;
public Integer getSuccess() {
return success;
}

public void setSuccess(Integer success) {
this.success = success;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
    public List<Detail> getDetails() {
        return details;
    }

    public void setDetails(List<Detail> details) {
        this.details = details;
    }

}

您的客户构建器

@GET("/retro/displayAll.php")
    Call<MyResponse> getResponse();//imp to include MyResponse as a call

获取详细信息的方法

Detail reqDetail;

    public void getDataForId(final String id){
        ApiInterface apiInterface = APIClient.getClient().create(ApiInterface.class);
        Call<MyResponse> call = apiInterface.getResponse();
        call.enqueue(new Callback<MyResponse>() {
            @Override
            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                if(response.body() != null){
                    MyResponse myResponse = response.body();
                    List<Detail> details = myResponse.getDetails();
                    for(Detail d : details){
                        if(d.getId().equals(id)){
                          reqDetail = d;

                          runOnUiThread(new Runnable() {
                            @Override
                            public void run() {//update your views here
                                tvName.setText(reqDetail.getName());
                            }
                            });
                            /*reqDetail will be having everything that you need and you can get it using the following code.
                            reqDetail.getName();
                            reqDetail.getAge();
                            reqDetail.getEmail();
                            reqDetail.getMobile();*/
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<MyResponse> call, Throwable t) {

            }
        });

    }

希望这对您有所帮助..编码愉快 :)

【讨论】:

  • 不错,这是使用改造的标准方式
  • 感谢您的回答....您能告诉我如何在我的 UI 中显示它吗i.stack.imgur.com/PAh5S.png
  • 检查更新的答案onResponse() 方法。如果有帮助,请接受答案。
  • 是的,我正在尝试您的代码。我已经发布了我的完整代码,你可以看看。正如你告诉我的那样,我想为此创建模型类,这是 UI 中的显示数据。
  • 温馨提醒,如果有帮助,请采纳答案..:)
猜你喜欢
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
  • 2013-08-16
相关资源
最近更新 更多