Android: Parse + Facebook integration - android

I am working on Parse and Facebook integration with reference to the tutorial https://github.com/ParsePlatform/IntegratingFacebookTutorial/tree/master/IntegratingFacebookTutorial-Android, and come across headache problems that would like someone who can offer advice.
LoginActivity.java
OnCreate
....
// Check if there is a currently logged in user and it's linked to a Facebook account.
ParseUser currentUser = ParseUser.getCurrentUser();
if ((currentUser != null) && ParseFacebookUtils.isLinked(currentUser))
{
// Go to the user info activity
showUserDetailsActivity();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
public void onLoginClick(View v)
{
progressDialog = ProgressDialog.show(LoginActivity.this, "", "Logging in...", true);
List<String> permissions = Arrays.asList(
"public_profile",
"user_friends",
"email",
"user_birthday"
);
ParseFacebookUtils.logInWithReadPermissionsInBackground(this, permissions, new LogInCallback()
{
#Override
public void done(ParseUser user, ParseException err)
{
progressDialog.dismiss();
if (user == null)
{
Log.d(Msg, "Uh oh. The user cancelled the Facebook login.");
Utilities.custom_toast(LoginActivity.this, "Uh oh. The user cancelled the Facebook login.", "gone!", "short");
}
else if (user.isNew())
{
Log.d(Msg, "User signed up and logged in through Facebook!");
Utilities.custom_toast(LoginActivity.this, "User signed up and logged in through Facebook!", "gone!", "short");
showUserDetailsActivity();
}
else
{
Log.d(Msg, "User logged in through Facebook!");
Utilities.custom_toast(LoginActivity.this, "User logged in through Facebook!", "gone!", "short");
showUserDetailsActivity();
}
}
});
}
private void showUserDetailsActivity()
{
Intent intent = new Intent(this, UserDetails.class);
startActivity(intent);
}
UserDetails.java
#Override
protected void onResume()
{
super.onResume();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null)
{
// Check if the user is currently logged and show any cached content
updateViewsWithProfileInfo();
}
else
{
// If the user is not logged in, go to the activity showing the login view.
startLoginActivity();
}
}
private void makeMeRequest()
{
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse)
{
if (jsonObject != null)
{
JSONObject userProfile = new JSONObject();
try
{
userProfile.put("facebookId", jsonObject.getLong("id"));
userProfile.put("name", jsonObject.getString("name"));
if (jsonObject.getString("gender") != null)
userProfile.put("gender", jsonObject.getString("gender"));
if (jsonObject.getString("email") != null)
userProfile.put("email", jsonObject.getString("email"));
// Save the user profile info in a user property
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("User", userProfile);
currentUser.saveInBackground();
// Show the user info
updateViewsWithProfileInfo();
}
catch (JSONException e)
{
Log.d(TAG,"Error parsing returned user data. " + e);
}
}
else if (graphResponse.getError() != null)
{
switch (graphResponse.getError().getCategory())
{
case LOGIN_RECOVERABLE:
Utilities.custom_toast(UserDetails.this, "Authentication error: " + graphResponse.getError(), "gone!", "short");
break;
case TRANSIENT:
Utilities.custom_toast(UserDetails.this, "Transient error. Try again" + graphResponse.getError(), "gone!", "short");
Log.d(TAG,"Transient error. Try again. " + graphResponse.getError());
break;
case OTHER:
Utilities.custom_toast(UserDetails.this, "Some other error: " + graphResponse.getError(), "gone!", "short");
Log.d(TAG,"Some other error: " + graphResponse.getError());
break;
}
}
}
});
request.executeAsync();
}
private void updateViewsWithProfileInfo()
{
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser.has("profile"))
{
JSONObject userProfile = currentUser.getJSONObject("profile");
try
{
if (userProfile.has("name"))
{
userNameView.setText(userProfile.getString("name"));
} else
{
userNameView.setText("no name");
}
if (userProfile.has("gender")) {
userGenderView.setText(userProfile.getString("gender"));
} else {
userGenderView.setText("no gender");
}
if (userProfile.has("email")) {
userEmailView.setText(userProfile.getString("email"));
} else {
userEmailView.setText("no email");
}
} catch (JSONException e) {
Log.d(TAG, "Error parsing saved user data.");
}
}
else
{
Utilities.custom_toast(UserDetails.this, "no profile!", "gone!", "short");
}
}
public void onLogoutClick(View v)
{
logout();
}
private void logout()
{
ParseUser.logOut(); // Log the user out
startLoginActivity(); // Go to the login view
}
private void startLoginActivity()
{
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Question:
I have tried run the app as a new user:
1. when press the login button, it process and pop up "User signed up and logged in through Facebook!" However, after logged in, it turns to the UserDetails page, but reports via a toast "no profile!" , ie the currentUser has no info inside. What is going wrong here?
Why there is no permission page popup when login despite it got "email" permission?
Thanks a lot!

Related

google game play services only works for first time then doesnt signin again

i have setup google play services. when i sign in for the first time in device it works and signs in. but when i restart the app it does not sign in and returns null.
can any one tell me proper steps to configure google play game services please ?
private boolean isSignedIn() {
return GoogleSignIn.getLastSignedInAccount(this) != null;
}
private void signInSilently() {
Log.d(TAG, "signInSilently()");
mGoogleSignInClient.silentSignIn().addOnCompleteListener(this,
new OnCompleteListener<GoogleSignInAccount>() {
#Override
public void onComplete(#NonNull Task<GoogleSignInAccount> task) {
if (task.isSuccessful()) {
Log.d(TAG, "signInSilently(): success"+task.getResult());
Toast.makeText(SetupActivity.this, ""+task.getResult().getEmail(), Toast.LENGTH_SHORT).show();
//onConnected(task.getResult());
} else {
Log.d(TAG, "signInSilently(): failure", task.getException());
//onDisconnected();
startSignInIntent();
}
}
});
}
private void startSignInIntent() {
startActivityForResult(mGoogleSignInClient.getSignInIntent(), RC_SIGN_IN);
}
private void signOut() {
Log.d(TAG, "signOut()");
if (!isSignedIn()) {
Log.w(TAG, "signOut() called, but was not signed in!");
Toast.makeText(this, "not sign in", Toast.LENGTH_SHORT).show();
return;
}
mGoogleSignInClient.signOut().addOnCompleteListener(this,
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
boolean successful = task.isSuccessful();
Log.d(TAG, "signOut(): " + (successful ? "success" : "failed"));
if (successful)
Toast.makeText(SetupActivity.this, "success logout", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SetupActivity.this, "no", Toast.LENGTH_SHORT).show();
// onDisconnected();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task =
GoogleSignIn.getSignedInAccountFromIntent(intent);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
Toast.makeText(this, ""+account.getEmail(), Toast.LENGTH_SHORT).show();
// onConnected(account);
} catch (ApiException apiException) {
String message = apiException.getMessage();
if (message == null || message.isEmpty()) {
message = getString(R.string.signin_other_error);
}
//onDisconnected();
new AlertDialog.Builder(this)
.setMessage(message)
.setNeutralButton(android.R.string.ok, null)
.show();
}
}
}
oncreate
mGoogleSignInClient = GoogleSignIn.getClient(this,
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN).build());
//signInSilently();
startSignInIntent();

