我有一个AsyncTask,我使用doInBackground方法从端点通过HTTP获取大量数据。我正在尝试将该数据传递到一个CustomAdapter,它在onPostExecute()方法中扩展BaseAdapter。 但数据没有得到更新。 知道我在这里做错了什么吗?
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listview_activity);
EventsAdapter eventsAdapter = new EventsAdapter(getActivity(), objects);
objects.add(new EventsObject("M2arius", "Shaorma2"));
listView.setAdapter(eventsAdapter);
return rootView;
}
public class FetchEmailActivityTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchEmailActivityTask.class.getSimpleName();
private final ProgressDialog dialog = new ProgressDialog(getActivity());
@Override
protected void onPreExecute() {
dialog.setMessage("Please Wait.");
dialog.setCancelable(true);
dialog.show();
}
@Override
protected String[] doInBackground(String... params) {
...
try {
return getActivityDataFromJson(activityJsonStr, limitParams);
} catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// This will only happen if there was an error getting or parsing the activity.
return null;
}
@Override
protected void onPostExecute(String[] result){
super.onPostExecute(result);
ArrayList<EventsObject> eventsList = new ArrayList<EventsObject>();
if (dialog.isShowing())
{
dialog.dismiss();
}
if (result != null){
objects.add(new EventsObject("Marius", "Shaorma"));
eventsAdapter = new EventsAdapter(getActivity(), objects);
if (objects != null) {
eventsAdapter.notifyDataSetChanged();
} else {
Log.v(LOG_TAG, "Objects: " + objects);
}
// New data is back from the server. Hooray!
}
}
}
答案 0 :(得分:1)
eventsAdapter = new EventsAdapter(getActivity(), objects);
onPostExecute
您正在创建适配器的新实例,但ListView包含旧实例。实例化后,再次调用setAdapter
if (getView() != null) {
ListView listView = (ListView) getView().findViewById(R.id.listview_activity);
if (listView != null) {
listView.setAdapter(eventsAdapter);
}
}