gpt4 book ai didi

java - Listview.setAdapter...当我从另一个选项卡返回时崩溃

转载 作者:行者123 更新时间:2023-12-01 12:02:38 32 4
gpt4 key购买 nike

我有一个带有 3 个选项卡的 Activity,其中第一个是带有 ListView 的 fragment 。 ListView 有自定义适配器。当我开始以及当我进入第二个选项卡并返回时没有问题。但是当我转到第三个选项卡并返回第一个选项卡时, fragment 执行 onCreateView 并因 nullpointerexception 崩溃,这是我的代码:

fragment :

List<Post> rings;
View headerView;


public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

rootView = inflater.inflate(R.layout.fragment_within_ring, container, false);
headerView = getActivity().getLayoutInflater().inflate(R.layout.header_list_view, null);

new consultarRing().execute(); //This get the Array from web service to rings

return rootView;
}

private void fullyAdapter() {

if (rings != null) {

adapter = new PostsAdapter(getActivity(), R.layout.item_row_show_ring, rings, false, null);

lyt = (PullAndLoadListView) getActivity().findViewById(R.id.listView_withinring);

lyt.addHeaderView(headerView); //crash here
lyt.setAdapter(adapter); //crash here


//crash all down
lyt.setOnRefreshListener(new OnRefreshListener() {
//OnRefreshListener

@Override
public void onRefresh() {
// TODO Auto-generated method stub
new PullToRefreshDataTask().execute();
}
});
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {

@Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
lyt.setOnScrollListener(new AbsListView.OnScrollListener() {

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
switch (firstVisibleItem) {
case 1:
Main.isScrolling = false;
break;
case 2:
Main.isScrolling = true;
break;
default:
break;
}
}
});
}
}

private class consultarRing extends AsyncTask<String, String, CollectionResponsePost> {

@Override
protected void onPreExecute() {
//do staff
}

@Override
protected CollectionResponsePost doInBackground(String... args) {
//do staff, get rings
}

@Override
protected void onPostExecute(CollectionResponsePost responsePost) {

//call fullyAdapter() method
fullyAdapter();
}
}

我的问题是当 ListView 托盘第二次设置适配器时,我不知道如何重置 ListView 以像新的一样开始。请帮忙。

最佳答案

您在onCreateView内执行AsyncTask。此时, fragment 的 View 层次结构尚未添加到 Activity 的 View 层次结构中,因此如果您搜索 fragment 的 View ,getActivity().findViewById() 将返回 null

稍后尝试启动 AsyncTask:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

new consultarRing().execute();
}

关于java - Listview.setAdapter...当我从另一个选项卡返回时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27880957/

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