How to check the current firebase user and open diffrent activities as per login

**I just want to open the activity as per state of firebase auth **
if(user already Logged in)
If the user is Customer then go to = Mainactivity .
If the user is Admin then go to = AdminNavigationActivity
the problem is what its always open go to the main activity when i opened the app in second time its doesn't check the user state . or which user is logged in.
Help me Sorry for my Bad english.
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
// String name = user.getDisplayName();
String email = user.getEmail();
if (email=="admin#gmail.com") {
Intent admin_intent = new Intent(LoginActivity.this, AdminNavigationActivity.class);
startActivity(admin_intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
}
}
}
};
linkSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intent);
}
});
reset_pass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// resetPassword();
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtEmail.getText().toString().trim().isEmpty()) {
txtEmail.setError("This field is required!");
} else if (!isValidEmail(txtEmail.getText().toString().trim())) {
txtEmail.setError("This is not a valid email!");
} else if (txtPassword.getText().toString().trim().isEmpty()) {
txtPassword.setError("This field is required!");
} else {
progressDialog.setTitle("Login");
progressDialog.setMessage("Please wait");
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
email = txtEmail.getText().toString();
password = txtPassword.getText().toString();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (task.isSuccessful()) {
progressDialog.dismiss();
if (txtEmail.getText().toString().equals("admin#gmail.com"))//&& txtPassword.getText().toString().equals("8605357562"))
{
startActivity(new Intent(LoginActivity.this, AdminNavigationActivity.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
}
else {
Toast.makeText(LoginActivity.this, "Login Failed", Toast.LENGTH_SHORT).show();
progressDialog.hide();
}
}
});
}
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onResume() {
super.onResume();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
remove this code:
if (user != null) {
// Name, email address, and profile photo Url
// String name = user.getDisplayName();
String email = user.getEmail();
if (email=="admin#gmail.com") {
Intent admin_intent = new Intent(LoginActivity.this, AdminNavigationActivity.class);
startActivity(admin_intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
}
}
so if email is not admin then it will always go to the mainActivity.
Also if you close the app remove it from background also. To do that click the button next to the home button and remove it then login again.
Or log out the user. Do a sign out button and give it this code on button click(and go to right activity):
FirebaseAuth.getInstance().signOut();
change this:
if (txtEmail.getText().toString().equals("admin#gmail.com"))
to this:
if (email.equals("admin#gmail.com"))

Intent activity after facebook login opened twice

I have a main activity that displays login option, if the user clicked login with FB button, I will call fblogin();, and if the login success then I will do intent to open home activity.
right now, the home activity seems to open twice. (i can see it appear twice, stacked)
private void Fblogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("LoginActivity", response.toString());
Log.d("LoginActivity", object.toString());
String jsonresult = String.valueOf(object);
System.out.println("JSON Result" + jsonresult);
String str_firstname=null,str_id=null;
try {
str_firstname=object.getString("name");
str_id = object.getString("id");
String str_email = object.getString("email");
Intent home = new Intent(MainActivity.this , HomeActivity.class);
home.putExtra("name", str_firstname);
home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE);
startActivity(home);
} catch (JSONException e) {
e.printStackTrace();
Log.d("xxxx","aa");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
in my main activity, i call this in my on create FacebookSdk.sdkInitialize(getApplicationContext());
, iI also check for initial login status `
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);}
but I think that initial check has nothing to do with it becauseI tried to delete it too but it still happening.`
and in my Home Activity, I have not write any facebook related codes yet.
EDIT : I PUT WHOLE CODE (MainActivity)
import ...
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public static Boolean IsLoggedFB = false; //general state of fb logged
public static Boolean IsLoggedManual =false; //status boolean if logged in by email (manual)
public static Boolean IsLoggedGM = false; //general state of google gmail logged
String ID_HNBS; //IDhnbs created when first Registered
String Email;
TextView Fpassword;
Button Daftar;
EditText email, password;
Button LoginEmail;
LoginButton fb_button;
SignInButton gplus_button;
MainActivity myContext;
static String personName;
private boolean mIntentInProgress;
FragmentManager fragmentManager;
private CallbackManager callbackmanager;
//for G+
private GoogleSignInOptions gso;
private static final int PROFILE_PIC_SIZE = 30;
private GoogleApiClient mGoogleApiClient;
private ConnectionResult mConnectionResult;
private boolean mSignInClicked;
static final int RC_SIGN_IN = 0;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
LinearLayout tv;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
public static final String MyPREFERENCES = "xpp";
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
IsLoggedManual = sharedpreferences.getBoolean("IsLoggedManual", false); // get value of last login status
IsLoggedGM = sharedpreferences.getBoolean("IsloggedGM", false); // get value of last login GM
Daftar = (Button) findViewById(R.id.buttonDaftarEmail);
LoginEmail = (Button) findViewById(R.id.buttonLoginEmail);
fb_button = (LoginButton)findViewById(R.id.fblogin_button);
//Initializing google signin option
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
gplus_button = (SignInButton) findViewById(R.id.sign_in_button);
gplus_button.setSize(SignInButton.SIZE_STANDARD);
gplus_button.setScopes(gso.getScopeArray());
//Initializing google api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
//.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
Daftar.setOnClickListener(this);
LoginEmail.setOnClickListener(this);
fb_button.setOnClickListener(this);
gplus_button.setOnClickListener(this);
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone())
{
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
}
Log.d("TAG", "ACCESS TOKEN STATUS" + AccessToken.getCurrentAccessToken() + " --- profile=" + Profile.getCurrentProfile());
//CHECK IF ALREADY LOGGED BY FB
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
} else if ( IsLoggedManual ) { //IF already LOGGED IN MANUAL (SHAREDPREF)
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.buttonDaftarEmail) {
Intent intent = new Intent(MainActivity.this, UserRegistration.class);
startActivity(intent);
} else if (v.getId() == R.id.buttonLoginEmail) {
Intent intent_signin = new Intent(MainActivity.this, LoginManual.class);
startActivity(intent_signin);
} else if (v.getId() == R.id.fblogin_button) {
Fblogin();
} else if (v.getId() == R.id.sign_in_button) //google sign in button
{
Intent intent_Gsignin = new Intent(MainActivity.this, GSignIn.class);
startActivity(intent_Gsignin);
}
}
private void onSignInClicked() {
// User clicked the sign-in button, so begin the sign-in process and automatically
// attempt to resolve any errors that occur.
mShouldResolve = true;
mGoogleApiClient.connect();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
private void Fblogin()
{
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile, email, user_birthday,user_friends"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Application code
Log.d("LoginActivity", response.toString());
Log.d("LoginActivity", object.toString());
String jsonresult = String.valueOf(object);
System.out.println("JSON Result" + jsonresult);
String str_firstname=null,str_id=null;
try {
str_firstname=object.getString("name");
str_id = object.getString("id");
String str_email = object.getString("email");
Intent home = new Intent(MainActivity.this , HomeActivity.class);
home.putExtra("name", str_firstname);
home.putExtra("URL", "https://graph.facebook.com/" + str_id + "/picture?width="+PROFILE_PIC_SIZE+"&height="+PROFILE_PIC_SIZE);
startActivity(home);
} catch (JSONException e) {
e.printStackTrace();
Log.d("xxxx","aa");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.v("LoginActivity", "cancel");
}
#Override
public void onError(FacebookException exception) {
Log.v("LoginActivity", exception.getCause().toString());
}
});
}
//After the signing we are calling this function
private void handleSignInResult(GoogleSignInResult result) {
//If the login succeed
if (result.isSuccess()) {
//Getting google account
GoogleSignInAccount acct = result.getSignInAccount();
//tv= (LinearLayout) tv.findViewById(R.id.layoutfragmentlogin);
//tv.setVisibility(View.GONE); //hide include , so include now show nothing
Intent Home=new Intent(this,HomeActivity.class);
Home.putExtra("name",acct.getDisplayName());
Home.putExtra("email", acct.getEmail());
Home.putExtra("URL",acct.getPhotoUrl());
startActivity(Home);
} else {
//If login fails
Toast.makeText(this, "Login Failed on silentsign in", Toast.LENGTH_LONG).show();
}
}
//#Override
public void onConnected(Bundle bundle) {
mSignInClicked = false;
Toast.makeText(myContext, "User is connected!", Toast.LENGTH_LONG).show();
}
//#Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(callbackmanager!=null) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
Log.d("ani", "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
}
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
if (resultCode != this.RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
}
}
//#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
//prefs.edit().putBoolean("Islogin",false).commit();
//DO Nothing..
/*
//==========Below is Trying to connect if googleUser not connected already =======
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d("ani", "onConnectionFailed:" + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(getActivity(), RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e("ani", "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
}
}*/
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setTitle("HnBS Alert")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
EDIT 2 : MY HOMEACTIVITY CODE
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
/**
* react to the user tapping/selecting an options menu item
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_menu_logout:
LoginManager.getInstance().logOut(); //LogOut from Facebook
//logout from login manual
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean("IsLoggedManual",false).commit();
//if (mGoogleApiClient.isConnected()) {
// if (mGoogleApiClient.isConnected())
// Auth.GoogleSignInApi.signOut(mGoogleApiClient);
//}
Toast.makeText(this, "LoggedOut!", Toast.LENGTH_SHORT).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finishAffinity();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
After eight hours trial with some debugging, i couldn't find any trace of what is causing my HomeActivity fires twice. for people who stuck in any similar case, if you want and if its not breaking out your code, you can try to make your activity appear only one instance by adding this on your activity declaration in the manifest:
android:launchMode = "singleTask"
this has been the solution for me right now cause i don't want to waste any time longer as i need to move on to the next progress. thank you for any assistance.
You are calling the activity twice. That is
when consider if you are logged in facebook and google then the both the code get executed.
in onCreate you are calling
if (opr.isDone())
{
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result); //check method for going to home activity
}
and
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
} else if ( IsLoggedManual ) { //IF already LOGGED IN MANUAL (SHAREDPREF)
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
Use these conditions as one eg
opr.isDone() || AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null
Here you missed it, check out this code -
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
}
Above cached sign-in will start HomeActivity as well as if your AccessToken is not null(you're logged in with facebook) - again will start Home Activity
//CHECK IF ALREADY LOGGED BY FB
if ( AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile()!=null ) {
//load profile and skip (loginfragment) to Home page
Intent home = new Intent(MainActivity.this , HomeActivity.class);
startActivity(home);
}
Solution:
You should put these conditions using else if ladder statements...

Facebook user to Parse.com

How do I get the data from The Facebook user to Parse.com? The code that I will provide below makes a user but it doesn't update it with data when I login, why is it not working?
public class LoginActivity extends Activity {
private EditText usernameView;
private EditText passwordView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onLoginButtonClicked();
}
});
// Set up the login form.
usernameView = (EditText) findViewById(R.id.etUsername);
passwordView = (EditText) findViewById(R.id.etPassword);
// Set up the submit button click handler
findViewById(R.id.ibLogin).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onNormalLoginButton();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
private void onNormalLoginButton(){
// Validate the log in data
boolean validationError = false;
StringBuilder validationErrorMessage =
new StringBuilder(getResources().getString(R.string.error_intro)); //please
if (isEmpty(usernameView)) {
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_username));//enter username
}
if (isEmpty(passwordView)) {
if (validationError) {
validationErrorMessage.append(getResources().getString(R.string.error_join));// and
}
validationError = true;
validationErrorMessage.append(getResources().getString(R.string.error_blank_password));//enter password
}
validationErrorMessage.append(getResources().getString(R.string.error_end));// .
// If there is a validation error, display the error
if (validationError) {
Toast.makeText(LoginActivity.this, validationErrorMessage.toString(), Toast.LENGTH_LONG) //LENGHT_LONG means how long the message will stand
.show();
return;
}
// Set up a progress dialog
final ProgressDialog dlg = new ProgressDialog(LoginActivity.this);
dlg.setTitle("Please wait.");
dlg.setMessage("Logging in. Please wait.");
dlg.show();
// Call the Parse login method
ParseUser.logInInBackground(usernameView.getText().toString(), passwordView.getText()
.toString(), new LogInCallback() {
public void done(ParseUser user, ParseException e) {
dlg.dismiss();
if (e != null) {
// Show the error message
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
} else {
// Start an intent for the dispatch activity
ParseUser userguy=ParseUser.getCurrentUser();
boolean validated=userguy.getBoolean("emailVerified");
if(validated)
{
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("user", userguy.getObjectId());
installation.put("fullname",userguy.getString("fullname"));
installation.saveInBackground();
openMainActivity();
}else{
Toast.makeText(LoginActivity.this, "You need to confirm your Email!",Toast.LENGTH_LONG).show();
}
}
}
});
}
private void onLoginButtonClicked() {
List<String> permissions = Arrays.asList("email", "user_about_me");
ParseFacebookUtils.logInWithReadPermissionsInBackground(this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Profile profile = Profile.getCurrentProfile();
user.put("gender", "");
user.put("location", "");
user.put("age", "");
user.put("meet", "");
user.put("status", "");
user.put("link", "");
user.put("fullname", profile.getName());
user.setEmail("");
user.signUpInBackground();
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("user", user.getObjectId());
installation.put("fullname", user.getString("fullname"));
installation.saveInBackground();
openMainActivity();
} else {
Log.d("MyApp", "User logged in through Facebook!");
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("user", user.getObjectId());
installation.put("fullname", user.getString("fullname"));
installation.saveInBackground();
openMainActivity();
}
}
});
}
private void openMainActivity(){
Intent intent = new Intent(LoginActivity.this, DispatchActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private boolean isEmpty(EditText etText) {
if (etText.getText().toString().trim().length() > 0) {
return false;
} else {
return true;
}
}
public void signUp(View view) {
Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
Ignore the onNormalLoginButton() it works, onloginButtonClicked() is the problem.
Edit:
I've tried this but it also didn't work.
user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if(e!=null){
Toast.makeText(LoginActivity.this,"User data didn't save!",Toast.LENGTH_SHORT).show();
}else{
openMainActivity();}
}
});
Look at below code. Why do you call user.signUpInBackground(); again?
I think it should be user.saveInBackground();
Also, please check the data type of your fields to make sure you put correct data type (Example: int/float/double for Number)
else if (user.isNew()) {
Profile profile = Profile.getCurrentProfile();
user.put("gender", "");
user.put("location", "");
user.put("age", "");
user.put("meet", "");
user.put("status", "");
user.put("link", "");
user.put("fullname", profile.getName());
user.setEmail("");
user.signUpInBackground();
ParseInstallation installation = ParseInstallation.getCurrentInstallation();
installation.put("user", user.getObjectId());
installation.put("fullname", user.getString("fullname"));
installation.saveInBackground();
openMainActivity();
}
From parse document, user.isNew() -> User signed up and logged in through Facebook!
ParseFacebookUtils.logInWithReadPermissionsInBackground(this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
If it doesn't work, try below code to know if your user is saved successfully or not
user.saveInBackground(new SaveCallback() {
#Override public void done(ParseException e) {
if (e != null) {
Log.e("Exception", e.getMessage());
return;
}
Log.e("OK", "Saved!");
}});

Facebook after login not coming back but asking login again

I am trying to implement Facebook login functionality in my app and getting token after giving publish permission.
For this I follow following steps.
Create app on Facebook(Fill all details like app name, Hash key(Release), Class name, Package Name, Single Sign On)
App is available for all user now.
Then i am using app id in my manifest.xml
Everything is working fine with me if Native Facebook app is install on my mobile. But if native app is not install then it will open facebook webview after filling login info it ask me to authorize after clicking on ok button it again asking me to login. And this process will continue.
****After login and allowing app permission it's not coming back to my screen but it asking login me again****.
Here is my screen shot.
Here is second screen shot
After clicking on ok then it's asking me again to login. It's loop login - authorize- login..
Here is my full code:
I am using my own button so i am not adding xml code.
public class FBActivity extends Activity {
Session.StatusCallback statusCallback = new SessionStatusCallback();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.registartionwithmultiple);
printHashKey();
bundle = savedInstanceState;
permissions = new ArrayList<String>();
readpermissions = new ArrayList<String>();
permissions.add("publish_actions");
readpermissions.add("email");
executeFacebookLogin();
}
private void executeFacebookLogin() {
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if(session == null) {
if(bundle != null) {
Log.i("TEST","RESTORING FROM BUNDLE");
session = Session.restoreSession(this, null, statusCallback, bundle);
}
if(session == null) {
Log.i("TEST","CREATE NEW SESSION");
session = new Session(this);
}
Session.setActiveSession(session);
session.addCallback(statusCallback);
if(session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(readpermissions));
}
}
if(session.isClosed()) {
session.closeAndClearTokenInformation();
Session.setActiveSession(null);
}
if(!session.isOpened()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(readpermissions));
Log.i("FB Login ","Open for Publish");
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state, Exception exception) {
//Check if Session is Opened or not
processSessionStatus(session, state, exception);
}
}
#SuppressWarnings("deprecation")
public void processSessionStatus(Session session, SessionState state, Exception exception) {
Log.i("TEST","Session in process session "+session);
if(session != null && session.isOpened()) {
if(session.getPermissions().contains("publish_actions")) {
//Show Progress Dialog
dialog = new ProgressDialog(this);
dialog.setMessage("Loggin in..");
dialog.show();
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (dialog!=null && dialog.isShowing()) {
dialog.dismiss();
}
if(user != null) {
Map<String, Object> responseMap = new HashMap<String, Object>();
GraphObject graphObject = response.getGraphObject();
responseMap = graphObject.asMap();
Log.i("FbLogin", "Response Map KeySet - " + responseMap.keySet());
// TODO : Get Email responseMap.get("email");
fb_id = user.getId();
fb_email = null;
user.getBirthday();
fb_userName = user.getUsername();
fb_fullname = user.getFirstName() +" "+user.getLastName();
String name = (String) responseMap.get("name");
if (responseMap.get("email")!=null) {
fb_email = responseMap.get("email").toString();
Log.i("TEST", "FB_ID="+fb_id +"email="+fb_email+"name="+name+"user_name="+user.getUsername()+"birthday="+user.getBirthday());
Session session = Session.getActiveSession();
tokenKey = session.getAccessToken();
SharedPreferenceStoring myPrefsClass = new SharedPreferenceStoring();
myPrefsClass.storingFBToken(FBActivity.this, tokenKey);
finish();
}
else {
//Clear all session info & ask user to login again
Session session = Session.getActiveSession();
if(session != null) {
session.closeAndClearTokenInformation();
}
}
}
}
});
} else {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(FBActivity.this, permissions));
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("TEST","Activity result");
super.onActivityResult(requestCode, resultCode, data);
Log.d("FbLogin", "Result Code is - " + resultCode +"");
Session.getActiveSession().onActivityResult(FBActivity.this, requestCode, resultCode, data);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Save current session
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
}
I also getting hash key.. Here is code for hash key
private void printHashKey() {
try {
PackageInfo info = getPackageManager().getPackageInfo(
"com.myapp",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:",
Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
I also add Internet Permission in AndroidManifest.xml and meta-data for Facebook .
Hope all this information is sufficient if need any thing more will surely update my question.
Please give me any reference or hint.
u need a library easyfacebookandroidsdk.jar and build it up in ur project
use this code :
public class MainActivity extends Activity implements LoginListener{
EditText et1;
private FBLoginManager fbLoginManager;
Button b;
//replace it with your own Facebook App ID
public final String FacebookTesting="218874471621782";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText)findViewById(R.id.editText1);
b=(Button)findViewById(R.id.button1);
connectToFacebook();
}
public void connectToFacebook(){
//read about Facebook Permissions here:
//http://developers.facebook.com/docs/reference/api/permissions/
String permissions[] = {
// "user_about_me",
// "user_activities",
// "user_birthday",
// "user_checkins",
// "user_education_history",
// "user_events",
// "user_groups",
// "user_hometown",
// "user_interests",
// "user_likes",
// "user_location",
// "user_notes",
// "user_online_presence",
// "user_photo_video_tags",
// "user_photos",
// "user_relationships",
// "user_relationship_details",
// "user_religion_politics",
// "user_status",
// "user_videos",
// "user_website",
// "user_work_history",
// "email",
//
// "read_friendlists",
// "read_insights",
// "read_mailbox",
// "read_requests",
// "read_stream",
// "xmpp_login",
// "ads_management",
// "create_event",
// "manage_friendlists",
// "manage_notifications",
// "offline_access",
// "publish_checkins",
"publish_stream",
// "rsvp_event",
// "sms",
//"publish_actions",
// "manage_pages"
};
fbLoginManager = new FBLoginManager(this,
R.layout.activity_main,
FacebookTesting,
permissions);
if(fbLoginManager.existsSavedFacebook()){
fbLoginManager.loadFacebook();
}
else{
fbLoginManager.login();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data){
fbLoginManager.loginSuccess(data);
}
public void loginSuccess(Facebook facebook) {
// GraphApi graphApi = new GraphApi(facebook);
new getDataBackgroundThread().execute(facebook);
// User user = new User();
// try{
// user = graphApi.getMyAccountInfo();
//
// //update your status if logged in
// graphApi.setStatus("Hello, world!");
// } catch(EasyFacebookError e){
// Log.d("TAG: ", e.toString());
// }
// fbLoginManager.displayToast("Hey, " + user.getFirst_name() + "! Login success!");
}
#Override
public void logoutSuccess() {
// TODO Auto-generated method stub
}
#Override
public void loginFail() {
// TODO Auto-generated method stub
}
class getDataBackgroundThread extends AsyncTask<Facebook, Void, String> {
private Exception exception;
protected String doInBackground(Facebook... urls) {
try{
GraphApi graphApi = new GraphApi(urls[0]);
User user = new User();
try{
// user = graphApi.getMyAccountInfo();
//update your status if logged in
//graphApi.setStatus("My android App "+"VivekAppTest");
graphApi.setStatus("Hello "+"VivekAppTest");
} catch(EasyFacebookError e){
Log.d("TAG: ", e.toString());
}
return "posted";
}
catch (Exception e) {
// TODO: handle exception
return null;
}
}
protected void onPostExecute(String ipr) {
// TODO: check this.exception
// TODO: do something with the feed
//
// Intent i=new Intent(getApplicationContext(),MainActivity.class);
// startActivity(i);
// finish();
// Toast toast=Toast.makeText(getApplicationContext(),"Post Successful !", 1);
// toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL,0, 130);
// toast.show();
//
}
}
}
Get your Facebook App id & replace it in the code. I always use this code whenever i have to post the text on FB.
In manifest give Internet permission
<uses-permission android:name="android.permission.INTERNET"/>
Thats all
Cheers
So what I wanted to tell you is, you'll have to find the key hashes values and put it in facebook console, Use below code for getting Key Hash Values:
try {
PackageInfo info = getPackageManager().getPackageInfo("com.key", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
TextView tvmyName = (TextView)findViewById(R.id.KeyText);
tvmyName.setText(Base64.encodeBytes(md.digest()));
Log.d("KEY_HASH", Base64.encodeBytes(md.digest()));
}
} catch (NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
KeyHash Value 1: tvmyName.setText(Base64.encodeBytes(md.digest()));
KeyHash Value 2: Log.d("KEY_HASH", Base64.encodeBytes(md.digest()));
See the below image for passing keyhash values in your facebook console :
First of all, avoid copying Facebook SDK into your current workspace, keep it somewhere and just add the working set of Facebook SDK into your workspace.
I have tried just a simple app and getting some permissions from the user. Here is the code which I have tried it was working just perfectly fine with me without Facebook app installed on the device.
public class MainActivity extends Activity implements StatusCallback {
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
// Do whatever u want. User has logged in
} else if (!currentSession.isOpened()) {
// Ask for username and password
OpenRequest op = new Session.OpenRequest((Activity) context);
op.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
op.setCallback(null);
List<String> permissions = new ArrayList<String>();
permissions.add("user_likes");
permissions.add("email");
permissions.add("user_birthday");
permissions.add("user_location");
permissions.add("user_interests");
permissions.add("friends_birthday");
op.setPermissions(permissions);
Session session = new Builder(MainActivity.this).build();
Session.setActiveSession(session);
session.openForRead(op);
}
}
public void call(Session session, SessionState state, Exception exception) {
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("Here");
super.onActivityResult(requestCode, resultCode, data);
if (Session.getActiveSession() != null)
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
Session currentSession = Session.getActiveSession();
if (currentSession == null || currentSession.getState().isClosed()) {
Session session = new Session.Builder(context).build();
Session.setActiveSession(session);
currentSession = session;
}
if (currentSession.isOpened()) {
Session.openActiveSession(this, true, new Session.StatusCallback() {
#SuppressWarnings("deprecation")
#Override
public void call(final Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
System.out.println(user.getName());
System.out.println(session
.getAccessToken());
System.out.println(user
.getFirstName());
}
}
});
}
}
});
}
}
}
On onActivityResult I have tried to print some basic info. Just try the code and comment if you bump with any issues with this current code.
Is there anything wrong with your SDK/Process/Code?
Just try this code & Let me know whether It's working fine or having same issue as you mentioned.
Click here.

Categories

Resources