首页 > 解决方案 > 使用 Volley 获取 JSON 文件的问题

问题描述

再会,

我在JSON使用 Android Studio 获取文件时遇到问题。如何JSONObject在下面的代码中调用特定的示例我想知道输入的电话号码是否等于该JSONObject号码。我正在尝试JSONArray在不同的字符串上单独读取和存储。

每次我试图obj.getString("phonenum")在循环内调用时,我得到的唯一值就是最后一个值。

我的代码如下。

JSON 文件。

获取信息.php

[
  {
    "id": 1,
    "name": "Angelo Dayao",
    "email": "angelo@gmail.com",
    "phonenum": "639201234567"
  },
  {
    "id": 2,
    "name": "Angelo Dayao",
    "email": "angelogg@g.com",
    "phonenum": "639161234567"
  },
  {
    "id": 3,
    "name": "Anna Chelzia",
    "email": "anna@g.com",
    "phonenum": "639771234567"
  }
]

JAVA文件代码

public void GetData(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONArray jsonArray = new JSONArray(response);

                            for(int i = 0; i < jsonArray.length(); i++){
                                try {
                                    JSONObject obj = null;

                                    obj = jsonArray.getJSONObject(i);

                                    if(obj.getString("phonenum") == phonenumber){
                                        Toast.makeText(getApplicationContext(), obj.getString("phonenum"), Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });


        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }

标签: androidjsonandroid-volley

解决方案


推荐阅读