3

I have an activity which contains BottomNavigationView and NavHostFragment.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);

    bottomNavigationView.setSelectedItemId(R.id.navigation_profile);

    NavController navController = Navigation.findNavController(this, R.id.myNavHostFragment);
    NavigationUI.setupWithNavController(bottomNavigationView, navController); 

I have also added onActivityResult method in this parent activity.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Toast.makeText(this,"Parent onActivity",Toast.LENGTH_SHORT).show();
    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

In the fragment, I have an ImageView in which I am using Intent to pick an image from the user.

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
this.startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);

And in the fragment's onActivityResult I am doing this:

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    Toast.makeText(getActivity(),"OnActivityResult",Toast.LENGTH_SHORT).show();

    // Result returned from launching the Intent to select image for profile
    if (requestCode == RC_PHOTO_PICKER && resultCode == Activity.RESULT_OK) {
        Toast.makeText(getActivity(),"Called",Toast.LENGTH_SHORT).show();
    }
}

The issue is onActivityResult is neither called in the parent activity and nor in the fragment.

I have tried various solutions provided in Answer1, Answer2, Answer3. But none of them are working!!

majurageerthan
  • 2,169
  • 3
  • 17
  • 30
Sagar Jogadia
  • 1,330
  • 1
  • 16
  • 25

3 Answers3

1

You cannot use Intent.createChooser() with Intent.GET_CONTENT - that's true for both activities and Fragments.

Instead, just use your Intent directly with startActivityForResult.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
0

Add the below code block to parent onActivityResult

for (Fragment fragment : getSupportFragmentManager().getFragments()) {
   //send result to all child fragment
       if(fragment!=this)
        fragment.onActivityResult(requestCode, resultCode, data);
    }
Giddy Naya
  • 4,237
  • 2
  • 17
  • 30
0

not too sure but could it be that the intent is being invoked by the fragment? can you please try to use a listener on when the imageView or button is clicked and then intercept it and invoke the intent from the parent activity?