gpt4 book ai didi

android - 如何在 onPostExecute() 中从 doInBackground() 添加数据到 BaseAdapter?

转载 作者:行者123 更新时间:2023-11-30 02:13:58 25 4
gpt4 key购买 nike

我有一个 AsyncTask,我在其中使用 doInBackground 方法通过 HTTP 从端点获取大量数据。我正在尝试将该数据传递到 CustomAdapter 中,该 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!
}
}
}

最佳答案

 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);
}
}

关于android - 如何在 onPostExecute() 中从 doInBackground() 添加数据到 BaseAdapter?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29683655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com