使用带有片段的部分,NullPointerException

Posted

技术标签:

【中文标题】使用带有片段的部分,NullPointerException【英文标题】:Using sections with fragments, NullPointerException 【发布时间】:2012-11-28 02:51:36 【问题描述】:

我之前通过使用 tablistener 并为每个片段设置一个类来完成带有选项卡的片段,现在我发现 Eclipse 允许您设置带有片段的选项卡或部分,所以我改用它。但现在我有一个问题。我在 mainactivity 类中创建了一个片段类。但是当我尝试更改文本视图中的数据时,我得到了一个空指针。

这里是代码

public class MainActivity extends FragmentActivity 

/**
 * The @link android.support.v4.view.PagerAdapter that will provide fragments for    each of the
 * sections. We use a @link android.support.v4.app.FragmentPagerAdapter derivative, which will
 * keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
 * to switch to a @link android.support.v4.app.FragmentStatePagerAdapter.
 */
SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The @link ViewPager that will host the section contents.
 */
ViewPager mViewPager;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // Create the adapter that will return a fragment for each of the three primary sections
    // of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());


    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setCurrentItem(2);


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;


@SuppressWarnings("deprecation")
@Override
public boolean onOptionsItemSelected(MenuItem item) 


    return true;



/**
 * A @link FragmentPagerAdapter that returns a fragment corresponding to one of the primary
 * sections of the app.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter 

    public SectionsPagerAdapter(FragmentManager fm) 
        super(fm);
    

    @Override
    public Fragment getItem(int i) 
        Fragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putInt(MainFragment.ARG_SECTION_NUMBER, i);
        fragment.setArguments(args);
        return fragment;
    

    @Override
    public int getCount() 
        return 4;
    

    @Override
    public CharSequence getPageTitle(int position) 
        switch (position) 
            case 0: return getString(R.string.title_section1).toUpperCase();
            case 1: return getString(R.string.title_section2).toUpperCase();
            case 2: return getString(R.string.title_section3).toUpperCase();
            case 3: return getString(R.string.title_section4).toUpperCase();
        
        return null;
    



public static class MainFragment extends Fragment 

    public static final String ARG_SECTION_NUMBER = "section_number";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        int position = args.getInt(ARG_SECTION_NUMBER);
        int tabLayout = 1;

        switch(position) 
        case 0:
            tabLayout = R.layout.tab1;
            break;
        case 1:
            tabLayout = R.layout.tab2;
            break;
        case 2:
            tabLayout = R.layout.tab3;
            break;
        case 3:
            tabLayout = R.layout.tab4;
            break;

        

        View view = inflater.inflate(tabLayout, container, false);

        TextView tv = (TextView) getActivity().findViewById(R.id.stats_squats);
        tv.setText("DEPRSTgjhndkpgfhn");




        return view;
    


我尝试了不同的方法来做到这一点:

        TextView tv = (TextView) getActivity().findViewById(R.id.stats_squats);
        tv.setText("DEPRSTgjhndkpgfhn");

        TextView tv = (TextView) getView().findViewById(R.id.stats_squats);
        tv.setText("DEPRSTgjhndkpgfhn");

        TextView tv = (TextView) view.findViewById(R.id.stats_squats);
        tv.setText("DEPRSTgjhndkpgfhn");

每次都出现同样的错误。

这里是 logcat 日志:

12-10 17:37:56.898: D/OpenGLRenderer(13574): Enabling debug mode 0
12-10 17:37:58.970: D/AndroidRuntime(13574): Shutting down VM
12-10 17:37:58.970: W/dalvikvm(13574): threadid=1: thread exiting with uncaught exception (group=0x40f82300)
12-10 17:37:58.980: E/AndroidRuntime(13574): FATAL EXCEPTION: main
12-10 17:37:58.980: E/AndroidRuntime(13574): java.lang.NullPointerException
12-10 17:37:58.980: E/AndroidRuntime(13574):    at no.whg.workout.MainActivity$MainFragment.onCreateView(MainActivity.java:189)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:871)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1083)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:635)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1431)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.view.ViewPager.populate(ViewPager.java:895)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.view.ViewPager.populate(ViewPager.java:772)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1234)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.View.measure(View.java:15172)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.View.measure(View.java:15172)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.widget.LinearLayout.measureVertical(LinearLayout.java:833)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.widget.LinearLayout.onMeasure(LinearLayout.java:574)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.View.measure(View.java:15172)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4816)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2435)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.View.measure(View.java:15172)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1850)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1102)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1275)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4214)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.Choreographer.doCallbacks(Choreographer.java:555)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.Choreographer.doFrame(Choreographer.java:525)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.os.Handler.handleCallback(Handler.java:615)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.os.Handler.dispatchMessage(Handler.java:92)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.os.Looper.loop(Looper.java:137)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at android.app.ActivityThread.main(ActivityThread.java:4931)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at java.lang.reflect.Method.invokeNative(Native Method)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at java.lang.reflect.Method.invoke(Method.java:511)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558)
12-10 17:37:58.980: E/AndroidRuntime(13574):    at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

尝试只输入 TextView tv = (TextView) findViewById(R.id.stats_squats);在 findView 方法之前没有任何方法。告诉我会发生什么。 TextView 定义在哪个布局文件中? 由于这个TextView是在一个fragment类里面而不是一个activity里面,所以这行不通,我们得到的消息是Cannot make a static reference to the non-static method findViewById(int) from the type Activity 【参考方案1】:

如果您查看Fragment documentation,您会发现onCreateView()onCreateActivity() 之前运行。 getActivity() 将在 onCreateView() 中返回 null。您需要将该部分移出onCreateView() 并覆盖onActivityCreated()..

【讨论】:

谢谢。如果我不是无神论者,我会认为你是上帝。 Err... 好的哈哈。这里没有上帝,之前偶然发现了这个:)

以上是关于使用带有片段的部分,NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章

带有片段参数的 Grails render()

带有许多片段的 Android 导航抽屉

MPEG DASH 部分片段

在片段部分使用YoutubePlayerView

在带有操作栏的活动中使用时,片段未完全显示

带有片段的两个面板 UI 与单独的活动