I am using parse android SDK in my app. Here is my login activity:
public class LoginActivity extends Activity {
EditText username, password;
Button login;
SharedPreferences prefs;
ProgressDialog dialog;
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(this, LogSignActivity.class));
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
dialog = new ProgressDialog(LoginActivity.this);
dialog.setCancelable(false);
dialog.setMessage("Loading...");
initializeViews();
if (prefs.getBoolean(PreferenceStrings.logged, false)) {
username.setText(prefs.getString(PreferenceStrings.uname, ""));
password.setText(prefs.getString(PreferenceStrings.pwd, ""));
dialog.show();
ParseUser.logInInBackground(username.getText().toString(), password
.getText().toString(), new LogInCallback() {
#Override
public void done(ParseUser user, ParseException e) {
dialog.dismiss();
if (e != null) {
prefs.edit()
.putBoolean(PreferenceStrings.logged, false)
.commit();
e.printStackTrace();
}
if (user == null) {
prefs.edit()
.putBoolean(PreferenceStrings.logged, false)
.commit();
Toast.makeText(getBaseContext(), "User not found!",
Toast.LENGTH_SHORT).show();
} else if (!user.isAuthenticated()) {
prefs.edit()
.putBoolean(PreferenceStrings.logged, false)
.commit();
Toast.makeText(getBaseContext(),
"User is not authenticated!",
Toast.LENGTH_SHORT).show();
} else {
prefs.edit().putBoolean(PreferenceStrings.logged, true)
.commit();
prefs.edit()
.putString(PreferenceStrings.uname,
username.getText().toString()).commit();
prefs.edit()
.putString(PreferenceStrings.pwd,
password.getText().toString()).commit();
startActivity(new Intent(LoginActivity.this,
HomeActivity.class));
finish();
}
}
});
}
TextView back = (TextView) findViewById(R.id.nav_back);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startActivity(new Intent(LoginActivity.this,
LogSignActivity.class));
finish();
}
});
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (username.getText().toString().equals("")) {
Toast.makeText(getBaseContext(), "Please enter username!",
Toast.LENGTH_SHORT).show();
} else if (password.getText().toString().equals("")) {
Toast.makeText(getBaseContext(), "Please enter password!",
Toast.LENGTH_SHORT).show();
} else {
dialog.show();
ParseUser.logInInBackground(username.getText().toString(),
password.getText().toString(), new LogInCallback() {
#Override
public void done(ParseUser user,
ParseException e) {
dialog.dismiss();
if (e != null) {
prefs.edit()
.putBoolean(
PreferenceStrings.logged,
false).commit();
e.printStackTrace();
}
if (user == null) {
prefs.edit()
.putBoolean(
PreferenceStrings.logged,
false).commit();
Toast.makeText(getBaseContext(),
"User not found!",
Toast.LENGTH_SHORT).show();
} else if (!user.isAuthenticated()) {
prefs.edit()
.putBoolean(
PreferenceStrings.logged,
false).commit();
Toast.makeText(getBaseContext(),
"User is not authenticated!",
Toast.LENGTH_SHORT).show();
} else {
prefs.edit()
.putBoolean(
PreferenceStrings.logged,
true).commit();
prefs.edit()
.putString(
PreferenceStrings.uname,
username.getText()
.toString())
.commit();
prefs.edit()
.putString(
PreferenceStrings.pwd,
password.getText()
.toString())
.commit();
startActivity(new Intent(
LoginActivity.this,
HomeActivity.class));
startActivity(new Intent(
LoginActivity.this,
HomeActivity.class));
finish();
}
}
});
}
}
});
}
private void initializeViews() {
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.btn_log);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
}
}
I was able to login successfully, but after some logins, I was unable to login and the following error is returned from Parse:
Any ideas?
This is a known bug, and has been verified by the Parse team for the iOS API (my hunch is that it runs deeper and is the same bug you are seeing here on the Android side).
You can find out more here:
https://developers.facebook.com/bugs/614018488703097/
Until it's resolved, it might be wise to turn off the Local Data Store and see if that helps.
Related
I want to restrict the ability to login to ONLY users that have clicked the VERIFICATION LINK in their emails. If not, they should have no access to the app.
I have found the code that I think I should use, but it doesn't do what it's supposed to do and I'll show you what I wrote thus far (in a separate LoginActivity that starts MainActivity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
edtEmailLogin = findViewById(R.id.edtEmailLogin);
edtPasswordLogin = findViewById(R.id.edtPasswordLogin);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progBarLogin);
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser fUser = fAuth.getCurrentUser();
if (fUser!=null) {
Toast.makeText(this, "Welkom terug, je wordt direct ingelogd", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
finish();
}
}
public void btn_Login (View view) {
String email = edtEmailLogin.getText().toString().trim();
String password = edtPasswordLogin.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
edtEmailLogin.setError("Vul hier je emailadres in");
return;
}
if(TextUtils.isEmpty(password)) {
edtPasswordLogin.setError("Vul hier je wachtwoord in");
return;
}
if (!email.endsWith("prorail.nl")) {
Toast.makeText(this, "Dit is geen geldig PRORAIL emailadres", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
fAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
checkIfEmailVerified();
} else {
Toast.makeText(LoginActivity.this, "Er is iets misgegaan" + task.getException().getMessage(), Toast.LENGTH_LONG).show();
progressBar.setVisibility(View.GONE);
}
});
}
private void checkIfEmailVerified() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user.isEmailVerified()) {
Toast.makeText(this, "Je bent geverifieerd en ingelogd", Toast.LENGTH_SHORT).show();
startActivity(new Intent(this, MainActivity.class));
finish();
} else {
Toast.makeText(this, "Controleer eerst je inbox en spamfolder om je emailadres te verifiƫren", Toast.LENGTH_LONG).show();
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(this, LoginActivity.class));
}
}
public void btn_NieuwAccount (View view) {
startActivity(new Intent(this, RegisterActivity.class));
Toast.makeText(this, "Registreer je account", Toast.LENGTH_SHORT).show();
}
public void btn_WachtwoordVergeten (View view) {
EditText resetMail = new EditText(view.getContext());
AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(view.getContext());
passwordResetDialog.setIcon(android.R.drawable.ic_dialog_alert);
passwordResetDialog.setTitle("Reset Wachtwoord?");
passwordResetDialog.setMessage("Vul je ProRail emailadres is voor een reset link");
passwordResetDialog.setView(resetMail);
passwordResetDialog.setPositiveButton("Verder", (dialog, which) -> {
String resetmail = resetMail.getText().toString();
fAuth.sendPasswordResetEmail(resetmail).addOnSuccessListener(aVoid -> Toast.makeText(LoginActivity.this, "Email met reset link verstuurd.", Toast.LENGTH_SHORT).show()).addOnFailureListener(e -> Toast.makeText(LoginActivity.this, "Er is iets misgegaan. Controleer uw gegevens." + e.getMessage(), Toast.LENGTH_LONG).show());
});
passwordResetDialog.setNegativeButton("Terug", (dialog, which) -> {
});
passwordResetDialog.create().show();
}
So I'm using checkIfEmailVerified, and signOut if not verified, but when I run this on a phone it doesn't check it at all, you can just log in. Have I made an error in the code? Did I put in in the wrong place?
P.S.: It might help, so here's the RegisterActivity too:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
edtEmailReg = findViewById(R.id.edtEmailRegister);
edtPasswordReg = findViewById(R.id.edtPasswordRegister);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progBarRegister);
}
public void btn_Registreer (View view) {
String email = edtEmailReg.getText().toString().trim();
String password = edtPasswordReg.getText().toString().trim();
if (TextUtils.isEmpty(email)){
edtEmailReg.setError("Vul een geldig emailadres in");
return;
}
if (TextUtils.isEmpty(password)){
edtPasswordReg.setError("Vul een wachtwoord in");
return;
}
if (!email.endsWith("prorail.nl")) {
Toast.makeText(this, "Dit is geen geldig PRORAIL emailadres", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
FirebaseUser user = fAuth.getCurrentUser();
assert user != null;
user.sendEmailVerification().addOnSuccessListener(aVoid -> Toast.makeText(RegisterActivity.this, "Verificatie email is verstuurd, controleer ook je spamfolder", Toast.LENGTH_LONG).show()).addOnFailureListener(e -> Toast.makeText(RegisterActivity.this, "Er is iets misgegaan " + e.getMessage(), Toast.LENGTH_SHORT).show());
Toast.makeText(RegisterActivity.this, "Gebruiker gecreƫerd", Toast.LENGTH_SHORT).show();
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
} else {
Toast.makeText(RegisterActivity.this, "Er heeft zich een fout voorgedaan " + Objects.requireNonNull(task.getException()).getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
public void btn_BestaandAccount (View view) {
startActivity(new Intent(this, LoginActivity.class));
Toast.makeText(this, "Login Pagina", Toast.LENGTH_SHORT).show();
}
After #FrankvanPuffelen convinced me to go into debugging mode I noticed I was directed to LoginActivity after registering my email adress and in LoginActivity I added the onStart method --> Immediate login!
So it never got to the isEmailVerified boolean at all, it just skipped all the code after onStart. After deleting the onStart method the program worked as it should: First click on the link in the email and only THEN be able to log in.
Ofcourse, now my colleagues have to log in every time they close the app, but that's only needed one time per workday, so they will have to live with that :)
For me as a starting programmer this was very helpful, so thank you Frank for opening my eyes to debugging mode.
I've registered users with the createUserWithEmailAndPassword method and they are registered on my firebase project (I can see their info). But when I try to login with the created email and password the task.isSuccessful method is always returning false and the else statement is running every time.
Code for login and registration:
private Button buttonRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignin;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog=new ProgressDialog(this);
firebaseAuth= FirebaseAuth.getInstance();
buttonRegister = (Button) findViewById(R.id.buttonRegister);
editTextEmail=(EditText) findViewById(R.id.editTextEmail);
editTextPassword=(EditText) findViewById(R.id.editTextPassword);
textViewSignin=(TextView) findViewById(R.id.textViewSignin);
buttonRegister.setOnClickListener(this);
textViewSignin.setOnClickListener(this);
if(firebaseAuth.getCurrentUser()!=null){
//start the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}
}
private void registerUser(){
String email=editTextEmail.getText().toString().trim();
String password=editTextEmail.getText().toString().trim();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter E-mail first", Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this, "Please enter password first", Toast.LENGTH_SHORT).show();
return;
}
progressDialog.setMessage("Registerring User......");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if(task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}
else{
Toast.makeText(MainActivity.this, "Unable to Register! Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
if(v == textViewSignin){
finish();
startActivity(new Intent(this, LoginActivity.class));
}
}
#Hemant Yadav
Have you checked what exception firebase give when it returns false? Please check what exception is occurred at that time by using below code:
task.getException() //which returns the exception that caused the Task to fail.
Check and update what exception you are getting so, we can help you or you can get the idea to resolve it?
It was a silly mistake from my side.
I assigned email value to password field while registering the user.
String email=editTextEmail.getText().toString().trim();
String password=editTextEmail.getText().toString().trim();
So password was not actually assigned the password which I actually passed.
Sorry for this very silly mistake.
Try this code
firebaseAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
finish();
startActivity(new Intent(this, MainActivity.class));
}
else {
try {
throw task.getException();
}
catch (FirebaseAuthInvalidCredentialsException e) {
Toast.makeText(getApplicationContext(), "Invalid Password", Toast.LENGTH_LONG).show();
}
catch (FirebaseAuthEmailException e){
Toast.makeText(getApplicationContext(), "Invalid Email", Toast.LENGTH_LONG).show();
}
catch (FirebaseAuthException e){
Toast.makeText(getApplicationContext(), "Invalid Credentials", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
});
for more detail visit this https://firebase.google.com/docs/auth/android/password-auth
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!");
}});
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.
I have Developed an application that have facebook login functionality for the Login in Application so i implement Two Button in Main Page of app so when click on login with facebook its open facebook login page so my question is when user already login with fb then the button of login should be invisible so i ckeck
facebook.isSessionValid() is true or false but its getting false everytime
my code
String APP_ID = "**************";
fb = new Facebook(APP_ID);
login = (Button) findViewById(R.id.btnFbLogin);
if(fb.isSessionValid())
{
login.setVisibility(View.GONE);
}
Toast.makeText(this, "" + fb.isSessionValid(), Toast.LENGTH_LONG).show();
withoutLogin = (Button) findViewById(R.id.btnWithoutLogin);
login.setOnClickListener(this);
withoutLogin.setOnClickListener(this);
}
#Override
public void onClick(View click) {
if (click == login) {
loginTofacebook();
} else {
Intent intent = new Intent(this, MockTest.class);
startActivity(intent);
Toast.makeText(this, withoutLogin.getText().toString(), Toast.LENGTH_SHORT).show();
}
}
public void loginTofacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
}
{
fb.authorize(this, new String[]{"email", "user_address ", "user_mobile_phone", "publish_stream", "manage_friendlists", "user_checkins", "friends_checkins", "read_friendlists", "manage_friendlists", "friends_birthday"}, new Facebook.DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e) {
Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.commit();
Intent intent = new Intent(MainActivity.this, Preparation.class);
startActivity(intent);
}
#Override
public void onCancel() {
Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
}
});
}
}
}
Session session = Session.getActiveSession();
if (session == null) {
// try to restore from cache
session = Session.openActiveSessionFromCache(this);
// Toast.makeText(this, "logout", Toast.LENGTH_LONG).show();
}
session.isOpenSession(); // return true if login
Hope this will help