2017-02-17 25 views
-1

Ich hatte versucht, den Json-Wert zu meinem Listview zu analysieren. Ich bekomme den Fehler in Logcat als JSON Parsing-Fehler, anstelle des Ergebnisses in ListView erscheint die gesamte JSON-Antwort in Toast, bitte helfen Sie mir, es zu lösen. Vielen Dank.Android Listview in API-Integration JSON Parsing

Hier ist mein Java-Code

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

Mein logcat:

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" : "[email protected]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" : "[email protected]", 
                       "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" : "", 
                       "email" : "[email protected]", 
                       "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" : "[email protected]", 
                       "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" : "[email protected]", 
                       "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":"[email protected]","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":"[email protected]","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":"","email":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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"]}]},{ 
+0

Ich hoffe, Sie 'contact' Schlüssel ist richtig, und Sie bedeuten nicht,' employee' wie wir es nicht im Protokoll sehen. Wenn es richtig ist: Versuchen Sie, die ersten 1000 (oder 5000 oder 10000) Zeichen aus Ihrem Fehler zu "substring" 'e.getMessage()' zu entfernen, damit Sie sehen können, wo der Fehler liegt. Andernfalls würde ich empfehlen, dass Sie diese Anfrage auf Ihrem Computer ausführen und überprüfen, ob der JSON tatsächlich von einem Onlinedienst gültig ist. – zed

+0

überprüfen Sie Ihre JSONObject "{" und "JSONArray" ["Sequenz" im Code vergleichen mit Ihrem JSON und es gibt keine "Kontakte" in Ihrem JSON JSONArray Mitarbeiter = JsonObj.getJSONArray ("Kontakte"); –

+0

Bitte posten Sie Ihre volle JSON Antwort, damit ich Ihnen helfen kann –

Antwort

1

die Sie interessieren,

 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) { 

     } 
+0

@ Da1 Ich denke, das funktioniert für Sie –

+0

@ user2025187 Vielen Dank, es hat mir wirklich geholfen – Da1

+0

@ZakiPathan, ja Zaki, das hat für mich funktioniert , vielen Dank – Da1

0

Json Schlüssel passt nicht:

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"); 

Ersetzen "Kontakt" Taste mit "Mitarbeiter", die Ihr Problem gelöst wird.

+0

ok ... lass mich das überprüfen ... nd erreiche dich. – Da1

+0

@ Da1 Kasse meine aktualisierte Antwort, sollte es funktionieren – Piyush

+0

lassen Sie mich überprüfen .. – Da1

0

Verwenden Sie JSONArray jsArray = neues JSONArray (jsonStr) instesd von JSONObject jsonObj = neues JSONObject (jsonStr), weil Ihre Antwort ein JsonArray ist.