Convert null object to String
Instead of catching the exception or putting conditions, use String.valueOf(result.getPropertyAsString(0));
It will call toString() method of the argument and will convert it to String and if result.getPropertyAsString(0) is null, then it wil change it to "null"
Though its not a good practice, But You can concatenate the null value with "" to make it a String.
For ex:
String str=null; System.out.println((str+"").length()); /// prints 4
result.getPropertyAsString(0)
alone will result in a NPE already when the property is internally null. Your stacktrace points to SoapObject.getPropertyAsString(SoapObject.java:165)
which should be
public String getPropertyAsString(int index) { PropertyInfo propertyInfo = (PropertyInfo) properties.elementAt(index); return propertyInfo.getValue().toString();}
source - it will crash when propertyInfo
or propertyInfo.getValue()
is null
.
To prevent that from happening you need to get the property not via getPropertyAsString
but via getProperty
and convert it manually to a String
.
You can encapsulate that into some utility method
public static String getPropertyAsString(SoapObject object, int index) { Object prop = object.getProperty(index); if(prop instanceof PropertyInfo) { prop = ((PropertyInfo)prop).getValue(); } return String.valueOf(prop); // will make it "null" if it is null}
and then do
deleteuserDetails.setUserId(getPropertyAsString(result, getPropertyAsString(4)));deleteuserDetails.setUserName(getPropertyAsString(result, getPropertyAsString(2)));deleteuserDetails.setUserRole(getPropertyAsString(result, getPropertyAsString(3)));