124697
124697

Reputation: 21893

Fragement getArguments() returns null

I'm trying to pass data from my activity to a fragment but I get a null pointer on Bundle.getString()

I've also noticed, that it goes to the fragment even without the fragment transaction code

Fragment:

public class MainFragment extends BrowseFragment {
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = this.getArguments();
        String myValue = bundle.getString("message");
    }

Activity

public class MainActivity extends FragmentActivity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Bundle bundle = new Bundle();
        String myMessage = "Stackoverflow is cool!";
        bundle.putString("message", myMessage );
        MainFragment fragInfo = new MainFragment();
        fragInfo.setArguments(bundle);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.main_browse_fragment, fragInfo);
        transaction.commit();
    }

activity_main.xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_browse_fragment"
    android:name="my.package.MainFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:deviceIds="tv"
    tools:ignore="MergeRootFrame" />

Upvotes: 0

Views: 166

Answers (1)

wichnator
wichnator

Reputation: 91

Change the fragment in your xml layout to simple FrameLayout. Creation of fragment from xml cause the exception, because it hasn't arguments (They are added manually in your Activity code)

Upvotes: 2

Related Questions