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!");
}});
Related
**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"))
I have searched the internet high and low and cannot find a solution to this problem that works for me. When the user signs into the app using the facebook login button, I want to get their Facebook profile picture and use it as their profile picture in my app. I'm trying to use Picasso to get the picture from the Facebook URL. Here is my code as it is. I'm getting an error
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (getIntent().getBooleanExtra("EXIT", false)) {
}
FacebookSdk.sdkInitialize(getApplicationContext());
AppEventsLogger.activateApp(this);
loginButton = (LoginButton) findViewById(R.id.fb_login_btn);
callbackManager = CallbackManager.Factory.create();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken
oldAccessToken, AccessToken currentAccessToken) {
}
};
accessToken = AccessToken.getCurrentAccessToken();
if (AccessToken.getCurrentAccessToken() == null) {
loginButton.registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Picasso.with(this) //I'm getting an error here "Picasso
cannot be applied"
.load("https://graph.facebook.com/" +
loginResult.getAccessToken().getUserId(); +
"/picture?type=large")
.into(profilePhoto);
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();
{
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
}
finish();
}
#Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Login Cancelled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Login Error",
Toast.LENGTH_SHORT).show();
}
});
} else {
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
this.finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
callbackManager.onActivityResult(requestCode,resultCode,data);
}
#Override
public void onDestroy() {
super.onDestroy();
accessTokenTracker.stopTracking();
}
}
The problem is with this part
Picasso.with(this) //I'm getting an error here "Picasso
cannot be applied"
.load("https://graph.facebook.com/" +
facebook_id + "/picture?type=large")
.into(profilePhoto);
Here instead of 'this' you need to pass activity or application context.
If you are in activity then type 'YourActivityName.this' or if you are in fragment then use 'getActivity'.
If you are thinking why 'this' is not working then FYI 'this' here means anonymous inner class.
try this
loginButton.registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginResult.getAccessToken().getUserId();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
try {
if (object.has("picture")) {
//String profilePicUrl="http://graph.facebook.com/"+object.getString("id")+"/picture?type=large";
String profilePicUrl = object.getJSONObject("picture").getJSONObject("data").getString("url");
profilePicUrl = profilePicUrl.replace("\\", "");
Picasso.with(YourActivity.this)
.load(profilePicUrl)
.into(profilePhoto);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,picture.type(large)");
request.setParameters(parameters);
request.executeAsync();
Toast.makeText(LoginActivity.this, "Login Successful",
Toast.LENGTH_SHORT).show();
{
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
}
finish();
}
#Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Login Cancelled",
Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Login Error",
Toast.LENGTH_SHORT).show();
}
});
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...
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!
I am creating a very simple app, to learn Parse functionalities.
Along the way I realized I have to use only username and NOT email, (got this from a archived question, not sure if there are any changes made now).
But in my case the following is code returning true even if the input fields are null
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity);
Parse.initialize(this, "#MASKED");
emailLogin = (EditText)findViewById(R.id.loginEmail);
passwordLogin = (EditText)findViewById(R.id.loginPassword);
login_Login = (Button)findViewById(R.id.loginBtn);
signup_Login = (Button)findViewById(R.id.loginSignup);
signup_Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
});
login_Login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = emailLogin.getText().toString().trim();
String password = passwordLogin.getText().toString().trim();
ParseUser.logInInBackground(email, password, new LogInCallback() {
#Override
public void done(ParseUser user, com.parse.ParseException e) {
if (e != null) {
// Hooray! The user is logged in.
Toast.makeText(Login_activity.this,"Sucessfully Logged in", Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), HomePage.class);
startActivity(i);
finish();
} else {
// Signup failed. Look at the ParseException to see what happened.
Toast.makeText(Login_activity.this, e.getMessage(), Toast.LENGTH_LONG).show();
AlertDialog.Builder alertDiag = new AlertDialog.Builder(Login_activity.this);
alertDiag.setMessage(e.getMessage());
alertDiag.setTitle("Error");
alertDiag.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//AlertDialog dialog =
alertDiag.create();
alertDiag.show();
}
}
});
}
});
}
if (e != null) {
// Hooray! The user is logged in.
Should be be:
if (e == null) {
// Hooray! The user is logged in.
So if there is no exceptions the user has successfully logged in.
Also your code only checks for the email and password not username.