How do I know if a Uri is empty?
Asked Answered
H

5

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.

Hernardo answered 25/2, 2015 at 23:22 Comment(0)
N
26

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

        if (!Uri.EMPTY.equals(followUri)) {
            //handle followUri
        }
Naga answered 25/2, 2015 at 23:42 Comment(0)
S
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
}
Scrag answered 25/2, 2015 at 23:35 Comment(0)
B
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.

Barbell answered 25/2, 2015 at 23:30 Comment(0)
C
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

Conah answered 25/2, 2015 at 23:36 Comment(0)
H
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
}
Helgeson answered 17/8, 2021 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.