【发布时间】:2014-12-19 15:01:11
【问题描述】:
我试图将一个对象从 doInBackground 传递到 OnPostExecute 但失败了。 我读过类似的主题,发现它们不相关。 (也许我没有足够的经验) 我是android的新手,想要一些指针。 为了便于阅读,我将粘贴相关代码而不是所有代码。
主要活动
public void processFinish(Question q) {
TextView tview;
tview = (TextView)findViewById(R.id.textView1);
tview.setText(q.getQuestion());
}
AsyncTask(Q 是一个对象)
public class getQus extends AsyncTask<String,Void,Question> {
public AsyncResponse delegate;
@Override
protected Question doInBackground(String... params) {
String range = "1";
// TODO Auto-generated method stub
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("range",range));
int q_id = 0;
String result=null;
String q_qus =" ";
String result2 = " ";
Question q = new Question();
InputStream is = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.6/fyp/qus.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);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result2=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
System.out.println("HEllo");
//parse json data
try{
JSONArray jArray = new JSONArray(result2);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","id: "+json_data.getInt("q_id")+
", qus: "+json_data.getString("q_qus")
);
q.setQid(json_data.getInt("q_id"));
q.setQuestion(json_data.getString("q_qus"));
return q;
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return q;
}
protected void onPostExecute(Question q) {
System.out.println("AT ONPOSTEXECUTE");
System.out.println(q.getQuestion());
delegate.processFinish(q);
}
}
调查结果: 我只能在控制台中看到我的 log.i 结果。 OnPostExecute 根本不会触发。
任何帮助或建议将不胜感激。 非常感谢!
【问题讨论】: