我已经看过几个教程,但它们都比防止主线程中的网络调用的 Android 更新更老。我尝试将调用它的代码移动到 RetrieveFeedTask,但这对我没有帮助,因为我无法在我的主线程中获取数据。这是我所做的:
class RetrieveFeedTask extends AsyncTask <String, Void, String>
{
private Exception exception;
private String doInBackground()
{
String returnString = "sample";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample_array.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
int step_num;
String description;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
step_num=json_data.getInt("step_num");
description=json_data.getString("description");
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No step found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
//System.out.println(result);
return result;
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return null;
}
}
然后在主线程中,我这样做了:
AsyncTask<String, Void, String> returnString = new RetrieveFeedTask().execute();
那么如何让这些信息在主线程中使用呢?