Aeonia Aeonia - 4 months ago 7
Java Question

Reading array values from return method

How can I safely read both of my array values from another class method without the nullexception warning coming up.I am getting both values orreclty just worried about the "Array access x[0] may produce NPE " warning without using intents

public Class ImageUtility{

public static String[] savePicture(Context context, Bitmap bitmap) {

......

String[] arr = new String[2];
arr[0] = img_name;
arr[1] = img_path;

return arr;
}



public Class Others{

public void Test(){
String[] x = ImageUtility.savePicture(getActivity(), bitmap);
value_one= x[0]; //nullexception warning is here
value_two= x[1];

}

Answer

Try the following code

 public void Test(){
   try{
     String[] x = ImageUtility.savePicture(getActivity(), bitmap);
     if(x != null && x.Length >= 1){
       value_one= x[0]; 
       value_two= x[1];
     }
   }catch(NullPointerException e){
     //print log
   }
 }
Comments