2014-08-28 89 views
0

我想从PHP MySql中填充Spinner。当我运行应用程序时,它获得org.json.JSONException: Value Category_code of type java.lang.String cannot be converted to JSONObject字符串无法在Android中转换为JSON对象

有人可以帮助我如何做到这一点。

这里是我的代码

public class Customer_Order_Detail extends Activity 
{ 
    private ArrayList<Category> categoriesList; 
    ProgressDialog pDialog; 
    Spinner spinnerCategory; 

    // Url to get all categories 
    private String URL_CATEGORIES = "http://192.168.1.102/client_vendor_mgmt/category_master.php"; 


    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.customer_order); 
     categoriesList = new ArrayList<Category>(); 
     spinnerCategory = (Spinner)findViewById(R.id.spinnerCategory); 
     new GetCategories().execute(); 
    } 

    /** 
    * Adding spinner data 
    * */ 
    private void populateSpinner() { 
     List<String> lables = new ArrayList<String>(); 

     for (int i = 0; i < categoriesList.size(); i++) 
     { 
      lables.add(categoriesList.get(i).getName()); 
     } 

     // Creating adapter for spinner 
     ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, lables); 

     // Drop down layout style - list view with radio button 
     spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 

     // attaching data adapter to spinner 
     spinnerCategory.setAdapter(spinnerAdapter); 
    } 


    /* 
    * Async task to get all categories 
    */ 

    private class GetCategories extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      pDialog = new ProgressDialog(Customer_Order_Detail.this); 
      pDialog.setMessage("Fetching categories.."); 
      pDialog.setCancelable(false); 
      pDialog.show(); 

     } 
     //org.apache.http.conn.HttpHostConnectException: Connection to http://192.168.1.102 refused 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      ServiceHandler jsonParser = new ServiceHandler(); 
      String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET); 

      Log.e("Response: ", " > " + json); 

      if (json != null) { 
       try 
       { 
        JSONObject jsonObj = new JSONObject(json); 

        if (jsonObj != null) 
        { 
         JSONArray categories = jsonObj.getJSONArray("category_master");      

         for (int i = 0; i < categories.length(); i++) 
         { 
          JSONObject catObj = (JSONObject) categories.get(i); 
          Category cat = new Category(catObj.getInt("cat_id"),catObj.getString("cat_name")); 
          categoriesList.add(cat); 
         } 
        } 

       } 
       catch (JSONException e) 
       { 
        e.printStackTrace(); 
       } 

      } 
      else 
      { 
       Log.e("JSON Data", "Didn't receive any data from server!"); 
      } 

      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) 
     { 
      super.onPostExecute(result); 
      if (pDialog.isShowing()) 
       pDialog.dismiss(); 

      populateSpinner(); 
     } 

    } 


} 

这是我的日志猫信息

08-28 16:39:17.854: E/Response:(531): Category_code:--ELEC1Category_nameElectronics 
08-28 16:39:17.917: W/System.err(531): org.json.JSONException: Value Category_code of type java.lang.String cannot be converted to JSONObject 
08-28 16:39:17.964: W/System.err(531): at org.json.JSON.typeMismatch(JSON.java:107) 
08-28 16:39:17.964: W/System.err(531): at org.json.JSONObject.<init>(JSONObject.java:158) 
08-28 16:39:17.964: W/System.err(531): at org.json.JSONObject.<init>(JSONObject.java:171) 
08-28 16:39:17.964: W/System.err(531): at com.customer.demo.Customer_Order_Detail$GetCategories.doInBackground(Customer_Order_Detail.java:91) 
08-28 16:39:17.974: W/System.err(531): at com.customer.demo.Customer_Order_Detail$GetCategories.doInBackground(Customer_Order_Detail.java:1) 
08-28 16:39:17.984: W/System.err(531): at android.os.AsyncTask$2.call(AsyncTask.java:185) 
08-28 16:39:17.984: W/System.err(531): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 
08-28 16:39:17.984: W/System.err(531): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 
08-28 16:39:17.984: W/System.err(531): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 
08-28 16:39:17.984: W/System.err(531): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 
08-28 16:39:17.994: W/System.err(531): at java.lang.Thread.run(Thread.java:1019) 

这里是我的ServiceHandeller

public class ServiceHandler { 

    static InputStream is = null; 
    static String response = null; 
    public final static int GET = 1; 
    public final static int POST = 2; 

    public ServiceHandler() { 

    } 

    /* 
    * Making service call 
    * @url - url to make request 
    * @method - http request method 
    * */ 
    public String makeServiceCall(String url, int method) { 
     return this.makeServiceCall(url, method, null); 
    } 

    /* 
    * Making service call 
    * @url - url to make request 
    * @method - http request method 
    * @params - http request params 
    * */ 
    public String makeServiceCall(String url, int method, 
      List<NameValuePair> params) { 
     try { 
      // http client 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpEntity httpEntity = null; 
      HttpResponse httpResponse = null; 

      // Checking http request method type 
      if (method == POST) { 
       HttpPost httpPost = new HttpPost(url); 
       // adding post params 
       if (params != null) { 
        httpPost.setEntity(new UrlEncodedFormEntity(params)); 
       } 

       httpResponse = httpClient.execute(httpPost); 

      } else if (method == GET) { 
       // appending 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(); 
      is = httpEntity.getContent(); 

     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } catch (ClientProtocolException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(
        is, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      response = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error: " + e.toString()); 
     } 

     return response; 

    } 
} 
+0

可以发布服务器的响应? – 2014-08-28 11:28:38

+0

@ Michael Shrestha - 类别代码: - ELEC1Category_nameElectronics。这是来自服务器的响应。 – tazeen 2014-08-28 11:34:39

+0

发布'Log.e(“Response:”,“>”+ json);'你的logcat。 – GrIsHu 2014-08-28 11:34:50

回答

0

这是你需要什么..

JSONObject jsonObject = new JSONObject(jsonString); 

为此,您只需将一个字符串传递给构造函数。

+3

发布的问题有'JSONObject jsonObj = new JSONObject(json);'是不是一样?另外stacktrace表示* org.json.JSONException:类型java.lang.String的Category_code不能转换为JSONObject * – Raghunandan 2014-08-28 11:30:08

+0

@Raghunandan:是这样的 – tazeen 2014-08-28 11:33:38

+0

@tazeen检查'makeServiceCall'中的响应。确保你有一个有效的json返回。 – Raghunandan 2014-08-28 11:34:29

0

从你的logcat行Category_code:--ELEC1Category_nameElectronics它表明你没有得到实际的json格式的响应。它是简单的字符串格式。

这就是为什么你不能将它转换为JSONObject,你在你的代码中如下所示。

JSONObject jsonObj = new JSONObject(json); 

您必须进入String值。

+0

- 感谢您的回复。对不起,但我没有得到你。 – tazeen 2014-08-28 11:39:54

+0

@tazeen你需要先学习JSON ..然后在你的应用程序中使用。 – 2014-08-28 11:41:45

+0

@tazeen你从服务器的实际响应就像是'Category_code: - ELEC1Category_nameElectronics',它是无效的json格式。这就是为什么你不能使用JSONObject解析它。 – GrIsHu 2014-08-28 11:43:24