2014-08-28 91 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