2013-12-13 136 views
0

我想使用json解析器填充listview。但我有以下錯誤:使用json解析器填充listview

12-12 22:49:39.812: ERROR/JSON Parser(1254): Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject 

JSONParse:

public class JSONParser { 
    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 
    // constructor 
    public JSONParser() { 
    } 
    public JSONObject getJSONFromUrl(String url) { 
     // Making HTTP request 
     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httpPost = new HttpPost(url); 
      HttpResponse httpResponse = httpClient.execute(httpPost); 
      HttpEntity 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, "iso-8859-1"), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 

      } 
      is.close(); 
      json = sb.toString(); 
     } catch (Exception e) { 
      Log.e("Buffer Error", "Error converting result " + e.toString()); 
     } 
     // try parse the string to a JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 
     // return JSON String 
     return jObj; 
    } 

} 

UpdateFromSite:

public class UpdateFromSite extends Activity { 
    ListView list; 
    TextView name; 
    TextView description; 
    TextView price; 
    Button Btngetdata; 
    ArrayList<HashMap<String, String>> newItemlist = new ArrayList<HashMap<String, String>>(); 
    //URL to get JSON Array 
    private static String url = "http://www.karocellen.com/newItem.json"; 
    //JSON Node Names 
    private static final String TAG_ITEM = "NewItem"; 
    private static final String TAG_NAME = "name"; 
    private static final String TAG_DESCRIPTION = "description"; 
    private static final String TAG_PRICE = "price"; 
    JSONArray NewItem = null; 

    @Override 
    protected void onCreate(Bundle bundle) { 
     super.onCreate(bundle); 
     setContentView(R.layout.updateapp); 
     newItemlist = new ArrayList<HashMap<String, String>>(); 
     Btngetdata = (Button)findViewById(R.id.getdata); 
     Btngetdata.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       //check internet connection 
       Boolean isInternetPresent = false; 
       ConnectionDetector cd; 
       cd = new ConnectionDetector(getApplicationContext()); 
       isInternetPresent = cd.isConnectingToInternet(); 

       if (isInternetPresent) { 
        new JSONParse().execute(); } 

       else { 
        Toast.makeText(getApplicationContext(),"You don't have internet connection.",Toast.LENGTH_SHORT).show(); 
            } 
        } 
     }); 
    } 



    private class JSONParse extends AsyncTask<String, String, JSONObject> { 


     private ProgressDialog pDialog; 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 


      name = (TextView)findViewById(R.id.nameNewItem); 
      description = (TextView)findViewById(R.id.descriptionNewItem); 
      price = (TextView)findViewById(R.id.priceNewItem); 
      pDialog = new ProgressDialog(UpdateFromSite.this); 
      pDialog.setMessage("Getting Data ..."); 
      pDialog.setIndeterminate(false); 
      pDialog.setCancelable(true); 
      pDialog.show(); 
     } 
     @Override 
     protected JSONObject doInBackground(String... args) { 
      try { 
       JSONParser jParser = new JSONParser(); 
       // Getting JSON from URL 
       JSONObject json = jParser.getJSONFromUrl(url); 
       return json; 
      } catch (Exception ex){ 
       Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show(); 
       return null; 
      } 

     } 
     @Override 
     protected void onPostExecute(JSONObject json) { 
      pDialog.dismiss(); 
      try { 
       // Getting JSON Array from URL 
       NewItem = json.getJSONArray(TAG_ITEM); 
       for(int i = 0; i < NewItem.length(); i++){ 
        JSONObject c = NewItem.getJSONObject(i); 

        // Storing JSON item in a Variable 
        String name = c.getString(TAG_NAME); 
        String description = c.getString(TAG_DESCRIPTION); 
        int price = c.getInt(TAG_PRICE);     
        // Adding value HashMap key => value 
        HashMap<String, String> map = new HashMap<String, String>(); 
        map.put(TAG_NAME, name); 
        map.put(TAG_DESCRIPTION, description); 
        map.put(TAG_PRICE, Integer.toString(price)); 
        newItemlist.add(map); 
        list=(ListView)findViewById(R.id.listupdate); 
        ListAdapter adapter = new SimpleAdapter(UpdateFromSite.this, newItemlist, 
          R.layout.updateapprow, 
          new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] { 
          R.id.nameNewItem,R.id.descriptionNewItem, R.id.priceNewItem}); 
        list.setAdapter(adapter); 
        }); 
       } 
      } 

      catch (Exception e) { 
       Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 


    } 

myJSON:

{"NewItem":[{"name":"Roast Ground Coffee","description":"Folgers Medium Classic Roast Ground Coffee 339 oz","price":8},{"name":"Seattle coffee","description":"Seattles Best Coffee Level 3 Whole Bean 12oz","price":10},{"name":"Medium Roast Bean Coffee","description":"Dunkin Donuts Original Blend Medium Roast Whole Bean Coffee 12 oz","price":6},{"name":"Espresso coffee","description":"Starbucks Dark Espresso Roast Whole Bean Coffee 12 oz","price":12}, 
{"name":"China Green Tea","description":"Tazo China Green Tips Tea 20 filterbags","price":8},{"name":"China Organic Green","description":"Uncle Lees Legends of China Organic Green Tea 100 Tea Bags","price":15},{"name":"Black Tea","description":"Tazo Earl Grey Black Tea 20 count","price":10},{"name":"Chai Spiced Black Tea","description":"Tazo Decaf Chai Spiced Black Tea Latte Concentrate 32 oz","price":5}, 
{"name":"Passion Tea","description":"Tazo Iced Passion Tea 6ct","price":11},{"name":"Peach Iced Tea","description":"Lipton Diet Peach Iced Tea Mix 2.9 oz","price":12}]} 
+0

