0

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.

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

JohnWilliams
  • 139
  • 1
  • 13
  • possible duplicate of [JSONException No value for..Android app](http://stackoverflow.com/questions/31525327/jsonexception-no-value-for-android-app) – Barend Jul 21 '15 at 18:33
  • @Barend That was my post, yes. However, I am adding a new feature now involving a JSON image and the solution from my post does not apply anymore. Thank you for your consideration though. So please remove the duplication flag or whatever it is called. – JohnWilliams Jul 21 '15 at 18:37
  • Even if you solve this problem, I see that you will get stuck again as you are base 64 decoding an english string in byte[] decodedString = Base64.decode("CarModelImage", Base64.DEFAULT); Debugging and proof reading your code may be your way out. – Wand Maker Jul 21 '15 at 18:44
  • @Wand Maker Hello, I want the corresponding JSON jpg image file to be decoded..please explain. – JohnWilliams Jul 21 '15 at 18:46
  • @JohnWilliams You need to get file name from JSON, and read the file (don't see the code that does that in your sample), and use the file contents to create BitMap. – Wand Maker Jul 21 '15 at 18:49
  • @Wand Maker The JSON is not coming from a file; it is coming from a URL. – JohnWilliams Jul 21 '15 at 18:50
  • I am talking about JPG file. Where is it? Is it on file system ? Where is the code to read it? As I said earlier, you may have to debug your code. Good luck ! – Wand Maker Jul 21 '15 at 18:53

1 Answers1

1

You're calling getString on jsonObj when you mean to call it on c.

Ian Macalinao
  • 1,608
  • 3
  • 20
  • 30
  • I am attempting to use that information for getBitmapFromString (String jsonString) because one of the JSON data pieces is an image which I need to decode. Please explain how I can decode without that mentioned line of code if possible. Thank you. – JohnWilliams Jul 21 '15 at 18:35
  • I agree with @simplyianm - When String car_id = c.getString(TAG_CARID); is working, there is no reason c.getString(TAG_MODELIMG); will not work. If you try to get it on jsonObj instead of c, obviously it will not work. – Wand Maker Jul 21 '15 at 18:52