JSONException没有价值for..Android应用 [英] JSONException No value for..Android app

查看:252
本文介绍了JSONException没有价值for..Android应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有这个特定错误的许多职位,但他们都不是解决我的问题,我是新来的Andr​​oid开发。由于这个错误的结果,我无法看到在ListView的数据的应用程序。

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.

以下是我的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;
                }

下面是logcat的数据:

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

什么样的​​JSON看起来像一个简单的观点:

A brief view of what the JSON looks like:

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

我AP preciate如有意见可以充​​分解释和证明,为什么这个错误发生。谢谢很大。

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

推荐答案

替换

private static final String TAG_CARID = "car_id";

private static final String TAG_CARID = "CarID";

您JSONArray具有关键CarID,而您正在搜索car_id。

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

希望这有助于:)

这篇关于JSONException没有价值for..Android应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