Android - Parse.com NullPointerException when saving object - java

In my app I am using Parse.com and Facebook login, and the Facebook login is working and I am now trying to save the email of the user who signed. I am doing this like this:
Request.newMeRequest(ParseFacebookUtils.getSession(), new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
String email = user.getProperty("email").toString();
Log.i(TAG, email);
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("email", email);
currentUser.saveInBackground();
}
}
}).executeAsync()
But then when I run I get java.lang.NullPointerException at this line currentUser.put("email", email); But I log email before this and it is not null and I have a email attribute in my User class on parse, so Im not sure why this?
Here the code that comes before to set up the FB Login you should need it and it is working but just in case.
public void onLoginClick(View v) {
progressDialog = ProgressDialog.show(LoginActivity.this, "", "Logging in...", true);
final List<String> permissions = Arrays.asList("public_profile", "email");
// NOTE: for extended permissions, like "user_about_me", your app must be reviewed by the Facebook team
// (https://developers.facebook.com/docs/facebook-login/permissions/)
ParseFacebookUtils.logIn(permissions, this, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
progressDialog.dismiss();
if (user == null) {
Log.d(TAG, "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d(TAG, "User signed up and logged in through Facebook!");
showSelectSchoolActivity();
} else {
Log.d(TAG, "User logged in through Facebook!");
showMainActivity();
}
}
});
Thanks for the help :)

for checking the response you should always use (err==null) as the condition for success. Only after you have recieved the response from the server and err==null then you can check for current user. You should also have a check for when err!=null. Then get the error message from the err.getCode() and check what the error code is.

Related

Can I get Contact Number while login in app using Facebook along with other fields like fbUserName, fbEmail,fbPicture etc.?

I want to fetch the Contact Number using facebook login in my app, is there any way to fetch the contact number ??
I have to show the facebook user details in my app and if the user hasn't added his contact Number then I simply set the ContactNo column as empty where I want to show the basic user details.
I have fetched the user details like this:
//useLoginInformation() method is called from the CallbackManager listener to display details once the user has successfully logged in
private void useLoginInformation(AccessToken accessToken) {
/**
Creating the GraphRequest to fetch user details
1st Param - AccessToken
2nd Param - Callback (which will be invoked once the request is successful)
**/
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
//OnCompleted is invoked once the GraphRequest is successful
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
String name = object.getString("name");
String email = object.getString("email");
String id=object.getString("id");
String image_url="https://graph.facebook.com/" + id + "/picture?type=normal";
//Send facebook user details from login activity to FacebookUserDetails activity
Intent intent=new Intent(LoginActivity.this,FacebookUserDetails.class);
intent.putExtra("facebookUsername",name);
intent.putExtra("facebookUserEmail",email);
intent.putExtra("facebookPic",image_url);
startActivity(intent);
progressBar.setVisibility(View.VISIBLE);
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// We set parameters to the GraphRequest using a Bundle.
Bundle parameters = new Bundle();
parameters.putString("fields", "name,email,id,picture");
request.setParameters(parameters);
// Initiate the GraphRequest
request.executeAsync();
}

How do I get the user's name, email, and profile picture when the user logs in with their Facebook account?

I have been able to create a successful login with the user's Facebook account on my android app. Now, I want to be able to get the user's name, email, and profile picture.
Similar to what I did when the user logs in with their Google account:
GoogleSignInAccount account = result.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Username.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
The above code shows what I did when the user logged in with their Google account. I want to pretty much do the same thing when the user logs in with their Facebook account. What do I do?
Use this after you get the user facebook accessToken :
public static void getFacebookUserInfo(AccessToken accessToken,
GraphRequest.GraphJSONObjectCallback callback) {
if (accessToken == null) {
throw new NullPointerException("AccessToken should not be null !");
}
Bundle params = new Bundle();
params.putString("fields", "name, email");
GraphRequest request = GraphRequest.newMeRequest(accessToken, loginCallback);
request.setParameters(params);
request.executeAsync();
}
and the callback :
private class FacebookUserInfoCallback implements GraphRequest.GraphJSONObjectCallback {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
if (response.getError() == null) {
String name = object.optString("name");
String email = object.optString("email");
}
}
}
and get the profile picture(should be call after facebook user logged in) :
Profile profile = Profile.getCurrentProfile();
if(profile != null) {
Uri profilePictureUri = profile.getProfilePictureUri(width, height);
}

Facebook Login - get user data in onCancel

I added Facebook login button to my code. it works well.
Assuming that the user logs in via facebook and unchecks the 'user_friends' permission: 'onSuccess' function will be called so the user data can be taken from the loginResult.
Next time when he opens the app, he will get the facebook permission screen in order to allow the 'user_friends' permission. Let's say that he unchecks it again: 'onCancel' function will be called although the user will be now logged in automatically as expected (because he has never logged out).
How can I get his data now in onCancel? (because I know that he is logged in but unchecked some permission)
The User logged in last time and not this time so onSuccess won't be called this time
mCallbackManager = CallbackManager.Factory.create();
mLoginButtonFacebook.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
}
#Override
public void onCancel() {
AccessToken token = AccessToken.getCurrentAccessToken();
if (token != null) {
// here I would like to retrieve the user data
// the user is logged in with canceled permissions
}
}
#Override
public void onError(FacebookException exception) {
}
});
Succeeded! sorry for your time and thanks.
AccessToken accessToken = AccessToken.getCurrentAccessToken();
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// object will contain the user data
}
});

