Search code examples
androidandroid-fragmentsandroid-fragmentactivity

How to pass bundle into fragment using getSupportFragmentManager?


I have an activity which receives a bundle from another activity. The bundle is a simple url string. The receiving activity launches a fragment using getSupportFragmentManager as shown below, and this works as expected.

I would like to pass the url string on to the fragment, but cannot find a way to do this. All the examples I have seen use different patterns to launch the fragment. Any suggestions appreciated!

See my comment as to why this is not exactly a duplicate of another question.

import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;

public class GalleryActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_gallery);

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
            getSupportActionBar().setBackgroundDrawable(
                    new ColorDrawable(Color.parseColor("#273134")));

            //Get the URL string from the calling activity

            String url = super.getIntent().getExtras().getString("urlString");

            Toast.makeText(this, "URL String is: " + url, Toast.LENGTH_LONG).show();

/*
Here is a new bundle. How do we get this passed to the new fragment?
            Bundle bundle = new Bundle();
            bundle.putString("url", url);
*/

            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.content, RecyclerViewFragment.newInstance())
                    .commit();
        }
    }

Solution

  • you can set the bundle in the fragment using the setArguments on fragment instance. you can find more info in the docs. for your example:

    Fragment fragment = RecyclerViewFragment.newInstance();
    
    Bundle bundle = new Bundle();
    bundle.putString("url", url);
    
    fragment.setArguments(bundle);
    
    getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.content, fragment)
            .commit();
    

    and in your onCreate or onCreateView in the fragment use:

    String url =  getArguments().getString("url")
    

    Answered question in the stackoverflow: setArguments - getArguments