2015-07-21 76 views
0

我想解析JSON數據並在Android應用程序的列表視圖中提供該數據。JSONException:沒有值(解析JSON圖像)

我收到以下錯誤:

org.json.JSONException: No value for CarModelImage 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:510) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:212) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:162) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) 
07-21 14:03:48.236 25946-25971/com.example.justin.myapplication W/System.err﹕ at java.lang.Thread.run(Thread.java:856) 
07-21 14:03:48.252 25946-25946/com.example.justin.myapplication V/List parsed﹕ [] 

我的代碼:

public class JSONBuilderActivity extends ListActivity { 

    private ProgressDialog pDialog; 

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

    //JSON Node names 
    private static final String TAG_CARS = "cars";  //root 
    private static final String TAG_CARID = "CarID"; 
    private static final String TAG_MODELIMG = "CarModelImage"; 

    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(); 
       String model_img = ((ImageView) view.findViewById(R.id.model_img)).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); 
       in.putExtra("TAG_MODELIMG", model_img); 
       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); 

           String jsonString = jsonObj.getString(TAG_MODELIMG); 
           getBitmapFromString(jsonString); 
           String model_img = c.getString(TAG_MODELIMG); 
           Log.d("model_img", model_img); 

           //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); 
           matchGetCars.put(TAG_MODELIMG, model_img); 
           caridList.add(matchGetCars); 
          } 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } else { 
         Log.e("ServiceHandler", "Couldn't get any data from the url"); 
        } 

        return null; 
       } 


     private Bitmap getBitmapFromString(String jsonString) { 
      byte[] decodedString = Base64.decode("CarModelImage", Base64.DEFAULT); 
      Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
      return decodedByte; 
     } 

@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, TAG_MODELIMG}, new int[]{R.id.car_id, R.id.model_img}); 
        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); 

          String jsonString = jsonObj.getString(TAG_MODELIMG); 
          getBitmapFromString(jsonString); 
          String model_img = c.getString(TAG_MODELIMG); 
          Log.d("model_img", model_img); 

          //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); 
          matchGetCars.put(TAG_MODELIMG, model_img); 
          caridList.add(matchGetCars); 
         } 
        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 
       } else { 
        Log.e("ServiceHandler", "Couldn't get any data from the url"); 
       } 

       return null; 
      } 

JSON數組的簡要說明:

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

我很欣賞任何有關爲何發生這種情況的見解。謝謝。

(P.S:我知道有很多類似的帖子,我已經試過,沒有運氣運用他們的解決方案。)

+0

可能重複的[JSONException沒有價值..安卓應用](http://stackoverflow.com/questions/31525327/jsonexception-no-value-for-android-app) – Barend

+0

@Barend這是我的帖子,是。但是,我添加了一個新功能,現在涉及JSON圖像,我的帖子中的解決方案不再適用。不過謝謝你的考慮。所以請刪除重複標誌或任何它被稱爲。 – JohnWilliams

+0

即使你解決了這個問題,我發現當你以base [64]解碼一個英文字符串時,你會再次被卡住[解碼字符串] = Base64.decode(「CarModelImage」,Base64.DEFAULT)。調試和校對你的代碼可能是你的出路。 –

回答

1

你呼籲jsonObjgetString當你想調用它c

+0

我試圖爲getBitmapFromString(字符串jsonString)使用該信息,因爲其中一個JSON數據片是我需要解碼的圖像。如果可能,請解釋如何在沒有提到的代碼行的情況下解碼。謝謝。 – JohnWilliams

+0

我同意@simplyianm - 當字符串car_id = c.getString(TAG_CARID);正在工作,沒有理由c.getString(TAG_MODELIMG);不管用。如果你試圖在jsonObj而不是c上獲得它,顯然這是行不通的。 –