7

For example, In a list view hosted by ListActivity, when user click on a item on the list, a new activity will be launched, and previous activity transfer extra data to the new activity like below:

public class Notepadv2 extends ListActivity {
    ...

   @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        Intent i = new Intent(this, NoteEdit.class);
        i.putExtra(NotesDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
     }
}

How it should be If I use fragments? I mean if I have one Activity which host 2 fragments, and make fragments transactions like below:

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

how can I transfer extra data from one fragment to the other fragment through the host activity?

I know on android developer webpage, there is a good document of how to use fragment and how to communicate with activity, but there is no description about how to transfer data from one fragment to another....

Leem.fin
  • 38,249
  • 74
  • 184
  • 323
  • 1
    possible duplicate of [Android: Pass data(extras) to a fragment](http://stackoverflow.com/questions/15392261/android-pass-dataextras-to-a-fragment) – Jim G. Feb 16 '14 at 13:45

2 Answers2

22

Use

Bundle data = new Bundle();
data.putString("name",value);
Fragment fragment = new nameOfFragment();
fragment.setArguments(data);
.navigateTo(fragment);
Its not blank
  • 2,897
  • 20
  • 37
  • Do you mean I do not need to define interface in fragment and let the host activity to implement the interface which set up a communication between fragment and host acvitity... instead, I can use your code to directly navigate to the next fragment? – Leem.fin Feb 03 '12 at 12:03
  • 1
    @its not blank Can you please shed more light on .navigateTo(fragment); android studio doesnt seem to recognize this – archon92 Jan 11 '15 at 06:44
  • navigate to was my local method. – Its not blank Jan 12 '15 at 04:19
4

From Activity you send data with intent as:

Bundle bundle = new Bundle();
bundle.putString("key", "value");
// set Fragmentclass Arguments
Fragmentclass fragmentobj = new Fragmentclass();
fragmentobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("key");    
    return inflater.inflate(R.layout.fragment, container, false);
}

I hope it is help full to you.

Neeraj Singh
  • 971
  • 8
  • 15