看起來你的迴應是一個字符串而不是json – Raghunandan

+0

打印這個字符串'json = sb.toString();'並顯示輸出。 – SilentKiller

+0

以「price」字符串格式打印價格:「11」 –

回答

1
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject 

看起來像你得到的是一個字符串,而您試圖將其轉換成一個JSONObject

你做一個HttpPost,而不是HttGet的

HttpPost httpPost = new HttpPost(url); 

應該是

HttpGet httpget = new HttpGet(url); 

您的JSON

{ // json object node 
    "NewItem": [ // json array NewItem 
     { // json object node 
      "name": "Roast Ground Coffee", // string 
      "description": "Folgers Medium Classic Roast Ground Coffee 339 oz", 
      "price": 8 
     }, 

第二個錯誤

catch (Exception ex){ 
       Toast.makeText(getApplicationContext(),"network problem",Toast.LENGTH_SHORT).show(); 
       return null; 

doInbackground顯示敬酒。你不能在doInbackground

完整的例子有快拍UI更新:

test.java

public class test extends Activity { 
     ListView list; 
     Button Btngetdata; 
     ProgressDialog pDialog; 
     ArrayList<HashMap<String, String>> newItemlist = new ArrayList<HashMap<String, String>>(); 

     private static final String TAG_ITEM = "NewItem"; 
     private static final String TAG_NAME = "name"; 
     private static final String TAG_DESCRIPTION = "description"; 
     private static final String TAG_PRICE = "price"; 

     @Override 
     protected void onCreate(Bundle bundle) { 
      super.onCreate(bundle); 
      setContentView(R.layout.test); 
      pDialog = new ProgressDialog(test.this); 
      pDialog.setMessage("Getting Data ..."); 
      newItemlist = new ArrayList<HashMap<String, String>>(); 
      Btngetdata = (Button)findViewById(R.id.button1); 
      Btngetdata.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 
        new JSONParse().execute(); 

       } 
      }); 
     } 


     private class JSONParse extends AsyncTask<String, Void, Void> { 

      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
       pDialog.show(); 
      } 
      @Override 
      protected Void doInBackground(String... args) { 
       try { 
        Log.i("...............","Hello.............."); 
        DefaultHttpClient httpClient = new DefaultHttpClient(); 
        HttpGet httpPost = new HttpGet("http://www.karocellen.com/newItem.json"); 
        HttpResponse httpResponse = httpClient.execute(httpPost); 
        HttpEntity httpEntity = httpResponse.getEntity(); 
        String jsonstring = EntityUtils.toString(httpEntity); 
        Log.i("...............",jsonstring); 
        JSONObject json = new JSONObject(jsonstring); 
        JSONArray newitem = json.getJSONArray(TAG_ITEM); 
        for(int i = 0; i < newitem.length(); i++){ 
         JSONObject c = newitem.getJSONObject(i); 
         String name = c.getString(TAG_NAME); 
         String description = c.getString(TAG_DESCRIPTION); 
         String price = c.getString(TAG_PRICE); 
         Log.i("...............",name); 
         HashMap<String, String> map = new HashMap<String, String>(); 
         map.put(TAG_NAME, name); 
         map.put(TAG_DESCRIPTION, description); 
         map.put(TAG_PRICE, price); 
         newItemlist.add(map); 
        } 

       } catch (Exception ex){ 


       } 
       return null; 

      } 
      @Override 
      protected void onPostExecute(Void result) { 
       super.onPostExecute(result); 
       pDialog.dismiss(); 
       list=(ListView)findViewById(R.id.list); 
       ListAdapter adapter = new SimpleAdapter(test.this, newItemlist, 
         R.layout.second, 
         new String[] { TAG_NAME,TAG_DESCRIPTION, TAG_PRICE }, new int[] { 
         R.id.textView1,R.id.textView2, R.id.textView3}); 
       list.setAdapter(adapter);       

      } 
     } 

} 

的test.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <ListView 
     android:id="@+id/list" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_above="@+id/button1" 
     /> 


    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentBottom="true" 
     android:layout_centerHorizontal="true" 
     android:text="Button" /> 

</RelativeLayout> 

second.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <TextView 
     android:id="@+id/textView1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="16dp" 
     android:text="TextView" /> 

    <TextView 
     android:id="@+id/textView2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/textView1" 
     android:layout_below="@+id/textView1" 
     android:layout_marginTop="50dp" 
     android:text="TextView" /> 

    <TextView 
     android:id="@+id/textView3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignLeft="@+id/textView2" 
     android:layout_below="@+id/textView2" 
     android:layout_marginTop="56dp" 
     android:text="TextView" /> 

</RelativeLayout> 

SNA p enter image description here

+1

我真的很感激。非常感謝你 – samira

+1

@sami你也做了一個http帖子而不是http get。我認爲那是你的問題。下一個領帶確保你做了一個獲取請求來獲取數據,併發佈一個帖子請求來發布一些東西到服務器。 – Raghunandan

0

您的網頁無法正確生成JSON,

"<!DOCTYPE" 

看起來你在輸出你的JSON字符串之前會輸入一些HTML。

+0

我解釋我的問題http://stackoverflow.com/questions/20580267/parsing-json-file-from-server – samira

0
Change your json response should be for price like... 
{ 
"NewItem": [ 
    { 
     "name": "Roast Ground Coffee", 
     "description": "Folgers Medium Classic Roast Ground Coffee 339 oz", 
     "price": "8" 
    } 
] 
} 
get price value as string and then you can cast it into (Integer value) in your code. 
+0

不,我有這個錯誤呢:錯誤解析數據org.json.JSONException:值java.lang.String類型的<!DOCTYPE無法轉換爲JSONObject – samira

+1

@sami檢查我的帖子 – Raghunandan