Android getting JSONObject Exception - android

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.

Related

Value in JSON Object not being accessed

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.

How to retrieve authData from a ParseUser?

I'm trying to retrieve the authData field from a ParseUser. With Parse 1.9.1, I used to do it like so:
ParseUser user = ParseUser.getCurrentUser();
HashMap authDataMap = (HashMap)user.get("authData");
HashMap facebookMap = (HashMap)authDataMap.get("facebook");
String facebookId = (String)facebookMap.get("id");
And this worked fine.
Something changed though. I don't know if it's because I updated to Parse 1.9.2 or if something changed on the Parse server side, but authData is no longer accessible. The line user.get("authData") returns null. Even if I re-fetch the user.
Ultimately I want to retrieve the Facebook id from the ParseUser, preferably without reaching out to Facebook. Is this no longer possible?
If you are using ParseFacebookUtils to perform login Facebook user then after successfully login from in parse try to get GraphUser using following to fetch Facebook user data-
Request.newMeRequest(ParseFacebookUtils.getSession(),
new Request.GraphUserCallback() {
#Override
public void onCompleted(
final GraphUser fbUser,
Response response) {
try {
if (fbUser != null
&& parseUser != null
&& fbUser.getName()
.length() > 0) {
// Facebook user data
String fbId = fbUser.getId();
} else {
// Facebook user not logged in
}
} catch (Exception e) {
e.printStackTrace();
stopLoading();
}
}
}).executeAsync();
Have you taken a look at Facebook Users section in the Parse.com documentation. I think authData is for internal communication, not meant to be called (any more).

Accessing a custom column in Parse.com user table returning me null

I am trying to retrieve a new column called "address" I created in Parse User in my android app. But it returns me nullPointerException error and returns me nothing although I filled the address in the table.
This link only shows the way to store your custom field in the user table but I need to retrieve what I stored there.
This is my code:
ParseUser pUser = ParseUser.getCurrentUser();
userAddress.setText(pUser.getString("address").toString());
I tried get("address") as well but still it returns me nothing. Is there something I'm missing here?
Alright, I found the answer on my own. It turns out that Parse caches the ParseUser.getCurrentUser() object locally and the reason I wasn't able to get the data from server was because I changed the data on server and the client cache wasn't updated.
I was able to fix this by fetching the ParseUser object from the server:
ParseUser.getCurrentUser().fetchInBackground();
and then after the object is retrieved from the server I was able to get the address field on my client.
You need to call it using a Query, then display it in a textView/editText. Try the following:
final ParseQuery<ParseObject> address = ParseQuery.getQuery("//Class Name");
address.getFirstInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject reqAdd, ParseException e) {
if (address != null) {
Log.d("quizOne", "Got it");
//Retrieve Age
String //CreateNewString = reqAdd.getString("//Column name");
TextView //textView Name = (TextView) findViewById(R.id.//textView ID);
//textViewName.setText(//StringName);
Toast.makeText(getApplicationContext(),
"Successfully Recieved Address",
Toast.LENGTH_LONG).show();
} else {
Log.d("//EnterName", "//Enter Error Message");
Toast.makeText(getApplicationContext(),
"Can't receive address", Toast.LENGTH_LONG)
.show();
}
}
});
Short answer: that user probably just doesn't have an address set.
Long answer: your code snippet will throw exceptions often, and you should expect and handle those, or use tests to avoid throwing them.
Read this page: http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException
Key example/excerpt:
Object obj = null;
obj.toString(); // This statement will throw a NullPointerExcept
So pUser.getString("address") appears correct. But calling .toString() on the result requires you to be try/catching the exception. Maybe do
ParseUser pUser = ParseUser.getCurrentUser();
if (pUser.getString("address") != null) {
userAddress.setText(pUser.getString("address"));
}
BTW, I believe the error is "nullPointerException" fyi! :)

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?

android facebook application

I'm trying to create on android a facebook application and I'm using android facebook-sdk .
The example that I'm trying to understand is this one:
https://github.com/facebook/facebook-android-sdk/tree/master/examples/stream
There is something that I don't understand in here if u could help me out a little bit it would be great.
At some point in the main Activity is doing something like:
Dispatcher dispatcher = new Dispatcher(this);
dispatcher.addHandler("login", LoginHandler.class);
dispatcher.addHandler("stream", StreamHandler.class);
dispatcher.addHandler("logout", LogoutHandler.class);
Session session = Session.restore(this);
if (session != null) {
dispatcher.runHandler("stream");
} else {
dispatcher.runHandler("login");
}
}
What I don't understand is the way this Session.restore(this) works.
The restore method looks like this:
public static Session restore(Context context) {
if (singleton != null) {
if (singleton.getFb().isSessionValid()) {
return singleton;
} else {
return null;
}
}
SharedPreferences prefs =
context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
String appId = prefs.getString(APP_ID, null);
if (appId == null) {
return null;
}
Facebook fb = new Facebook(appId);
fb.setAccessToken(prefs.getString(TOKEN, null));
fb.setAccessExpires(prefs.getLong(EXPIRES, 0));
String uid = prefs.getString(UID, null);
String name = prefs.getString(NAME, null);
if (!fb.isSessionValid() || uid == null || name == null) {
return null;
}
Session session = new Session(fb, uid, name);
singleton = session;
return session;
}
If someone could explain me what is the whole purpose of SharedPreferences, what is stored there and why are these 2 lines needed :
fb.setAccessToken(prefs.getString(TOKEN, null));
fb.setAccessExpires(prefs.getLong(EXPIRES, 0));
When you access any facebook user information or any other action which requires permission to be accessed as shown below. . If the user press Allow button then A Token is inserted in their Database with the user Id , your App Id and the validation time (which may be unlimited) as well as the Actions you may perform (e.g Access Info, Send Email, Access Posts, Post to Wall etc.), that specific Token is returned to you and you save that Token to access the info and other action which are permitted against that token.
Whenever you make a request for any action they match that token, check validation and then see if that action is allowed by the user, if allowed you are granted to complete the action.

Categories

Resources