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(); } }
If you want get intent data, you have to call Fragment's method getArguments() , which returns Bundle with extras. Show activity on this post.
If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent);
Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.
You can use a getIntent()
with Fragments
but you need to call getActivity()
first. Something like getActivity().getIntent().getExtras().getString("image")
could work.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With