Android - getIntent () from fragment

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

send bitmap using Android intent

I am having problems with a fragment of host activity using getIntent (). It does not recognize the method. there are some messages out there saying that its impossible to use getIntent () in a fragment ... but should there be a way? should the code work in the host?

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(); } } 
+15
source share
4 answers

You can use getIntent() with Fragments , but first you need to call getActivity() . Maybe something like getActivity().getIntent().getExtras().getString("image") .

+34
source

Itโ€™s not that you cannot transfer data, it is what you do not want.

From the documentation for the snippet:

Often you need one fragment to communicate with another, for example, to change the content depending on the user's event. All communication of the fragment with the fragment is carried out through the associated activity. Two fragments should never communicate directly.

If you look at the Fragment documentation, it will help you understand how to do this.

+5
source

If you want to get intent information, you must call the Fragment's getArguments() method, which returns a Bundle with additional functions.

+2
source

You can also achieve this with Fragment using setArguments() and getArguments() , for example:

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

Hope this also helps.

+1
source

Source: https://habr.com/ru/post/1206922/


All Articles