Search code examples
javaandroidandroid-fragmentsnullpointerexceptionpagerslidingtabstrip

NullPointerException when calling a Fragment method from Activity?


I'm getting a NullPointerException when calling a Fragment's method.

In my MainActivity:

  AddTab fragObj = (AddTab) getSupportFragmentManager().findFragmentById(R.layout.fragment_add);
 fragObj.receiveURL(sharedText);

receiveURL() is a method in my Fragment AddTab.

I'm using pagerslidingtabstrip in my app to create tabs and that Fragment is created by it's PagerAdapter class.

I'm not sure if it is right to create a new instance of the Tab, because already one exists. I don't know how to get access to that instance as well.

I'm getting a NullPointerException now. Can anyone please help me on how to call that method in the fragment?

EDIT :

AddTab.java :

public class AddTab extends Fragment implements View.OnClickListener {

...

}

fragment_add.xml :

<FrameLayout 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="com.example.nikhil.amazon1.Add">


    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:text="@string/URL"
        android:hint="@string/hint"
        android:layout_marginTop="200dp"
        android:layout_gravity="center_horizontal|top" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Track"
        android:id="@+id/button"
        android:layout_gravity="center" />

</FrameLayout>

Solution

  • If you use the <fragment> tag to include a Fragment in your layout, you can use find findFragmentById using the id you assigned for the Fragment in the xml. Example :

    <fragment
        ...
        android:id="@+id/fragment_id/>
    

    and

    AddTab fragObj = (AddTab)getSupportFragmentManager().findFragmentById(R.id.fragment_id);
    

    If you added your Fragment dynamically, use tags :

    String TAG = "fragment tag";
    
    FragmentTransaction ft;
    ft.add(containerViewId, fragment, TAG);
    

    and

    AddTab fragObj = (AddTab)getSupportFragmentManager().findFragmentByTag(TAG);