如何在 onPostExecute() 中从 doInBackground() 向 BaseAdapter 添加数据



我有一个AsyncTask,我使用doInBackground方法通过HTTP从端点获取一堆数据。我正在尝试将该数据传递到一个自定义适配器中,该适配器在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!
        }
   }
}
 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);
    }
}

相关内容

  • 没有找到相关文章

最新更新