【发布时间】:2014-01-24 20:40:06
【问题描述】:
我有一个填充了数据库的列表视图,带有一个自定义光标适配器 SavedTripsAdapter。
这是我初始化适配器的方式: allTrips = mDb.fetchAllTrips();
String[] from = new String[] { "purp", "fancystart", "fancyinfo", "endtime", "start", "distance", "status" };
int[] to = new int[] { R.id.TextViewPurpose, R.id.TextViewStart,
R.id.TextViewInfo };
sta = new SavedTripsAdapter(getActivity(),
R.layout.saved_trips_list_item, allTrips, from, to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
lv.setAdapter(sta);
当我单击一个列表项时,我可以通过调用以下函数再次上传它,该函数在 AsyncTask 中完成。
在 FragmentSavedTripsSection 中:
private void retryTripUpload(long tripId) {
TripUploader uploader = new TripUploader(getActivity());
uploader.execute();
}
在 TripUploader 中:
@Override
protected void onPostExecute(Boolean result) {
try {
if (result) {
Toast.makeText(mCtx.getApplicationContext(),"Trip uploaded successfully.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mCtx.getApplicationContext(),"Cycle Atlanta couldn't upload the trip, and will retry when your next trip is completed.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// Just don't toast if the view has gone out of context
}
}
但是,TripUploader 是一个单独的类。当行程上传成功时,数据库更新,所以我想使用 savedTripsAdapter.notifyDataSetChanged() 刷新列表
应该把savedTripsAdapter.notifyDataSetChanged()放在哪里以及如何?
如果我把它放在列表视图类中,它不会被调用 onPostExecute。但是如果我把它放在 TripUploader 的 onPostExecute 函数中,我怎样才能访问我在列表视图类中实例化的同一个 savedTripsAdapter 实例?
感谢您的帮助!
【问题讨论】:
-
你是在 FragmentSavedTripsSection 类的 Lsitview 上设置适配器吗?
-
@amitsingh 我添加了一些代码。谢谢!
-
在“FragmentSavedTripsSection”类中创建一个“公共”函数,用于通知适配器并从 AsyncTask 的 onPostExecute() 调用该函数。
-
@amitsingh 我补充说: public void notifyDataSetChanged(){ sta.notifyDataSetChanged();我应该如何从 onPostExecute() 调用函数?
-
通过在 TripUploader 类的构造函数中发送该类的对象来访问它。
标签: android android-asynctask notifydatasetchanged