2016-04-30 83 views
-3

我有一个String图像路径,它具有所选图像的路径。如果用户选择图像,我必须在服务器上传它。我想检查一下imagepath是否为空。我已经尝试过,但它给NullPointerException图像路径中的NullPointerException

这是我的代码。

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

,我检查,如果它是空的:

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); 
      } 

如果我不选择任何图片,它显示了NullPointerException。请帮帮我。这里有什么问题。

回答

1

试试这个:

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

更多的参考检查:

Checking if a string is empty or null in Java

更具体的方法来检查字符串是否为空或不使用TextUtils

if (TextUtils.isEmpty(imagepath)) { 
    Log.d(TAG, "imagepath is empty or null!"); 
} 
+0

' TextUtils.isEmpty'会为你做到这一点 –

+0

@ cricket_007是的,你是对的.. –

0

首先看到两个字符串不是在继续之前为null。试试这个:

if(imagepath!=null) { 

    //Do your stuff 
    uploadfile(imagepath); 

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

    //Do your stuff 
    uploadfile(imagepath1); 

} else { 
    // Handle the exception 
} 
1

你应该使用try catch来处理这个异常,因为NullPointerException异常时,对象没有任何价值或没有定义,你在这里不选择,这就是为什么NullPointerExcepion发生任何图像发生Reference for nullPointerException