这是我第一次使用AsyncTask,所以如果错误非常愚蠢会道歉......
这是mi课程:
class HttpAsyncTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... urls)
{
return null;
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result)
{
Log.i("ASYNC", "size: "+todo.size());
displayListView();
}
public String POST(String url)
{
InputStream inputStream = null;
String result = "";
try
{
HttpClient httpclient = new DefaultHttpClient();
//make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
// pass parameters in this way
for(int i=0;i<preguntas.length;i++)
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id",String.valueOf(preguntas[i])));
nameValuePairs.add(new BasicNameValuePair("te",tablas[i]));
//add data
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
{
result = convertInputStreamToString(inputStream);
NumPregTem todoAux = new NumPregTem();
todoAux.setBBDD(preguntas[i]) ;
todoAux.setTema(tablas[i]);
String[] aux = result.split(";");
todoAux.setPreg(aux[0]);
todoAux.setRespA(aux[1]);
todoAux.setRespB(aux[2]);
todoAux.setRespC(aux[3]);
todoAux.setRespD(aux[4]);
todoAux.setRespV(aux[5]);
todo.add(todoAux);
}
else
{
result = "Did not work!";
}
}
Log.i("ASYNC", "i've finished to query");
}
catch (Exception e)
{
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
}
我的问题是在debbuger中我看到了消息Log.i(&#34; ASYNC&#34;,&#34; size:&#34; + todo.size());在消息Log.i之前的onPostExecute()中(&#34; ASYNC&#34;,&#34;我已完成查询&#34;);在POST中,当我在我的主类(调用displayListView())中使用todo.get(i)时,此对象为null。
谢谢你!
我想在异步任务完成时调用displayListView()
PD:我在这个函数中调用POST(在我的主类中)
HttpAsyncTask httpAsyncTask = new HttpAsyncTask();
httpAsyncTask.execute("http://appdomain.hol.es/webService.php");
答案 0 :(得分:2)
您可能希望从POST()
这样调用doInBackground()
方法
@Override
protected String doInBackground(String... urls)
{
return POST(myUrl);
}
答案 1 :(得分:0)
好吧,粗略观察...... doInBackground()方法是异步调用的代码。该方法完成后,它将调用onPostExecute()方法。现在,doInBackground()只返回null,它会立即调用onPostExecute()。
我不确定你什么时候调用你的POST方法,但如果你想在displayListView()之前执行它,那么就把它放在doInBackground()方法中。