我在过去 19 小时内尝试更新listFragment
但无法使用notifyDataSetChanged()
. 我已经访问了很多关于它的线程,但未能使其工作。我有一个父片段,里面有三个ListFragment
。s 需要在ListFragment
它们之间传递数据,我可以通过interface
. 信息正在成功传递。但是ListView
没有更新。这是我的尝试代码:
public class SubChaptersListFragment extends SherlockListFragment {
ArrayAdapter<String> mAdapter = null;
ArrayList<String> items = new ArrayList<String>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
Chapter instance = CompetitiveProgramming.chapterList.get(0);
for (int i = 0; i < instance.subchapterList.size(); i++) {
items.add(instance.subchapterList.get(i).subChapterTitle);
}
mAdapter = new ArrayAdapter<String>(getSherlockActivity(), layout, items);
setListAdapter(mAdapter);
}
@Override
public void onStart() {
super.onStart();
if (getFragmentManager().findFragmentById(
R.id.sub_sub_category_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
// this function is invoked from another `fragment` and position is retrieved successfully
public void updateList(int position) {
Chapter instance = CompetitiveProgramming.chapterList.get(position);
items.clear();
for (int i = 0; i < instance.subchapterList.size(); i++) {
items.add(instance.subchapterList.get(i).subChapterTitle);
}
mAdapter.notifyDataSetChanged(); // nullpointerException in this line
}
}
编辑 Logcat
08-13 18:33:30.670: E/AndroidRuntime(537): java.lang.NullPointerException
08-13 18:33:30.670: E/AndroidRuntime(537): at me.kaidul.uhunt.SubChaptersListFragment.updateList(SubChaptersListFragment.java:57)
08-13 18:33:30.670: E/AndroidRuntime(537): at me.kaidul.uhunt.CompetitiveProgramming.onChapterSelected(CompetitiveProgramming.java:214)
08-13 18:33:30.670: E/AndroidRuntime(537): at me.kaidul.uhunt.ChaptersListFragment.onListItemClick(ChaptersListFragment.java:60)
08-13 18:33:30.670: E/AndroidRuntime(537): at android.support.v4.app.ListFragment$2.onItemClick(ListFragment.java:58)
08-13 18:33:30.670: E/AndroidRuntime(537): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
08-13 18:33:30.670: E/AndroidRuntime(537): at android.widget.ListView.performItemClick(ListView.java:3382)
08-13 18:33:30.670: E/AndroidRuntime(537): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1696)
08-13 18:33:30.670: E/AndroidRuntime(537): at android.os.Handler.handleCallback(Handler.java:587)
这就是我从 parentFragment 调用片段的方式:
@Override
public void onChapterSelected(int position) {
SubChaptersListFragment subChapterFrag = new SubChaptersListFragment();
if ( subChapterFrag != null) {
subChapterFrag.updateList(position);
} else {
}
}