【问题标题】:Android listview in API integration JSON parsingAPI集成JSON解析中的Android listview
【发布时间】:2017-02-17 10:46:29
【问题描述】:

我曾尝试将 json 值解析为我的列表视图。我在 logcat 中收到错误作为 json 解析错误,而不是结果出现在 listview 中,整个 json 响应出现在 toast 中,请帮我解决它。谢谢。

这是我的java代码

MainActivity.java

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get contacts JSON
private static String url = " https://private-2a004-androidtest3.apiary-mock.com/employeesList";

ArrayList<HashMap<String, String>> employeeList;

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

    employeeList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new Getemployees().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class Getemployees extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray employees = jsonObj.getJSONArray("contacts");

                // looping through All Contacts
                for (int i = 0; i < employees.length(); i++) {
                    JSONObject c = employees.getJSONObject(i);
                    String firstName = c.getString("firstName");
                    String lastName = c.getString("lastName");
                    String designation = c.getString("designation");
                    String city = c.getString("city");
                    HashMap<String, String> emp = new HashMap<>();
                    emp.put("firstName", firstName);
                    emp.put("lastName", lastName);
                    emp.put("designation",designation);
                    emp.put("city",city);
                    employeeList.add(emp);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, employeeList,
                R.layout.list_item, new String[]{"firstName","lastName","designation", "city"},new int[]{R.id.firstName,
                R.id.lastName,R.id.city,R.id.designation});
        lv.setAdapter(adapter);
    }

}

}

HttpHandler.java

public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

我的日志猫:

