NullPointerException in imagepath [duplicate] - android

This question already has answers here:
Check whether a String is not Null and not Empty
(35 answers)
Closed 6 years ago.
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.

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

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

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
}

Related

Picasso ImageError

I am using Picasso to show images from server in my android App.I have 5 image URL (HTTP form) getting from server and storing it in a String value.If i send a Correct link to Picasso (.jpg form) it Runs correctly and show my image in my imageview and if send a wrong link in (.pdf form) it shows error in my Image View,But when ever i pass null value or empty value from my server to string my app crash its running if statement first even if its value is null or empty else statement is not running what should i update in my code so that if i get null value from server my imageview should show and error and text view value should be changed.
// Code only where my If/Else Start :
if (image_fourth != null && image_fourth != ""){
Picasso.get().load(image_fourth).resize(200, 200).placeholder(R.drawable.placeholder).error(R.drawable.error).into(image1);
image1.setVisibility(View.VISIBLE);
buttons.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (image_second == null){
image_2t.setText("Image Not Found");
image_2t.setVisibility(View.GONE);
}
else if (image_second != null){
Picasso.get().load(image_second).resize(200, 200).placeholder(R.drawable.placeholder).error(R.drawable.error).into(image2);
image2.setVisibility(View.VISIBLE);
image_2t.setText("Image 2");
image_2t.setVisibility(View.VISIBLE);
}
}
});
}
else{
image_1t.setText("Image Not Found");
}
Use Glide instead of Picasso, then you don't need to add any other conditions or code to check if the string is empty or not,
Check this sample
Glide.with(activity_context)
.load(your_url)
.placeholder(R.drawable.default_image)
.error(R.drawable.default_image)
.override(200, 200)
.centerCrop()
.dontAnimate()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(mHolder.imgIcon);
you can find more about Glide here
if you want to do continue with Picasso, try this code, this may help you
if(!TextUtils.isEmpty(Url)) {
Picasso.with(activity).load(Url.replace(" ", "%20")).error(R.drawable.default_image).networkPolicy(NetworkPolicy.NO_CACHE)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.into(imageView, new Callback() {
public void onSuccess() {
System.out.println(" 02062015:onSuccess");
}
#Override
public void onError() {
imageView.setImageResource(R.drawable.default_image);
System.out.println(" 02062015:onError");
}
});
}
You could try reversing the if/else statement. Picasso, as far as I know, cannot take a null or empty string in load(). In your case the if statement could cover if the string/url source is null you could load a placeholder:
if (url == null || url.isEmpty()) {
Picasso.with(context).load(placeholder).transform(transformation).into(this)
} else {
Picasso.with(context).load(url).error(placeholder).transform(transformation)
.placeholder(placeholder).into(this)
}
Another option might be to keep your if statement as it is but add this to the else statement:
else
image_fourth.setImageResources(R.mipmap.ic_launcher);
I have used similar techniques with Glide. That worked for me. For more info you can check this stackoverflow answer: Picasso doesn't tolerate empty String URL?
Just switch between statements and check is it working?
if (image_fourth == null || image_fourth == ""){
//write your else statement here
}else{
//And if code is here
}

Why do I I get null point exception even though I safeguarded against it?

