-3

I have a String imagepath which has path of the selected image. If user selects image i have to upload it on sever. I want to check wheter imagepath is null. I have tried this but it give NullPointerException.

This is my code.

public String imagepath = null;
public String imagepath1 = null;

and I am checking if it is null as:

   Log.e("imagepath",""+imagepath);
            Log.e("imagepath1", ""+imagepath1);

            if (imagepath.equals(null)){
                Log.e("no image path","dfdsfdsfdsfdsfdf");

            }
            else {
                uploadFile(imagepath);
            }

            if (imagepath1.equals(null)){
                Log.e("no imagepath1 path","imagepath1");

            }
            else {
                uploadFile2(imagepath);
            }

If I do not select any image, it shows NullPointerException. Please help me. What is wrong here.

USER9561
  • 1,084
  • 3
  • 15
  • 41

3 Answers3

1

Try this:

 if(imagepath != null && imagepath.isEmpty()) { /* do your stuffs here */ }

for more reference check this:

Checking if a string is empty or null in Java

more specific way to check if a string is null or not is using TextUtils:

if (TextUtils.isEmpty(imagepath )) {
    Log.d(TAG, "imagepath is empty or null!");
}
Community
  • 1
  • 1
Parsania Hardik
  • 4,593
  • 1
  • 33
  • 33
1

You should use try catch to handle this exception because NullPointerException occurs when object not have any value or not defined and here you are not selecting any image that's why NullPointerExcepion occured Reference for nullPointerException

PRIYA PARASHAR
  • 777
  • 4
  • 15
0

See first that the two strings are not null before proceeding. Try this:

if(imagepath!=null) {

    //Do your stuff
    uploadfile(imagepath);

} else {
    // Handle the exception
}
if(imagepath1!=null) {

    //Do your stuff
    uploadfile(imagepath1);

} else {
    // Handle the exception
}
Matei Radu
  • 2,038
  • 3
  • 28
  • 45