我的代码在解析数据时返回 null
值。
也可以告诉我,我们检索到的数据可以显示在列表中吗?
这是我的代码
主活动 和 servicehandler .java public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://maps.googleapis.com/maps/api/place/details/json?reference= CnRsAAAA9ErLnmGfgp5Z67O5YXj3cDefnl7_-aVpk8Gy-bA0jJ3T1b8MZbnNTfCr93U5ylAIlU_6T-1paayMmG48-Sk0UWjMea_oC_qecuPKiL2A_cwoVs-K9EuGfOqhmOKO31g0PQdLDEScBl9cDXEU_txF2BIQjmaqLKCitDU8c1Rg-8aIGBoUSTdyLb9MCOmv0Vh9nGNxQVSgg94&sensor=false&key=AIzaSyC7x-9sdw_fYwS-e4WLoXB1QaC8OpES9pA";
// JSON Node names
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
});
// Calling async task to get json
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);
Log.d("Response: ", "> " + jsonStr);
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
/* ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_LONGNAME, TAG_SHORTNAME,
TAG_TYPES }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
*/
}
}
public class ServiceHandler {
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();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
尝试以下代码调用URL并在字符串中获取其响应。
public static String callRequestWebservice(String p_url) {
String m_response = null;
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(p_url);
HttpResponse response;
System.err.println("Request URL---------->" + p_url);
try {
response = client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
StringBuilder sb = new StringBuilder();
String line = "";
BufferedReader bf = new BufferedReader(
new InputStreamReader(in));
while ((line = bf.readLine()) != null) {
sb.append(line);
}
m_response = sb.toString();
System.err.println("JSON Response--->" + m_response);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return m_response;
}
eidted:
解析响应如下:
try {
JSONObject m_obj = new JSONObject(response);
JSONObject result_obj = m_obj.getJSONObject("result");
JSONArray m_arr = result_obj
.getJSONArray("address_components");
Log.e("Formate", result_obj.getString("formatted_address"));
Log.e("geometry", result_obj.getString("geometry"));
for (int i = 0; i < m_arr.length(); i++) {
JSONObject m_sJobj = m_arr.getJSONObject(i);
Log.e("ICon", m_sJobj.getString("long_name"));
Log.e("Name", m_sJobj.getString("short_name")
+ "City---" + m_sJobj.getString("types"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
更改您的代码如下:
private class GetContacts extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// Making a request to url and getting response
String jsonStr = callRequestWebservice(url);
Log.d("Response: ", "> " + jsonStr);
return jsonStr;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if(result !=null)
{
try {
JSONObject m_obj = new JSONObject(result);
JSONObject result_obj = m_obj.getJSONObject("result");
JSONArray m_arr = result_obj
.getJSONArray("address_components");
Log.e("Formate", result_obj.getString("formatted_address"));
Log.e("geometry", result_obj.getString("geometry"));
for (int i = 0; i < m_arr.length(); i++) {
JSONObject m_sJobj = m_arr.getJSONObject(i);
Log.e("ICon", m_sJobj.getString("long_name"));
Log.e("Name", m_sJobj.getString("short_name")
+ "City---" + m_sJobj.getString("types"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Updating parsed JSON data into ListView
* */
/* ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { TAG_LONGNAME, TAG_SHORTNAME,
TAG_TYPES }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
*/
}