How do I safeguard against null points? I tried this way:
var spr = context.getSharedPreferences("FAV", Context.MODE_PRIVATE)
var emptyArray: JsonArray = jsonArray()
var myjson = spr.getString("KEY", null)
//GET JSON FROM SHARED PREFERENCE
Log.d("TAG", "NOT NULL")
if(myjson != null) {
var parsedFavFromJson = Gson().fromJson<List<String>>(myjson)
//PARSE FROM JSON TO ARRAY
for (i in parsedFavFromJson) {
emptyArray.add(i)
Log.d("TAG", "" + i)
if (i == recipeArray!![counterX].recipeKey!!) {
Picasso.with(context)
.load(R.drawable.fav_icon_60at3x).into(favMarkerButton)
Log.d("TAG", "Match " + i)
} else {
Log.d("TAG", "WAS NULL")
Picasso.with(context)
.load(R.drawable.fav_unclicked_icon60at3x).into(favMarkerButton)
}
}
}
I have clearly stated the conditional if(myjson != null), still it pass through and crash with the error message java.lang.IllegalStateException: fromJson(json, typeToken<T>()) must not be null. There is no clear indication where the error actually occur - it actually points to an empty code line! If I remove the code above, things are working fine. I also tried using:
var myjson = spr.getString("KEY", null).let {
...and so on, with the same result. Am I missing something here?
UPDATE
I checked variable myjson and it is clearly null. Question is why the conditional if(myjson != null) passed...
In short, you're missing the question mark.
You expect that in block:
spr.getString("KEY", null).let { it }
Won't be null? That's incorrect.
Correct syntax is
spr.getString("KEY", null)?.let { it }
Easy to miss.
Same goes for working with nested JSONs. You should never use bang-bang (!!) in Kotlin. Use the safe syntax instead:
recipeArray?[counterX].recipeKey

How to check if a string returns null value in android?

For login page in android, I am using php webservice to connect to server database. I stored the response from php service in a string. The response should be either success or failed. But sometimes it is neither returning success or failed. So at that time it is showing null pointer exception. I tried as below but it is showing null pointer exception at line
if (!response.equals(null) && response.equals("SUCCESS"))
when the response is empty. How can I solve this issue. Please help me in this regard.
if (!response.equals(null) && response.equals("SUCCESS")) {
Intent howis = new Intent(Login.this, Homepage.class);
startActivity(in);
}
else if (response.equals("FAILED")) {
new AlertDialog.Builder(Login1.this)
.setMessage(
"Sorry!! Incorrect Username or Password")
.setCancelable(false).setPositiveButton("OK", null)
.show();
password.setText("");
username.requestFocus();
} else if (response.equals(null)) {
new AlertDialog.Builder(Login1.this)
.setMessage("Invalid email or password")
.setCancelable(false).setPositiveButton("OK", null)
.show();
password.setText("");
username.requestFocus();
} else {
new AlertDialog.Builder(Login1.this)
.setMessage("Please Try Again..")
.setCancelable(false).setPositiveButton("OK", null)
.show();
password.setText("");
username.requestFocus();
}
If you are checking for an empty (with nothing in it) string, then the condition should be:
if (response == null) {
} else if (response != null) {
}
If you are checking for the String value of null (the String has the value null in it), then the condition should be:
if (response.equals("null")) {
} else {
}
You can't use String's methods like equals() when it is null. You should check for null first (response == null).
I'd propose to do
if (response == null) {
//null
} else if (response.equals("SUCCESS")) {
//success
} else if (response.equals("FAILED")) {
//failed
} else {
//neither of those
}
or
if (!response == null && response.equals("SUCCESS")) {
//success
} else if (!response == null && response.equals("FAILED")) {
//failed
} else if (response == null) {
//null
} else {
//neither of those
}
First way is shorter and less verbose, second has the ordering as your code, what can be better for understanding the code.
You can also use
if(TextUtils.isEmpty(response))
{
// response is either null or empty
}
From the docs:
public static boolean isEmpty (CharSequence str)
Returns true if the string is null or 0-length.
You can simply use..
if (!response.equals("") && response.equals("SUCCESS"))
{
...
}
Another possible workaround (works for me) is to avoid the null pointer exception by setting up a default value inside the layout xml:
android:text="sometext"
That is if your stuck :-)

Why NullPointerException in Service after Application exit?

