0
我有一個程序從服務器下載JSON字符串。事情本來進行得很細,直到最近,當我嘗試調用模擬器不會執行AsyncTask.execute()。get()
jsonReader.execute(getUrl).get();
凡jsonReader是的AsyncTask下載JSON字符串和使用getURL是執行URL。這種方法從來沒有得到執行,奇怪的是,它在我的手機上運行。
這裏是我的代碼
方法,它調用JSON字符串讀者
private PointOfInterest getPointWithID(int id) {
String getUrl;
JSONReader jsonReader = new JSONReader();
try {
Log.d(TAG,"Trying to get ID: " + id);
getUrl = url + String.valueOf(id);
Log.d(TAG,"Trying to get json from: " + id); <-- Last Log line to get printed when run on emulator
jsonReader.execute(getUrl).get();
} catch (Exception e) {
e.printStackTrace();
}
String jsonString = jsonReader.returnJSONString();
Log.d(TAG,"Downloaded: " + jsonString);
//System.out.println("JSON: " + jsonString);
JSONResponse jsonResponse = JSONResponse.convertJSONToResponse(jsonString);
//System.out.println("JSON RESPONSE " + jsonResponse);
return jsonResponse.getPointofInterest();
}
jsonReader
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
/**
* Read JSON Strings
* @author Tom
*
*/
public class JSONReader extends AsyncTask <String, Void, String> {
String result;
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
StringBuilder sb = new StringBuilder();
String TAG = "JSONReader";
// constructor
public JSONReader() {
result = "";
}
@Override
protected String doInBackground(String... url) {
Log.d(TAG, "Executing " + url); <--Does not get printed when run on emulator
HttpPost httppost = new HttpPost(url[0]);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
// json is UTF-8 by default i believe
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}catch(Exception e){
e.printStackTrace();
}
return result = sb.toString();
}
public String returnJSONString(){
return result;
}
}
我曾嘗試重新啓動亞行,使得新的AVD的,但似乎沒有任何工作,我只選項正在測試我的手機,但是,這是不可取的,因爲我正在爲api 17開發。感謝您的幫助!
你的電話和AVD在Android版本? –
我測試的AVD是google-apis level 17.在安裝這個api之後,我想我注意到AVD會停止執行上面的代碼。 我的電話是2.1 – TomSelleck
你打電話給非ui線程執行嗎? –