-1
public class GecodeFuncation {
public static String getLatLongByURL(String requestURL) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setDoOutput(true);
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
我這樣excuting的AsyncTask對象甲:值傳遞是在Android的
new GeocodeImplementation().execute("D-109 3rd floor ShakarPur Laxmi Nagar New Delhi 110092".replace(" ","%20"));
下面
是我AsyncTask
:
class GeocodeImplementation extends AsyncTask<String, Void, String[]> {
ProgressDialog dialog = new ProgressDialog(DataEntry.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
@Override
protected String[] doInBackground(String... params) {
String response;
try {
response = GecodeFuncation.getLatLongByURL("http://maps.google.com/maps/api/geocode/json?address="+params+"&sensor=false");
Log.d("response",""+response);
return new String[]{response};
} catch (Exception e) {
return new String[]{"error"};
}
}
@Override
protected void onPostExecute(String... result) {
try {
JSONObject jsonObject = new JSONObject(result[0]);
double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
Log.d("latitude", "" + lat);
Log.d("longitude", "" + lng);
} catch (JSONException e) {
e.printStackTrace();
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
當我通過地址的AsyncTask然後其網址變爲:
http://maps.google.com/maps/api/geocode/json?address=[Ljava.lang.String;@41fff330&sensor=false
所以我無法得到響應,而應該是
這樣我就可以得到響應,請告訴我,我做錯了。
params爲一個字符串...,什麼意味着是一個可變參數(字符串數組),而不是字符串,所以你必須通過使用params [0] –
如何訪問你的url,存儲在第一個位置如何執行taske –
這樣做: response = GecodeFuncation.getLatLongByURL(「your url」+ params [0] +「&sensor = false」 ); 讓一切都保持不變。 –