40

I am trying to pass a bitmap from one fragment to another--and am using this post as a guide:

send Bitmap using intent Android

What i am having trouble with is in the receiving activity fragment using getIntent(). It doesn't recognize the method. there are some posts out there saying that its not possible to use getIntent() in a fragment... but there must be a way? should the code go in the host activity?

here is what i am trying:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String filename = getIntent().getStringExtra("image");
    try {
        FileInputStream is = this.openFileInput(filename);
        imageBitmap = BitmapFactory.decodeStream(is);
        is.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Community
  • 1
  • 1
StillLearningToCode
  • 2,271
  • 4
  • 27
  • 46

5 Answers5

97

You can use a getIntent() with Fragments but you need to call getActivity() first. Something like getActivity().getIntent().getExtras().getString("image") could work.

Fareya
  • 1,523
  • 10
  • 11
8

You can also achieve this with Fragment using setArguments() and getArguments(), like the following:

MyFragment fragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.putString("image", fileName);
fragment.setArguments(bundle);//Here pass your data

Now inside your fragment class ,for example inside onCreate() or onCreateView() do the following:

String fileName = this.getArguments().getString("image");
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Ali Ezzat Odeh
  • 2,093
  • 1
  • 17
  • 17
7

It's not that you can't pass data, it's that you don't want to.

From the Fragment documentation:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

If you take a look at the Fragment documentation, it should walk you through how to do this.

BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
  • 2
    Gave this an up vote not because it solves the question but is rather the proper approach. You should use the activity as the "medium" for having the fragments communicate with one another. – ChallengeAccepted Nov 14 '14 at 23:21
3

If you want get intent data, you have to call Fragment's method getArguments(), which returns Bundle with extras.

skywall
  • 3,956
  • 1
  • 34
  • 52
1

To get intent extra write this code in fragment

if (requireActivity().intent.hasExtra("key_name")) {
    val extra = requireActivity().intent.getStringExtra("key_name")
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Geek Tanmoy
  • 745
  • 1
  • 9
  • 20