我知道我不应该在 UI 线程上运行与网络相关的东西,因此我使用 asynctask 通过远程服务器上的 php 从数据库中读取一些东西。但是,当代码到达 --HttpResponse response = httpclient.execute(httppost);-- 我收到错误 -- java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 -- 因此代码不起作用。
请注意,我这样调用 asyncTask —— new dataRetrievalViaAsyncTask().execute(url,url,url); (第二个和第三个“url”是虚拟的,因为它们没有被使用)——在 oncreate() 中。
那里有什么问题?
class dataRetrievalViaAsyncTask extends AsyncTask<String, String, String>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(String... f_url)
{
Log.i("tag", "inside doInBackground");
String url2 = f_url[0];
Log.i("tag", url2);
HttpClient httpclient = new DefaultHttpClient();
Log.i("tag", "done : HttpClient httpclient = new DefaultHttpClient();");
HttpPost httppost = new HttpPost(url2);
Log.i("tag", "done : HttpPost httppost = new HttpPost(url);");
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("tag", "done : httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));");
HttpResponse response = httpclient.execute(httppost);
Log.i("tag", "done : HttpResponse response = httpclient.execute(httppost);");
HttpEntity entity = response.getEntity();
Log.i("tag", "done : HttpEntity entity = response.getEntity();");
is = entity.getContent();
Log.i("tag", "after : is = entity.getContent();");
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection" + e.toString());
}
// convert response to string
return "a";
}
@Override
protected void onPostExecute(String result)
{
// enter code here
}
}