Retrofit Android:如何使用id获取Json数据并显示到textview中

时间:2017-07-16 23:02:16

标签: android arrays json retrofit retrofit2

我想使用id从json对象中获取特定数据,并在textview中显示它。我可以在listview中获取数据。但是我希望在不使用listview的情况下获取数据到基本的textview中。使用每个id。

**只想要获取ID =" 1" json数据并将其显示为textview名称,手机,年龄,电子邮件。点击按钮**

Json Data

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

}

DisplayData Class

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();
                         }
                     }
        );
    }
}

1 个答案:

答案 0 :(得分:5)

我可以从您的代码中得到的结果是您为所有字段设置了不同的数组,这不是存储数据的好方法, 这样做: 像这样制作属性的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) {

            }
        });

    }

希望这有所帮助......快乐的编码:)