Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - getIntent() from a Fragment

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();     } } 
like image 276
StillLearningToCode Avatar asked Nov 14 '14 22:11

StillLearningToCode


People also ask

How to get data from intent in fragment android?

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

How do I start an intent from a fragment?

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);

How do I pass data from fragment to fragment in Kotlin?

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.


2 Answers

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

like image 179
Fareya Avatar answered Sep 23 '22 07:09

Fareya


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.

like image 41
BlackHatSamurai Avatar answered Sep 23 '22 07:09

BlackHatSamurai