简体   繁体   中英

JSONException: No value for (parsing a JSON IMAGE)

I am trying to parse JSON data and make that data available in listview on an Android app.

I receive the following error:

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﹕ []

My code:

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

I understand that the error is occurring around the following, but I do not understand where I went wrong:

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

A brief view of the JSON array:

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

I appreciate any insight as to why this is occurring. Thank you.

(PS: I realize that there are many similar posts and I have tried to apply their solutions with no luck.)

您打算在c上调用jsonObj getString

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM