JSONException No value for..Android app

隐身守侯 提交于 2019-12-13 23:52:53

问题


I know that there are many posts about this particular error, but none of them are solving my issue and I am new to Android development. As a result of this error, I am unable to see the data in a listView for an app.

The following is my code:

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

I realize that an error is occurring near the following:

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

Here is the logcat data:

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

A brief view of what the JSON looks like:

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

I appreciate if any suggestions could be thoroughly explained and demonstrated as to why this error is occurring. Thank you greatly.


回答1:


Replace

private static final String TAG_CARID = "car_id";

with

private static final String TAG_CARID = "CarID";

You JSONArray has key "CarID", whereas you are searching for "car_id".

Hope this helps :)




回答2:


"cars" is jsonArray in the jsonObject. You must get the array first and then extract values from it. I cant give you code example right now, because I am currently on my phone.



来源:https://stackoverflow.com/questions/31525327/jsonexception-no-value-for-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!