Alex Rivera | Logout

NullPointerException in oncreateView() of Fragment

Asked 2013-03-26T18:22:49.757
11

This code below shows part of activity where the fragment is added.


    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.fragment_container, srkt_frag);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.commit();

    TabSpec specs1=mTab.newTabSpec("tag1");
    specs1.setContent(R.id.fragment_container);
    specs1.setIndicator("SRK/T");
    mTab.addTab(specs1);

mTab is TabHost where the srkt_frag is displayed as the content. the fragment class is shown below


public class Srkt_x extends Fragment 
{
    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            // TODO Auto-generated method stub
            View view=inflater.inflate(R.layout.activity_srkt_x,container,false);
            TextView text = (TextView) getView().findViewById(R.id.srkt_power);
            Float result=getArguments().getFloat("RESULT");
            text.setText(String.valueOf(result));
            return view;

        }

}

after executing the project i get nullpointerexception at line 21 i.e at

TextView text = (TextView) getView().findViewById(R.id.srkt_power);

my xml file is shown below


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context=".Srkt_x" >

<ScrollView
    android:id="@+id/srkt_scrollView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:background="@color/Black" >

    <RelativeLayout
        android
Edit
Report

1 Answer

1

The reason for your bug and confusion is due to not understanding how the Android event loop works.

You are calling getView() at a time when the fragment does not yet have one. The fragment will only have a view after onCreateView finishes running. The point of onCreateView is "to have the fragment instantiate its user interface view".

You should do getActivity().findViewById.

answered 2013-03-26T18:40:00.953

Your Answer