02-17 15:45:03.667 24027-24149/com.example.simple E/MainActivity: Response from url: [
                                                                      {

                                                                          "employee": 
                                                                          [
                                                                            {
                                                                              "id": "1",
                                                                              "firstName": "Ram",
                                                                              "lastName": "Kumar",
                                                                              "address" : "1/20, Rich street",
                                                                              "city" : "Karur",
                                                                              "zipcode" : "636138",
                                                                              "gender" : "male",
                                                                              "dob" : "20-May-1995",
                                                                              "designation":"developer",
                                                                              "mobile" : "9988776655",
                                                                              "email" : "tom@gmail.com",
                                                                              "nationality" : "Indian",
                                                                              "language" : "English",
                                                                              "imageURL" : "https://dummyimage.com/500x500/d12ad1/fff.png&text=Ram",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++", "Java" ],
                                                                                  "extra_curricular" : ["chess", "cricket"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "2",
                                                                              "firstName": "Kumari",
                                                                              "lastName": "Raja",
                                                                              "address" : "2/20, Rich street",
                                                                              "city" : "Coimbatore",
                                                                              "zipcode" : "636148",
                                                                              "gender" : "female",
                                                                              "dob" : "10-Jun-1995",
                                                                              "designation":"Tester",
                                                                              "mobile" : "8899667744",
                                                                              "email" : "maria@gmail.com",
                                                                              "nationality" : "Indian",
                                                                              "language" : "Tamil",
                                                                              "imageURL" : "https://dummyimage.com/500x500/52d929/fff.png&text=Kumari",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++", ".net" ],
                                                                                  "extra_curricular" : ["Tennis", "Carrom"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "3",
                                                                              "firstName": "Raja",
                                                                              "lastName": "Ravi",
                                                                              "address" : "13/20, Rich street",
                                                                              "city" : "Salem",
                                                                              "zipcode" : "636138",
                                                                              "gender" : "male",
                                                                              "dob" : "22-Jan-1994",
                                                                              "designation":"Team Lead",
                                                                              "mobile" : "9876543210",
                                                                              "email" : "raja@gmail.com",
                                                                              "nationality" : "Indian",
                                                                              "language" : "English",
                                                                              "imageURL" : "https://dummyimage.com/500x500/bef0af/fff.png&text=Raja",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++", "Java" , "Android"],
                                                                                  "extra_curricular" : ["chess", "cricket"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "4",
                                                                              "firstName": "Sheela",
                                                                              "lastName": "Ravi",
                                                                              "address" : "14/20, Rich street",
                                                                              "city" : "Madurai",
                                                                              "zipcode" : "636200",
                                                                              "gender" : "female",
                                                                              "dob" : "10-Feb-1985",
                                                                              "designation":"developer",
                                                                              "mobile" : "5566778899",
                                                                              "email" : "Sheela@gmail.com",
                                                                              "nationality" : "Indian",
                                                                              "language" : "Tamil",
                                                                              "imageURL" : "https://dummyimage.com/500x500/e6866e/fff.png&text=Sheela",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "photoshop", "Ruby" ],
                                                                                  "extra_curricular" : ["Carrom", "Reading books"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "5",
                                                                              "firstName": "Shankar",
                                                                              "lastName": "Kumar",
                                                                              "address" : "15/20, Rich street",
                                                                              "city" : "Madurai",
                                                                              "zipcode" : "636300",
                                                                              "gender" : "Male",
                                                                              "dob" : "10-Feb-1985",
                                                                              "designation":"Sr.Developer",
                                                                              "mobile" : "5566778899",
                                                                              "email" : "shankar@gmail.com",
                                                                              "nationality" : "Indian",
                                                                              "language" : "Tamil",
                                                                              "imageURL" : "https://dummyimage.com/500x500/8f3532/fff.png&text=Shankar",
                                                                              "skills": [
                                                                                {
                                                                                  "technical" : [ "C", "C++" ],
                                                                                  "extra_curricular" : ["chess", "Drawing"]
                                                                                }]
                                                                            },
                                                                            {
                                                                              "id": "6",
                                                                              "firstName": "Suren",
                                                                              "lastName": "Saker",
                                                                              "address" : "16/20, Rich street",
                                                                              "city" : "Salem",
                                                                              "zipcode" : "636400",
                                                                              "gender" : "Male",
                                                                              "dob" : "14-Jan-1985",
                                                                              "designat
02-17 15:45:03.676 24027-24149/com.example.simple E/MainActivity: Json parsing error: Value [{"employee":[{"id":"1","firstName":"Ram","lastName":"Kumar","address":"1\/20, Rich street","city":"Karur","zipcode":"636138","gender":"male","dob":"20-May-1995","designation":"developer","mobile":"9988776655","email":"tom@gmail.com","nationality":"Indian","language":"English","imageURL":"https:\/\/dummyimage.com\/500x500\/d12ad1\/fff.png&text=Ram","skills":[{"technical":["C","C++","Java"],"extra_curricular":["chess","cricket"]}]},{"id":"2","firstName":"Kumari","lastName":"Raja","address":"2\/20, Rich street","city":"Coimbatore","zipcode":"636148","gender":"female","dob":"10-Jun-1995","designation":"Tester","mobile":"8899667744","email":"maria@gmail.com","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/dummyimage.com\/500x500\/52d929\/fff.png&text=Kumari","skills":[{"technical":["C","C++",".net"],"extra_curricular":["Tennis","Carrom"]}]},{"id":"3","firstName":"Raja","lastName":"Ravi","address":"13\/20, Rich street","city":"Salem","zipcode":"636138","gender":"male","dob":"22-Jan-1994","designation":"Team Lead","mobile":"9876543210","email":"raja@gmail.com","nationality":"Indian","language":"English","imageURL":"https:\/\/dummyimage.com\/500x500\/bef0af\/fff.png&text=Raja","skills":[{"technical":["C","C++","Java","Android"],"extra_curricular":["chess","cricket"]}]},{"id":"4","firstName":"Sheela","lastName":"Ravi","address":"14\/20, Rich street","city":"Madurai","zipcode":"636200","gender":"female","dob":"10-Feb-1985","designation":"developer","mobile":"5566778899","email":"Sheela@gmail.com","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/dummyimage.com\/500x500\/e6866e\/fff.png&text=Sheela","skills":[{"technical":["photoshop","Ruby"],"extra_curricular":["Carrom","Reading books"]}]},{"id":"5","firstName":"Shankar","lastName":"Kumar","address":"15\/20, Rich street","city":"Madurai","zipcode":"636300","gender":"Male","dob":"10-Feb-1985","designation":"Sr.Developer","mobile":"5566778899","email":"shankar@gmail.com","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/dummyimage.com\/500x500\/8f3532\/fff.png&text=Shankar","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"6","firstName":"Suren","lastName":"Saker","address":"16\/20, Rich street","city":"Salem","zipcode":"636400","gender":"Male","dob":"14-Jan-1985","designation":"Sr.Developer","mobile":"8899776655","email":"suren@gmail.com","nationality":"Indian","language":"English","imageURL":"http:\/\/indianapublicmedia.org\/arts\/files\/2012\/04\/sample-gates-9-940x626.jpg","skills":[{"technical":["Java","Android"],"extra_curricular":["Reading","Stamp collection"]}]},{"id":"7","firstName":"Rajesh","lastName":"Kumar","address":"17\/20, Rich street","city":"Karur","zipcode":"636800","gender":"Male","dob":"10-Feb-1985","designation":"Sr.Developer","mobile":"5566778899","email":"shankar@gmail.com","nationality":"Indian","language":"Tamil","imageURL":"http:\/\/images.fonearena.com\/blog\/wp-content\/uploads\/2013\/11\/Lenovo-p780-camera-sample-10.jpg","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"8","firstName":"Sham","lastName":"Kumar","address":"18\/20, Rich street","city":"Salem","zipcode":"636700","gender":"Male","dob":"08-Feb-1985","designation":"Sr.Developer","mobile":"7788996655","email":"sham@gmail.com","nationality":"Indian","language":"Tamil","imageURL":"https:\/\/taylorstaste.files.wordpress.com\/2014\/07\/screenshot-2014-07-03-10-25-41.png","skills":[{"technical":["C","C++"],"extra_curricular":["chess","Drawing"]}]},{"id":"9","firstName":"Jayakumar","lastName":"Ravi","address":"19\/20, Rich street","city":"Coimbatore","zipcode":"623300","gender":"Male","dob":"3-Mar-1986","designation":"Designer","mobile":"8879797979","email":"jaya@gmail.com","nationality":"Indian","language":"Tamil","imageURL":"http:\/\/images.fonearena.com\/blog\/wp-content\/uploads\/2013\/11\/google-nexus-5-macro-samples-1.jpg","skills":[{"technical":["Photoshop","Design tools"],"extra_curricular":["chess","Drawing"]}]},{

【问题讨论】:

  • 我希望您的contact 键是正确的,您的意思不是employee,因为我们在日志中看不到它。如果正确:尝试 substring e.getMessage() 从错误中删除前 1000(或 5000 或 10000)个字符,以便查看错误在哪里。否则,我建议您在您的计算机上运行此请求,并检查 JSON 在某些在线服务中是否确实有效。
  • 检查您的 JSONObject "{" 和 JSONArray"[" 代码中的序列与您的 JSON 比较,并且您的 JSON JSONArray 中没有“联系人” employees = jsonObj.getJSONArray("contacts");跨度>
  • 请发布您的完整 JSON 响应,以便我可以帮助您
  • @ZakiPathan,这是我的完整 JSON 回复:
  • 在哪里?那是一个logcat。我需要完整的 JSON 响应

标签: java android json listview


【解决方案1】:

试试这个,

        try {


            JSONArray jsonArray=new JSONArray(jsonStr);

            JSONObject jsonObj =jsonArray.getJSONObject(0);

            // Getting JSON Array node
            JSONArray employees = jsonObj.getJSONArray("employee");

            // looping through All Contacts
            for (int i = 0; i < employees.length(); i++) {
                JSONObject c = employees.getJSONObject(i);
                String firstName = c.getString("firstName");
                String lastName = c.getString("lastName");
                String designation = c.getString("designation");
                String city = c.getString("city");
                HashMap<String, String> emp = new HashMap<>();
                emp.put("firstName", firstName);
                emp.put("lastName", lastName);
                emp.put("designation",designation);
                emp.put("city",city);
                employeeList.add(emp);
            }
        } catch (final JSONException e) {

        }

【讨论】:

  • @user2025187 非常感谢,对我很有帮助
  • @ZakiPathan,是的,Zaki,这对我有用,非常感谢
  • 将此标记为正确答案,以便其他人从中获得帮助
  • @ZakiPathan 请告诉我如何传递每个列表行的意图,请告诉我,谢谢
  • 是什么意思?您正在尝试从不同的列表行打开不同的活动?
【解决方案2】:

使用 JSONArray jsArray= new JSONArray(jsonStr) instesd of JSONObject jsonObj = new JSONObject(jsonStr) 因为你的响应是一个 JsonArray。

【讨论】:

    【解决方案3】:

    Json 键不匹配:

    JSONArray jsonArray=new JSONArray(jsonStr); // As your response is in json array format
    JSONObject jsonObject =jsonArray.getJSONObject(0);
    // Getting JSON Array node
    JSONArray employees = jsonObject.getJSONArray("employee");
    

    将“联系人”键替换为“员工”即可解决您的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多