gpt4 book ai didi

java - Android 中出现空指针异常问题

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

这是错误

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 24397
java.lang.NullPointerException
at com.example.myapplication.ui.main.SectionsPagerAdapter.getItem(SectionsPagerAdapter.kt:43)
at androidx.fragment.app.FragmentPagerAdapter.instantiateItem(FragmentPagerAdapter.java:105)
at androidx.viewpager.widget.ViewPager.addNewItem(ViewPager.java:1010)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1158)
at androidx.viewpager.widget.ViewPager.populate(ViewPager.java:1092)
at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1622)
at android.view.View.measure(View.java:24530)

这是我认为有问题的代码

FragmentPagerAdapter

@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
if (mCurTransaction == null) {
mCurTransaction = mFragmentManager.beginTransaction();
}

final long itemId = getItemId(position);

// Do we already have this fragment?
String name = makeFragmentName(container.getId(), itemId);
Fragment fragment = mFragmentManager.findFragmentByTag(name);
if (fragment != null) {
if (DEBUG) Log.v(TAG, "Attaching item #" + itemId + ": f=" + fragment);
mCurTransaction.attach(fragment);
} else {
fragment = getItem(position);
if (DEBUG) Log.v(TAG, "Adding item #" + itemId + ": f=" + fragment);
mCurTransaction.add(container.getId(), fragment,
makeFragmentName(container.getId(), itemId));
}
if (fragment != mCurrentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}

return fragment;
}

SectionsPagerAdapter

override fun getItem(position: Int): Fragment {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return when(position){
1 -> input
2 -> history
3 -> chart
else -> throw NullPointerException()
}
}

我的 fragment 可以返回空 fragment ,因此我在 PagerAdapter 中抛出 NullPointerException。有人可以帮助我为什么我会遇到 NullPointerException 吗?非常感谢

最佳答案

位置0开始,而不是从1开始。请尝试以下操作:

override fun getItem(position: Int): Fragment {

return when(position){
0 -> input
1 -> history
2 -> chart
else -> throw NullPointerException()
}
}

此外,您的 getCount 应该返回 3

override fun getCount(): Int {
return 3
}

关于java - Android 中出现空指针异常问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59608119/

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