我对noob问题感到抱歉,但我对如何处理这个问题感到很难过......
1:我在测试USB连接手机时收到此错误,但在执行搜索时无法在AVD上测试。
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
2:在AVD中运行时,第一次JSON搜索成功,但一旦退出并尝试访问新搜索,结果为空。下面是搜索后实例化的JSON列表活动:
package com.example.georgiahistoricalmarkers;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainListActivity extends ListActivity {
// url to make request
private static String url = "http://www.georgiaplanning.com/DCAMarkerService/dcamarkerservice.markerservice.svc/rest/Locations?SearchText=";
// JSON Node names
private static final String TAG_MARKERSINRANGE = "GetAllMarkersInRangeResult";
private static final String TAG_DCAID = "DCA_ID";
private static final String TAG_MARKERTITLE = "MarkerTitle";
private static final String TAG_MARKERLATITUDE = "MarkerLatitude";
private static final String TAG_MARKERLONGITUDE = "MarkerLongitude";
// contacts JSONArray
JSONArray markersInRange = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String value = null;
Bundle extras = getIntent().getExtras();
if(extras != null){
value = extras.getString("markerSearch");
}
url = (url+value);
// Hashmap for ListView
ArrayList<HashMap<String, String>> markerList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
markersInRange = json.getJSONArray(TAG_MARKERSINRANGE);
// looping through All Contacts
for(int i = 0; i < markersInRange.length(); i++){
JSONObject c = markersInRange.getJSONObject(i);
// Storing each json item in variable
int dcaid = c.getInt(TAG_DCAID);
String markertitle = c.getString(TAG_MARKERTITLE);
double markerlongitude = c.getDouble(TAG_MARKERLATITUDE);
double markerlatitude = c.getDouble(TAG_MARKERLONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DCAID, Integer.toString(dcaid));
map.put(TAG_MARKERTITLE, markertitle);
map.put(TAG_MARKERLONGITUDE, Double.toString(markerlongitude));
map.put(TAG_MARKERLONGITUDE, Double.toString(markerlatitude));
// adding HashList to ArrayList
markerList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, markerList,
R.layout.list_item,
new String[] { TAG_MARKERTITLE, TAG_DCAID }, new int[] {
R.id.title, R.id.dcaid });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String passId = ((TextView) view.findViewById(R.id.dcaid)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleItemActivity.class);
in.putExtra(TAG_DCAID, passId);
startActivity(in);
}
});
}
}
以下是我的清单,如果这可能有助于理解这个问题:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.georgiahistoricalmarkers"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.georgiahistoricalmarkers.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainListActivity"
android:label="MainListActivity" >
</activity>
<activity
android:name=".SingleItemActivity"
android:label="SingleItemActivity" >
</activity>
</application>
答案 0 :(得分:0)
我们应在您的http请求标题中添加“application / x-www-form-urlencoded”。
在你的情况下,你正在等待接收一个json,所以加上这个:
httpost.setHeader("Content-type", "application/json;charset=utf8");
request.setHeader("Accept", "application/json");
问题是你收到的回复是html而不是json。希望这对您有用,如果有,请告诉我。
/ *编辑* / 使用此解析器:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json;charset=utf8");
HttpResponse httpResponse = httpClient.execute(httpGet);
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, "utf-8"), 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;
}
您还应该在线程或异步传输中执行请求。否则,您将在4.0到高于4.0的设备中获得网络例外。这就是我解决你的活动的方式:
public class MainListActivity extends ListActivity {
// url to make request
private static String url = "http://www.georgiaplanning.com/DCAMarkerService/dcamarkerservice.markerservice.svc/rest/Locations?SearchText=";
// JSON Node names
private static final String TAG_MARKERSINRANGE = "GetAllMarkersInRangeResult";
private static final String TAG_DCAID = "DCA_ID";
private static final String TAG_MARKERTITLE = "MarkerTitle";
private static final String TAG_MARKERLATITUDE = "MarkerLatitude";
private static final String TAG_MARKERLONGITUDE = "MarkerLongitude";
// contacts JSONArray
JSONArray markersInRange = null;
private ArrayList<HashMap<String, String>> markerList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String value = null;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getString("markerSearch");
}
url = (url + value);
markerList = new ArrayList<HashMap<String, String>>();
new DoMarkersSearchTask().execute();
}
class DoMarkersSearchTask extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
markersInRange = json.getJSONArray(TAG_MARKERSINRANGE);
// looping through All Contacts
for (int i = 0; i < markersInRange.length(); i++) {
JSONObject c = markersInRange.getJSONObject(i);
// Storing each json item in variable
int dcaid = c.getInt(TAG_DCAID);
String markertitle = c.getString(TAG_MARKERTITLE);
double markerlongitude = c.getDouble(TAG_MARKERLATITUDE);
double markerlatitude = c.getDouble(TAG_MARKERLONGITUDE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_DCAID, Integer.toString(dcaid));
map.put(TAG_MARKERTITLE, markertitle);
map.put(TAG_MARKERLONGITUDE, Double.toString(markerlongitude));
map.put(TAG_MARKERLONGITUDE, Double.toString(markerlatitude));
// adding HashList to ArrayList
markerList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getApplicationContext(), markerList, R.layout.list_item,
new String[] { TAG_MARKERTITLE, TAG_DCAID }, new int[] { R.id.title, R.id.dcaid });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
String passId = ((TextView) view.findViewById(R.id.dcaid)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleItemActivity.class);
in.putExtra(TAG_DCAID, passId);
startActivity(in);
}
});
}
}
}
希望这最终适合你:)