我遇到一个代码问题,我必须从restservices中检索数据并将其显示在listview中....
private class surveyCheck extends AsyncTask<String, Integer,List<SurveyMetaData>> {
protected List<SurveyMetaData> doInBackground(String... params) {
if (mdebug_flag) {
Log.i(TAG_DEBUG, "SurveyCheck:doInBackground");
}
String url = params[0];
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(request);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(), "Error " + statusCode
+ " for URL " + url);
return null;
}
HttpEntity responseEntity = response.getEntity();
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
Gson gson=new Gson();
Type collectionType=new TypeToken<List<SurveyMetaData>>(){}.getType();
List<SurveyMetaData> result =gson.fromJson(reader,collectionType);
for( SurveyMetaData element : result)
{
Log.d("TAG","I 'm doing stuff with: " + element);
}
Survey_DB dataobj = new Survey_DB(getApplicationContext());
for (int i = 0; i <result.size() ; i++) {
if (dataobj.AddSurvey(result.get(i)) != -1)
ToastUtils.displayToast(Available_Surveys.this,
"Survey Inserted successfully",
(ViewGroup) findViewById(R.id.llRoot));
}
Survey_Adapter adapter = new Survey_Adapter(
getApplicationContext(), R.layout.list_item_menu,
result);
listView1 = (ListView) findViewById(R.id.listview_surveys);
listView1.setAdapter(adapter);
// Populate text field return result;
} catch (IOException e) {
request.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
return null;
}
}
代码正在接收流,读者可以在添加时读取相同内容 AddSurvey(result.get(i))...它将空值传递给插入的参数..
答案 0 :(得分:0)
您正在从后台线程执行UI tasks
。
像
ToastUtils.displayToast(Available_Surveys.this,
"Survey Inserted successfully",
(ViewGroup) findViewById(R.id.llRoot));
和
Survey_Adapter adapter = new Survey_Adapter(
getApplicationContext(), R.layout.list_item_menu,
result);
listView1 = (ListView) findViewById(R.id.listview_surveys);
listView1.setAdapter(adapter);
在onPostExecute
AsyncTask
中执行与UI相关的任务