NullPointerException in Fragment's onCreateView() method

前端 未结 2 1912
情书的邮戳
情书的邮戳 2020-12-21 06:53

My code:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // t-alk és impresszumhoz
         


        
相关标签:
2条回答
  • 2020-12-21 07:28

    Here are the internals of the Fragment life cycle:


    FragmentManager sets the activity value for a Fragment performing a state transition:

    f.mActivity = mActivity;
    f.mFragmentManager = mActivity.mFragments;
    f.mCalled = false;
    f.onAttach(mActivity);
    

    Also, it sets this value to null, after detaching the Fragment:

    f.mCalled = false;
    f.onDetach();
    
    . . .
    
    f.mActivity = null;
    f.mFragmentManager = null;
    

    So, The value should not be null, between onAttach() and onDetach(), if every thing else is fine.


    To be safe, move all such code to onActivityCreated();

    0 讨论(0)
  • 2020-12-21 07:35

    First I needed to inflate the layout, to be able to use findViewById() .

    Finally the solution:

    This is not needed:

    LinearLayout layout = (LinearLayout) view
                    .findViewById(R.layout.impresszum);
    

    Instead this should be used:

    View view = inflater.inflate(R.layout.impresszum, container, false);
    

    And another modification in this line:

    ((TextView) **view**.findViewById(R.id.impresszumtext1))
                            .setText(appName + " v." + versionName);
    

    I have found some explanation, too: If I am thinking right, first I needed to inflate the layout to be able to access the objects using "findViewById"... It is sneaking, because setcontentview() does this for us.

    0 讨论(0)
提交回复
热议问题