6

I'm trying to display a Snackbar in the screen with some File data that I retrieve in the onActivityResult() method after taking a photo.

The thing is that the View that is passed to the Snackbar returns null and I cannot display it.

This is the code of the onActivityResult() method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
    File f = new File(mCurrentPhotoPath);

    if (this.getCurrentFocus() != null)
      Snackbar.make(this.getCurrentFocus(), f.length() / (1024 * 1024) + " MB, " + f.getPath(), Snackbar.LENGTH_INDEFINITE).show();
  }
}

Any idea why this happen?

Thanks!

ישו אוהב אותך
  • 22,515
  • 9
  • 59
  • 80
Iván Guerra
  • 61
  • 2
  • 4

2 Answers2

8

This is because when you calling another Activity, the current focus is lost in the caller Activity so it's set to null.

As the documentation says:

View getCurrentFocus ()

Return the view in this Window that currently has focus, or null if there are none. Note that this does not look in any containing Window.

You can use the root view of your activity for the Snackbar:

// Get the root current view.
View view = findViewById(android.R.id.content);
Snackbar.make(view, f.length() / (1024 * 1024) + " MB, " + f.getPath(), Snackbar.LENGTH_INDEFINITE).show();

UPDATE

Please be noted that

findViewById(android.R.id.content);

may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not). As in the https://stackoverflow.com/a/4488149/4758255 says.

you can use:

final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
            .findViewById(android.R.id.content)).getChildAt(0);

But better just set id to this view in your xml layout and use this id instead.

Or as op has said, we can use:

View v1 = getWindow().getDecorView().getRootView();
Community
  • 1
  • 1
ישו אוהב אותך
  • 22,515
  • 9
  • 59
  • 80
  • 1
    Thanks for the answer! Sorry for the late response, I found another solution for this. `View v = getWindow().getDecorView().getRootView();` This way I obtain the root view of the Activity and pass it as the first parameter in the `Snackbar.make()` method – Iván Guerra Feb 16 '17 at 18:45
  • No problem. I've integrated your solution to my answer. In case someone else stumbles upon the same problem. – ישו אוהב אותך Feb 17 '17 at 02:57
-3

You can use getCurrentFocus() for view in an activity. you will almost always get a view. It is nullable though

sabbibJAVA
  • 1,008
  • 1
  • 11
  • 17