9

I have an application where I need to be able to let the user decide how to put a picture profile, (camera or gallery). I have only one variable of type "Uri" but I do not understand how to reset it and make it EMPTY, or check if it is EMPTY. Because when I choose a picture I have to have the ability to change the photo if you do not like the one just put.
I have tested as

 if (followUri.equals (Uri.EMPTY)) {...}

but the application crashes with a null point exception.

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
Alex Voicu
  • 107
  • 1
  • 1
  • 5

5 Answers5

24

Just check that Empty URI is not equal to followUri, this check includes check by null:

        if (!Uri.EMPTY.equals(followUri)) {
            //handle followUri
        }
13

If the Uri itself is null then calling followUri.equals(Object) will result in a NPE. A better solution:

if (followUri != null && !followUri.equals(Uri.EMPTY)) {
    //doTheThing()
} else {
    //followUri is null or empty
}
Michael Powell
  • 746
  • 4
  • 11
1

If your app crashes with an NPE at that stage followUri is most likely null.

Also Uri objects are immutable, see here http://developer.android.com/reference/android/net/Uri.html so you cannot "reset" it.

ci_
  • 8,594
  • 10
  • 39
  • 63
0

Check if followUri != null and after that you can check if it is empty, you get NPE because followUri is null don't you? After that you can set followUri = Uri.EMPTY

DoubleK
  • 542
  • 3
  • 16
0

Just to add my 2 cents a null Uri is not treated as Empty. The value of Uri.EMPTY is "". Which can cause some confusion if you are expecting null == Uri.EMPTY to be trueenter code here. A small kotlin code snippet as well :

 fun isUriEmpty(uri: Uri?):Boolean{
    return uri == null || uri == Uri.EMPTY
}
Salil Kaul
  • 157
  • 1
  • 9