2015-07-20 68 views
-2

我知道有很多關於這個特定錯誤的帖子,但他們都沒有解決我的問題,我是Android開發新手。由於這個錯誤,我無法在應用程序的listView中看到數據。JSONException沒有值..安卓應用

以下是我的代碼:

public class JSONBuilderActivity extends ListActivity { 

    private ProgressDialog pDialog; 

    //URL to get JSON 
    private static String url = "http://""; 

    //JSON Node names 
    private static final String TAG_CARS = "cars";  //root 
    private static final String TAG_CARID = "car_id"; 

    JSONArray carid = null; //Initializes JSON array 

    static String response = null; 

    //Hashmap for ListView 
    ArrayList<HashMap<String, String>>caridList; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     ListView lv = getListView(); 

     //Listview on item click listener 
     lv.setOnItemClickListener(new OnItemClickListener() { 

      @Override 
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 

       //Gets values from selected ListItem 
       String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString(); 
       String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString(); 

       Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class); 
       //getApplicationContext() 
       //sending data to new activity 
       in.putExtra("TAG_CARS", cars); 
       in.putExtra("TAG_CARID", car_id); 
       startActivity(in); 
      } 
     }); 

     //Calls async task to get json 
     new GetCars().execute(); 
    } 

    public class ServiceHandler { 

     public final static int GET = 1; 
     public final static int POST = 2; 

     public ServiceHandler() { 

     } 

     /** 
     * Makes service call 
     * @url - url to make request 
     * @method - http request method 
     * */ 
     public String makeServiceCall(String url, int method) { 
      return this.makeServiceCall(url, method, null); 
     } 

     /** 
     * Makes service call 
     * @url - url to make request 
     * @method - http request method 
     * @params - http request params 
     * */ 
     public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) { 
        try { 
        DefaultHttpClient httpClient = new DefaultHttpClient(); 
        HttpEntity httpEntity = null; 
        HttpResponse httpResponse = null; 

        //Checks http request method type 
        if (method == POST) { 
         HttpPost httpPost = new HttpPost(url); 

         //Adds post params 
        if (params != null) { 
         httpPost.setEntity(new UrlEncodedFormEntity(params)); 
        } 

         httpResponse = httpClient.execute(httpPost); 

       } else if (method == GET) { 

        //Appends params to url 
        if (params != null) { 
         String paramString = URLEncodedUtils.format(params, "utf-8"); 
         url += "?" + paramString; 
        } 
         HttpGet httpGet = new HttpGet(url); 

         httpResponse = httpClient.execute(httpGet); 
       } 

       httpEntity = httpResponse.getEntity(); 
       response = EntityUtils.toString(httpEntity); 

      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } catch (ClientProtocolException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

      return response; 

     } 
    } 

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

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      caridList = new ArrayList<HashMap<String, String>>(); 
      //Shows progress dialog 
      pDialog = new ProgressDialog(JSONBuilderActivity.this); 
      pDialog.setMessage("Please wait..."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 

      //Creates service handler class instance 
      ServiceHandler sh = new ServiceHandler(); 

      //Makes a request to url and getting response 
      String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET); 

      //Prints the json response in the log 
      Log.d("GetCars response: ", "> " + jsonStr); 

      //Prints array in app 


        if (jsonStr != null) { 
         try { 

          Log.d("try", "in the try"); 

          JSONObject jsonObj = new JSONObject(jsonStr); 
          Log.d("jsonObject", "new json Object"); 

          //Gets JSON Array node 
          carid = jsonObj.getJSONArray(TAG_CARS); 
          Log.d("json array", "user point array"); 

          int len = carid.length(); 
          Log.d("len", "get array length"); 

          for (int i = 0; i < carid.length(); i++) { 
           JSONObject c = carid.getJSONObject(i); 
           String car_id = c.getString(TAG_CARID); 
           Log.d("car_id", car_id); 

           //Hashmap for single match 
           HashMap<String, String> matchGetCars = new HashMap<String, String>(); 

           //Adds each child node to HashMap key => value 
           matchGetCars.put(TAG_CARID, car_id); 
           caridList.add(matchGetCars); 
          } 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } else { 
         Log.e("ServiceHandler", "Couldn't get any data from the url"); 
        } 

        return null; 
       } 

       @Override 
       protected void onPostExecute(Void result) { 
        super.onPostExecute(result); 
        //Dismisses the progress dialog 
        if (pDialog.isShowing()) 
         pDialog.dismiss(); 

        /** 
        * Updates parsed JSON data into ListView 
        * */ 
        ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item, 
          new String[]{TAG_CARID}, new int[]{R.id.car_id}); 
        setListAdapter(adapter); 
        Log.v("List parsed", caridList.toString()); 
       } 
    } 
} 

我認識到錯誤時靠近下列發生:

if (jsonStr != null) { 
         try { 

          Log.d("try", "in the try"); 

          JSONObject jsonObj = new JSONObject(jsonStr); 
          Log.d("jsonObject", "new json Object"); 

          //Gets JSON Array node 
          carid = jsonObj.getJSONArray(TAG_CARS); 
          Log.d("json array", "user point array"); 

          int len = carid.length(); 
          Log.d("len", "get array length"); 

          for (int i = 0; i < carid.length(); i++) { 
           JSONObject c = carid.getJSONObject(i); 
           String car_id = c.getString(TAG_CARID); 
           Log.d("car_id", car_id); 

           //Hashmap for single match 
           HashMap<String, String> matchGetCars = new HashMap<String, String>(); 

           //Adds each child node to HashMap key => value 
           matchGetCars.put(TAG_CARID, car_id); 
           caridList.add(matchGetCars); 
          } 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } else { 
         Log.e("ServiceHandler", "Couldn't get any data from the url"); 
        } 

        return null; 
       } 

這裏是logcat的數據:

org.json.JSONException: No value for car_id 
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354) 
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:510) 
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:202) 
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:155) 
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287) 
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.lang.Thread.run(Thread.java:856) 
07-20 15:31:30.455 7567-7567/com.example.justin.myapplication V/List parsed﹕ [] 

簡要查看JSON的外觀:

{"cars":[{"id":1,"CarID":"20946"....so on... 

我很感激,如果有任何建議可以徹底解釋和證明爲什麼會發生此錯誤。非常感謝。

回答

0

更換

private static final String TAG_CARID = "car_id"; 

private static final String TAG_CARID = "CarID"; 

您JSONArray具有關鍵 「CarID」,而您正在搜索 「car_id」。

希望這有助於:)

+0

非常感謝!我是Android開發人員,Java和解析思想的新手,所以我沒有意識到相應的字符串必須與JSON數據完全匹配......哇......這很愚蠢。再次感謝你! – JohnWilliams

0

「汽車」 是jsonArray中的JSONObject。您必須首先獲取數組,然後從中提取數值。我現在不能給你代碼示例,因爲我目前正在使用我的手機。

+0

解決方案是,我沒有正確的標籤字符串值。無論如何,謝謝你的幫助。 – JohnWilliams