3

I currently have an app that relies heavily on Intents and the extras given to them before starting the activity. The extras are used when calling a webservice which in turn supplies the content that needs to be shown

I am trying to convert that model, to one where I have a static Fragment (lets call it Player) at the bottom of my screen, and another Fragment (lets call it Content) above it which will show the main content. By selecting options on the main screen other content will be shown by replacing the Content Fragment.

But, these new Fragments are currently the Intents that rely on the extras so heavily. Is there a way to replace a Fragment by a new one, but still be able to add extras to it?

If so, let's say I have the following piece of code:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_holder, new MusicAlbumList(), "albumlist");
        ft.commit();

How would I add the extras to the MusicAlbumList?

If that's not possible, how will I get the data that's currently being passed through extras into my new Fragment before it force closes due to missing essential data?

Sander van't Veer
  • 5,930
  • 5
  • 35
  • 50

2 Answers2

11

Or you can do this

MusicAlbumList fragment = new MusicAlbumList();
Bundle args = new Bundle();
args.putString("StringName","Value here");
fragment.setArguments(args);

then do your replace stuff. Then in the fragments onStart or onCreate call this.getArguments(); to pull the bundle, then get your extras out of there.

Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
Shaun
  • 5,483
  • 10
  • 40
  • 49
2

Change the constructor of MusicAlbumList from default constructor to one with arguments like new MusicAlbumList(int arg1, ...) and pass the values you want to set through the constructor

pankajagarwal
  • 13,462
  • 14
  • 54
  • 65
  • This was my first idea. Guessing I'll have to rewrite all classes to Fragments then (currently using FragmentActivities) – Sander van't Veer Dec 05 '11 at 10:21
  • I have been using the above mentioned way pretty successfully – pankajagarwal Dec 05 '11 at 10:23
  • Actually this is not recommended. The correct way is through providing an argument bundle. The problem is that if your fragment gets removed from memory and reconstructed then this constructor will not get called and you get hard to track down bugs. –  Oct 17 '13 at 11:45