I am creating a webview based Android Application using Phonegap. To help the application, I have created a service that basically gets user's location from time to time and processes it and saves it.
This is what happens:
I run the application - I have startService() call in onCreate() of the MainActivity. There is no other activity in the application (until now).
The service runs, application runs. I can see all this in LogCat.
Now, when I press back key on application's first screen, application exits and as a result after few seconds I see stack trace in LogCat and message that application has stopped. The error is NullPointerException
I get the exception in method below at indicated line:
public void GetAvailableLocation(){
vstore = new VariableStorage(); //Even when I assigned new object to vstore
if(vstore.load("mobileNumber").equals("0")) // Exception occures here
return;
// Get all available providers
List<String> providers = locationManager.getAllProviders();
for(String provider: providers) {
Location newLocation = locationManager.getLastKnownLocation(provider);
if(isBetter(newLocation, locationListener.location)
&& newLocation != null) {
locationListener.location = newLocation;
}
}
}
The above method is first method called in onCreate() of service.
Please help me out on this.
Edit: here is the load method in vstore-
public String load(String key){
Log.d(TAG, "Load key: "+key);
try{
if(!loaded){
this.loadFromFile();
}
String result = null;
if(key.equals("loggedIn"))
result = Boolean.toString(loggedIn);
else if(key.equals("mobileNumber"))
result = Long.toString(mobileNumber);
else if(key.equals("password"))
result = password;
else if(key.equals("gettingService"))
result = Boolean.toString(gettingService);
else if(key.equals("providingService"))
result = Boolean.toString(providingService);
else if(key.equals("gettingServiceID"))
result = Integer.toString(gettingServiceID);
else if(key.equals("providingServiceTo"))
result = Long.toString(providingServiceTo);
else if(key.equals("usersName"))
result = usersName;
else if(key.equals("currLatitude"))
result = Double.toString(currLatitude);
else if(key.equals("currLongitude"))
result = Double.toString(currLongitude);
else if(key.equals("prevLatitude"))
result = Double.toString(prevLatitude);
else if(key.equals("prevLongitude"))
result = Double.toString(prevLongitude);
else if(key.equals("lastLocationUpdateTime"))
result = Integer.toString(lastLocationUpdateTime);
else if(key.equals("publicKey"))
result = publicKey;
else if(key.equals("notification"))
result = Integer.toString(notification);
else if(key.equals("verifyMobileNumber"))
result = Long.toString(verifyMobileNumber);
return result;
}
catch(Exception e){
Log.d(TAG, "VSLoad Error: " + e.getMessage());
return null;
}
}
that is a better way to write that condition:
if("0".equals(vstore.load("mobileNumber")))
"0" is always given. so if load returns null you will call return;
That is called null saved :)
Be sure that vstore.load("mobileNumber") returns something
or write something like:
if(vstore.load("mobileNumber") == null || vstore.load("mobileNumber").equals("0"))
return;

Android: json's value is null

In my Android project when user log in, it will access our server and return to the client a json data, when user enter a wrong username or password, server will return the json data just like this:
{"d":{"__type":"FMService.LoginUser:#StarHope.FMS.Web.Pages.Service","Error":"worng","Permissions":null,"UserInfo":null}}
But when user enter the right username and password the return data "Error" is null.So the value of key "Error" is null. I try this to deal with it.
try
{
//when Error is not null
String error = (String) map.get("Error");
}
catch (Exception e)
{
//when Error is null
}
Is this OK? Anything wrong with this? Thang you.
parse your json string as use isNull to check if jsonobject content NULL or not before adding value to Map:
JSONObject jobject=new JSONObject("YOUR_JSON_STRING");
if(!jobject.isNull("d")){
JSONObject jobjd=jobject.getJSONObject("d");
String strtype,strError;
if(jobjd.isNull("__type")){
strtype=jobjd.getString("__type");
}
else{
//do some code here
strtype="is null";
}
if(jobjd.isNull("Error")){
strError=jobjd.getString("Error");
}
else{
//do some code here
strError="is null";
}
//.....same code here for Permissions and UserInfo
}
else{
//do some code here
}
You can use getString(). This method will raise a JSONException if the mapping is missing.
public String getString (String name)
Added in API level 1 Returns the value mapped by name if it exists,
coercing it if necessary.
Throws JSONException if no such mapping exists.
You can also test if the mapping exists or is null using isNull()
Note that the Error field is inside the d object, not the root.

Categories

Resources