Value in JSON Object not being accessed - android

I have JSON Object contacts which Looks like so {"email":"Mark#HookahStationBCS.com","phone":"+19796918899"}In my code I grab the phone key and am able to get it's value, but then when I print out the email value it says it's null, and in my code below it doesn't actually pass the termination case. Does anyone know why?
if(nextActivityObject.getJSONObject("contacts") != null){
Log.d("NEXT ACTIVITY OBJECT NOT EMPTY", "NOT EMPTY");
contacts = nextActivityObject.getJSONObject("contacts");
if(contacts.getString("phone") != null){
phone = contacts.getString("phone");
Log.d("PHONE PASSED", phone.toString());
intent.putExtra("phone",phone);
} else if(contacts.getString("email") != null){
email = contacts.getString("email");
Log.d("THIS IS THE EMAIL PASS", email.toString());
intent.putExtra("email", email);
}
}

I think your code should be something like this:
if (nextActivityObject.getJSONObject("contacts") != null){
Log.d("NEXT ACTIVITY OBJECT NOT EMPTY", "NOT EMPTY");
contacts = nextActivityObject.getJSONObject("contacts");
if(contacts.getString("phone") != null && contacts.getString("email") != null){
phone = contacts.getString("phone");
email = contacts.getString("email");
intent.putExtra("phone",phone);
intent.putExtra("email",email);
}
else if (contacts.getString("phone") != null){
phone= contacts.getString("phone");
intent.putExtra("phone", phone);
}
else if (contacts.getString("email") != null){
email = contacts.getString("email");
intent.putExtra("email", email);
}
}

You have an elseif condition.. You have to have 2 if conditions. I am pretty much saying what the previous poster said, just wording it differently.

Related

Unable to store data into firebase database

Help, I cant save my data in firebase realtime database, it keeps my app force close. Please help im new at android.
private void SReport(){
String name = etfulln.getText().toString().trim();
String reason = etreason.getText().toString().trim();
String address = etaddr.getText().toString().trim();
String contact = etcontn.getText().toString().trim();
if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(reason) && !TextUtils.isEmpty(address) && !TextUtils.isEmpty(contact)){
String id = DBReport.push().getKey();
Report report = new Report(id,name,reason,address,contact);
DBReport.child(id).setValue(report);
Toast.makeText(this, "Report added", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(this, "Fill details", Toast.LENGTH_LONG).show();
}
}

Android getting JSONObject Exception

I'm getting a JSONObject Exception in cases where the twitter value in my JSON Object media is null in my below code, even though I check to make sure I'm not assigning the value to anything if it is. Is the way I am checking correct? or how can I avoid my code throwing the exception and allow me to check if the twitter value is there or not?
if(nextActivityObject.getJSONObject("media") != null){
media = nextActivityObject.getJSONObject("media");
Log.d("NEXT MEDIA OBJECT NOT EMPTY", media.toString());
if(media.getString("twitter") != null && media.getString("facebook") != null){
Log.d("BOTH NOT NULL", "both not null");
twitter = media.getString("twitter");
facebook = media.getString("facebook");
intent.putExtra("twitter", twitter);
intent.putExtra("facebook", facebook);
}
else if(media.getString("twitter") != null){
twitter = media.getString("twitter");
Log.d("JUST TWITTER NOT NULL", twitter.toString());
intent.putExtra("twitter", twitter);
}
else if(media.getString("facebook") != null){
facebook = media.getString("facebook");
Log.d("JUST FACEBOOK NOT NULL", facebook.toString());
intent.putExtra("facebook", facebook);
}
}
You can use media.optString("twitter");. And you need another media.has("twitter") to distinguish between "no key called twitter" and "twitter key has empty string value".
To sum up, for "twitter" key, you could write
else if(media.has("twitter")){
twitter = media.optString("twitter");
// here twitter is non-NULL String
Log.d("JUST TWITTER NOT NULL", twitter.toString());
intent.putExtra("twitter", twitter);
}
Use .has method to find out whether the key is in json or not. Instead of getString it is wise to use optString.

Null returned for getPackageManager().getLaunchIntentForPackage("com.android.email")

My aim is to launch Email client on Android device using:
Intent regularIntent = getPackageManager().getLaunchIntentForPackage("com.android.email");
if (regularIntent == null) {
Toast.makeText(getApplicationContext(),"This Email client not configured!",
Toast.LENGTH_LONG).show();
} else {
regularIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(regularIntent,0);
}
I always get regularIntent as Null. What is a workaround for this issue?

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;

Categories

Resources