我想用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 :(得分:1)
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
看起来你得到的是一个String,你试图将它转换为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
使用快照完成示例:
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>
对齐
答案 1 :(得分:0)
您的网页未正确生成JSON,
"<!DOCTYPE"
在输出您的JSON字符串之前,似乎您正在输入一些HTML。
答案 2 :(得分: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.