org.json.JSONException:all_advertisement没有值

时间:2014-07-09 05:13:36

标签: android json

我创建了一个应用程序。在该应用中,存在广告模块。该模块分为两部分:

  1. 制作广告
  2. 查看广告
  3. 但是当我点击vies广告时,Log-cat中会出现以下错误 以下代码显示all_advertisement没有值。但是我为参数输入的值已成功存储在数据库中。

        07-07 04:32:12.643: W/System.err(3306):    org.json.JSONException: No value for all_advertisements
        07-07 04:32:12.653: W/System.err(3306):     at org.json.JSONObject.get(JSONObject.java:355)
        07-07 04:32:12.653: W/System.err(3306):     at org.json.JSONObject.getJSONArray(JSONObject.java:549)
        07-07 04:32:12.653: W/System.err(3306):     at com.sunmobileappnow.mobileappnow.ViewAdvertise$ViewAdvertisement.doInBackground(ViewAdvertise.java:99)
        07-07 04:32:12.653: W/System.err(3306):     at com.sunmobileappnow.mobileappnow.ViewAdvertise$ViewAdvertisement.doInBackground(ViewAdvertise.java:1)
        07-07 04:32:12.653: W/System.err(3306):     at android.os.AsyncTask$2.call(AsyncTask.java:288)
        07-07 04:32:12.653: W/System.err(3306):     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        07-07 04:32:12.653: W/System.err(3306):     at 
    

    第一单元正常运作。创建广告并填写参数(如名称,移动设备,状态)并添加添加说明后,单击“发送”按钮可创建广告并将值存储在数据库中。该值以JSON格式存储。

    代码ID

                JSONObject jo = new JSONObject(data1);
    
                Log.d("response", jo.toString(4));
                if(jo.getString("err-code").equals("0"))
                {
    
    
                JSONArray jArray = jo.getJSONArray("all_advertisement");  
                Log.d("Array", jArray.toString(4));
    
    
    
    
                for (int j=0; j < jArray.length(); j++)
                {
                    try {
                        JSONObject jsob = jArray.getJSONObject(j);
    
                        mname = jsob.getString("name");   
                        mobile = jsob.getString("mbl_nmbr");   
                        state = jsob.getString("states");   
                        desc = jsob.getString("desc");   
    
    
                        nameArray.add(jsob.getString("name").toString());
    
                        mobileArray.add(jsob.getString("mbl_nmbr").toString());
    
                        stateArray.add(jsob.getString("states").toString());
    
                        descArray.add(jsob.getString("desc").toString());
    
                        HashMap<String, String> adHash = new HashMap<String, String>();
    
                        adHash.put("name", jsob.getString("name").toString());
    
                        adHash.put("mbl_nmbr", jsob.getString("mbl_nmbr").toString());
    
                        adHash.put("states", jsob.getString("states").toString());
    
                        adHash.put("desc", jsob.getString("desc").toString());
    
                        //adsArray.add(adHash);
    
                          // adapter = new ArrayAdapter<String>(ViewAdvertise.this, R.layout.listrow, stateArray);   
    

    }

    response.
    
    
    07-08 01:19:39.547: D/response(1434): {
    07-08 01:19:39.547: D/response(1434):     "data": [
    07-08 01:19:39.547: D/response(1434):         {
    07-08 01:19:39.547: D/response(1434):             "id": "53",
    07-08 01:19:39.547: D/response(1434):             "desc": "",
    07-08 01:19:39.547: D/response(1434):             "status": "2",
    07-08 01:19:39.547: D/response(1434):             "name": "vivek",
    07-08 01:19:39.547: D/response(1434):             "states": "",
    07-08 01:19:39.547: D/response(1434):             "mbl_nmbr": "",
    07-08 01:19:39.547: D/response(1434):             "user_id": "45",
    07-08 01:19:39.547: D/response(1434):             "date_time": "2014-07-07 05:16:29"
    07-08 01:19:39.547: D/response(1434):         }
    07-08 01:19:39.547: D/response(1434):     ],
    07-08 01:19:39.547: D/response(1434):     "err-code": "0"
    07-08 01:19:39.547: D/response(1434): }
    

    完整的JAVA代码

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.view_ads);
            pref=this.getSharedPreferences("Driver", MODE_WORLD_READABLE);
            login_token = pref.getString("login_token","login_token"); 
            list=(ListView) findViewById(R.id.list);   
            tv1=(TextView) findViewById(R.id.text2);
            tv2=(TextView) findViewById(R.id.text4);
            tv3=(TextView) findViewById(R.id.text5);
            tv4=(TextView) findViewById(R.id.text6);
            new ViewAdvertisement().execute();
    
        }
        private class ViewAdvertisement extends AsyncTask<String, String, String[]> {
            String mname,mobile,state,desc;
    
            @Override
            protected String[] doInBackground(final String... params) 
            {
                ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                if (conMgr.getActiveNetworkInfo() != null
                        && conMgr.getActiveNetworkInfo().isAvailable()
                        && conMgr.getActiveNetworkInfo().isConnected()) 
                {
                    HttpClient httpclient = new DefaultHttpClient();
    
                    JSONObject job1= new JSONObject();
                    try 
                    {
                        job1.put("status_key","2");
                        job1.put("method", "view_add");
                        job1.put("state", state);
                        job1.put("login_token", login_token);
    
                        StringEntity se = new StringEntity(job1.toString());
    
                         HttpPost httppost = new HttpPost("http://suntechwebsolutions.com/clients/DGCapp/webservice.php");
    
    
    
                        httppost.setEntity(se);
    
                        HttpResponse response1 = httpclient.execute(httppost);
                        String data1 = EntityUtils.toString(response1.getEntity());
                        System.out.println("response "+data1);
    
    
    
                        JSONObject jo = new JSONObject(data1);
    
                        Log.d("response", jo.toString(4));
                        if(jo.getString("err-code").equals("0"))
                        {
    
    
                        JSONArray jArray = jo.getJSONArray("all_advertisement");  
                        Log.d("Array", jArray.toString(4));
    
    
    
    
                        for (int j=0; j < jArray.length(); j++)
                        {
                            try {
                                JSONObject jsob = jArray.getJSONObject(j);
    
                                mname = jsob.getString("name");   
                                mobile = jsob.getString("mbl_nmbr");   
                                state = jsob.getString("states");   
                                desc = jsob.getString("desc");   
    
    
                                nameArray.add(jsob.getString("name").toString());
    
                                mobileArray.add(jsob.getString("mbl_nmbr").toString());
    
                                stateArray.add(jsob.getString("states").toString());
    
                                descArray.add(jsob.getString("desc").toString());
    
                                HashMap<String, String> adHash = new HashMap<String, String>();
    
                                adHash.put("name", jsob.getString("name").toString());
    
                                adHash.put("mbl_nmbr", jsob.getString("mbl_nmbr").toString());
    
                                adHash.put("states", jsob.getString("states").toString());
    
                                adHash.put("desc", jsob.getString("desc").toString());
    
                                //adsArray.add(adHash);
    
                                  // adapter = new ArrayAdapter<String>(ViewAdvertise.this, R.layout.listrow, stateArray);   
    
                            } 
                            catch (JSONException e) 
                            {
                                e.printStackTrace();
                            } 
    
                        }
    
                        }
                    }
                    catch (Exception e) 
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    final AlertDialog.Builder alert = new AlertDialog.Builder(ViewAdvertise.this);
                    alert.setTitle("Alert !");
                    alert.setMessage("No Internet connection ");
                    alert.setPositiveButton("Ok",
                            new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog,
                                int whichButton) 
                        {
                            dialog.dismiss();
    
    
                        }
                    });
                    runOnUiThread(new Runnable() 
                    {
                        public void run() 
                        {
                            //pDialog.dismiss();
                            alert.show();
                        }
                    });
                }
    
                return params;
    
            }             
    
            @SuppressLint("NewApi")
            @Override
            protected void onPostExecute(String[] result) 
            {
    
    
                super.onPostExecute(result);
                //  adapter.clear();
                /*adapter.notifyDataSetChanged();  */
                //  adapter.clear();
                adapter = new ArrayAdapter<String>(ViewAdvertise.this, R.layout.listrow, stateArray);   
    
                list.setAdapter(adapter);   
    
                adapter.notifyDataSetChanged();
    
    
    
                //  adapter.addAll(stateArray);
    
    
    
                /*tv1.setText(desc);
                tv2.setText(mname);
                tv3.setText(mobile);
                tv4.setText(state);*/
    
                System.out.print("Original contents of al: ");
                Iterator<String> itr = nameArray.iterator();
                while (itr.hasNext()) {
                    String element = itr.next();
                    System.out.print(element + " ");
                }
                System.out.println();   
    
    
                System.out.print("Original contents of al: ");
                Iterator<String> itr1 = stateArray.iterator();
                while (itr.hasNext()) {
                    String element = itr1.next();
                    System.out.print(element + " ");
                }
                System.out.println();   
                //  ListView lv = getListView();
    
                // listening to single list item on click
                list.setOnItemClickListener(new OnItemClickListener() {
                    int position;
    
                    public void onItemClick(AdapterView<?> parent, View view,
                            int position, long id) {
    
                        // selected item 
                        // String product = ((TextView) view).getText().toString();
                        long index = parent.getSelectedItemId();
                        this.position=position;
                        // Launching new Activity on selecting single List Item
                        Intent i = new Intent(getApplicationContext(), ViewAds.class);
                        // sending data to new activity
    
                        i.putStringArrayListExtra("nameArray", nameArray);
                        i.putStringArrayListExtra("mobileArray", mobileArray);
                        i.putStringArrayListExtra("stateArray", stateArray);
                        i.putStringArrayListExtra("descArray", descArray);
    
                        //i.putExtra("adArray", adsArray);
    
                        i.putExtra("position", position);
                        startActivity(i);
    
                    }
                });
            }
        }
    }
    

    在服务器端

    function view_add($ data) {     $ user_id = NULL;

    if ($user_id = getUser($data -> login_token))
    {
        $status_key     = mysql_real_escape_string($data->status_key);
        $msg = array();
    
        $get_state = mysql_fetch_assoc(mysql_query("SELECT State FROM advertisement where id='$user_id'"));
        $sql = mysql_query("SELECT * FROM advertisement WHERE states='{$get_state['State']}'");
    
        if (mysql_affected_rows() > 0)
        {
            while($add = mysql_fetch_assoc($sql))
            {
                $msg[] = $add;
            }
            return array("err-code" => '0', "data" => $msg);
        }
        else
        {
            return array("message" => "There is no Add for you.", "err-code" => "400");
        }
    }
    else
    {
        return array("err-code"=>"1","data"=>"Session Expired");
    }
    

    }

1 个答案:

答案 0 :(得分:0)

使用jo.getJSONArray("all_advertisement");时,android会在all_advertisement对象中查找带有jo键的jsonArray。但是,您发布的示例JSON字符串不包含具有该键的任何数组。您的解析机制应如下所示:

String response = //contains your JSON String. 
JSONObject responseObject = new JSONObject(response);
JSONArray jArray = responseObject.getJSONArray("data");
//Since you have only one object in the data array, 
//you can use get(0) but incase you have multiple objects 
//just loop through the array to retrieve all 
//required objects from the data array.
String id = jArray.get(0).getString("id");
String desc = jArray.get(0).getString("desc");
...
...