"FirebaseError: Invalid authentication credentials provided" error when setting up google sign in on Android

I've been trying to set up a google login for my app.
I followed the tutorial here:
https://developers.google.com/identity/sign-in/android/start-integrating
I did everything. I can sign in sign in and sign out.
Then I added an Async task to get a token, which it seems to successfully retrieve. It is implemented as follows:
private class GetIdTokenTask extends AsyncTask<Void, Void, String> {
private static final String SERVER_CLIEdNT_ID = "749433126040-ca4gfj7ucuh0m2suo3230u03o3d7doni.apps.googleusercontent.com";
#Override
protected String doInBackground(Void... params) {
String accountName = Plus.AccountApi.getAccountName(mGoogleApiClient);
Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
String scopes = "audience:server:client_id:" + SERVER_CLIEdNT_ID; // Not the app's client ID.
try {
return GoogleAuthUtil.getToken(getApplicationContext(), account, scopes);
} catch (IOException e) {
Log.e(TAG, "Error retrieving ID token.", e);
return null;
} catch (GoogleAuthException e) {
Log.e(TAG, "Error retrieving ID token. Google exception", e);
return null;
}
}
#Override
protected void onPostExecute(String result) {
Log.i(TAG, "ID token: " + result);
if (result != null) {
idToken = result;
Toast.makeText(context, "token is " + result, Toast.LENGTH_LONG).show();
} else {
// There was some error getting the ID Token
// ...
Toast.makeText(context, "token is null", Toast.LENGTH_LONG).show();
}
}
}
So after running the method and getting the token, I then run the generic firebase code to connect to Firebase (having already set up a google app, put the client ID in firebase, enabled it etc.) I got the code from https://www.firebase.com/docs/android/guide/login/google.html
And implemented it as follows:
public void loginFireBase() {
Firebase ref = new Firebase("https://boiling-fire-944.firebaseio.com");
ref.authWithOAuthToken("google", idToken, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// the Google user is now authenticated with your Firebase app
Toast.makeText(context, "user succesfully authenticated with firebase", Toast.LENGTH_LONG).show();
Toast.makeText(context, idToken, Toast.LENGTH_LONG).show();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
///////THIS IS THE PART WHERE THE ERROR IS GENEREATED FROM//////////
Log.v("firebase problem", firebaseError.toString());
Toast.makeText(context, "I'm an authenticated error" + "id Token was " + idToken, Toast.LENGTH_LONG).show();
}
});
}
}
So ultimately, I login, I get a token, and then pass it to the firebase authWithOAuthToken method, and then I get the error:
FirebaseError: Invalid authentication credentials provided.
Can anyone see any problems in my code? I have a feeling the token is not valid but can't find a way to check its validity.
Tell me if you need me to post more, I was trying to keep it brief.
Thanks to anybody who can help !
Whenever I need to authenticate with Firebase on Android, I go back to the Firebase Android login demo. Here's how that app gets the OAuth token for Google authentication:
String scope = String.format("oauth2:%s", Scopes.PLUS_LOGIN);
token = GoogleAuthUtil.getToken(
GoogleOAuthActivity.this,
Plus.AccountApi.getAccountName(mGoogleApiClient),
scope);
It looks like you're getting the cross-client id for the user, which is not a valid OAuth token.
Update (20160308): nowadays I instead look at the FirebaseUI library, which includes this functionality and is more up to date.
In my case i was having this error message in Firebase/Crash
the solution was run this line:
rm $HOME/Library/Preferences/com.google.SymbolUpload*
this was happening because previously already had generated the ServiceAccount.json file and restart the credentials needed

Android Facebook SDK and authenticating on my server

I am trying to setup login on my app using facebook. Currently I have the SDK working fine, it authenticates and I can accession user information and then I start an Intent to my activity. (not sure if this is what I should be doing)
Now I am wondering what the workflow is for this is to authenticate with my RestAPI.
I can post the facebook_id to my server and add to my users database but I then read that I should be using the AccessToken, but how do I know if this is the correct AccessToken for that user?
What should be the flow here? Where should I be posting to the server and what should I be posting for every request in every Activity?
Here is my code I currently have.
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(final Session session, SessionState sessionState, Exception e) {
if (sessionState.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser graphUser, Response response) {
if (graphUser != null) {
Log.w(TAG, graphUser.getFirstName() + ' ' + graphUser.getId());
Log.w(TAG, session.getAccessToken() + ' ' + session.getExpirationDate());
Intent intent = new Intent(LoginActivityFragment.this, MainActivity.class);
startActivity(intent);
}
}
}).executeAsync();
} else if (sessionState.isClosed()) {
}
}
};
You should use the user ID as the unique identifier. The access token can change under many situations (updated permissions, user log in/out, etc), and should not be used to identify someone. The user ID will remain stable within your app.
You can send the access token along with the ID to your server, perhaps to make some FB requests from the server side, but that's a separate issue.

Categories

Resources