0

I have two activities. And I passed the argument to the target activity by intent:

Bundle bundle = new Bundle();
bundle.putString("ImagePath", path);
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("paths", bundle);
startActivity(intent);

The target activity DetailActivity has a fragment, and I want to get the argument ImagePath in it. Now I have two method:

  1. I get the argument in the DetailActivity by getIntent() and then pass it to the fragment using setArgmunets()

  2. I get the argument in the target fragment using getActivity().getIntent() directly.

I like the method 2 and use it now because the clean code. But the Android Studio tell me the message Method invocation 'getIntent' may produce 'java.lang.NullPointerException' in getIntent().

So should I abandon the method 2?


Update: Final, I used the method 1, because of this answer :

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.

Alex Liu
  • 7
  • 1
  • 5

4 Answers4

1

You can check for extras..

Intent intent = getActivity().getIntent();

if(intent.hasExtra("paths")){
  // get the data
}else{
   // Do something else
}
Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
0

No, it's not about the intent. It's because in some point of the time(e.g. fragment has been detached from the activity) getActivity() method can return null. So, correct call will be the next:

if(getActivity != null) getActivity().getIntent()
Viktor Dolgalyov
  • 274
  • 2
  • 12
  • Another way: I want to call the parent activity some times likes `getActivity().getWindow().setFlags(...)`. Is this better to define variable in fragment's `onCreate()`: `if (getActivity() != null) mActivity = getActivity();` – Alex Liu Apr 24 '18 at 09:24
0

getActivity() on Fragment may produce null.

So you need to use either any interface for communication between activity and fragment or use bundle by passing in setArgument() in instance of fragment.

Janvi Vyas
  • 732
  • 5
  • 16
Azay Gupta
  • 281
  • 2
  • 16
0

Use Below Code :

  Bundle bundle = new Bundle();
        bundle.putString(Constants.BUNDLE_DATA, "From Activity");
        Fragment fragment = new Fragment();
        fragment.setArguments(bundle);

and in Fragment onCreateView method:

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

If you want to send large data ,then create a model and make that model implements Serializable .

Rohan Lodhi
  • 1,385
  • 9
  • 24