I am stuck in a loop here.
Users can log in with their FB account. The app creates a Firebase user w/ the same info.
With the launcher activity (LoginActivity), if it detects an user is already logged in, it redirects them to their profile fragment.
However, on the profile fragment, I click the log off button and redirect
them to the Login page. This is where the cycle begins.
From code snippets and official Firebase doc, I am using .unauth();. However, my logcat still shows the user is logged in. I've also tried using the Facebook SDK method of LoginManager, but that hasn't worked either.
LogOut method (in MainFrag)
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
LoginActivity
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "AndroidBash";
public User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
private DatabaseReference mDatabase;
//Add YOUR Firebase Reference URL instead of the following URL
private Firebase mRef=new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
//FaceBook callbackManager
private CallbackManager callbackManager;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "CHECK - FB SIGN IN - USER IS LOGGED IN " + mUser.getUid());
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
String uid = mAuth.getCurrentUser().getUid();
String image=mAuth.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if(image!=null || image!=""){
intent.putExtra("profile_picture",image);
}
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
//FaceBook
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
//
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_email_id);
password = (EditText) findViewById(R.id.edit_text_password);
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//FaceBook
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString());
user.setPassword(password.getText().toString());
}
public void onSignUpClicked(View view) {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
public void onLoginClicked(View view) {
setUpUser();
signIn(email.getText().toString(), password.getText().toString());
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, 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()) {
Log.w(TAG, "signInWithEmail", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
intent.putExtra("user_id", uid);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
//
}
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
return valid;
}
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential: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()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
user = new User();
// user.setId(authData.getUid());
user.setName(name);
user.setEmail(email);
user.saveUser();
// mRef.child("uid").setValue(uid);
// mRef.child(name).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), CustomColorActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
MainFragment.java
public class MainFragment extends Fragment {
private static final String TAG = "AndroidBash";
public User user;
private Firebase myFirebaseRef =new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private TextView name;
private TextView welcomeText;
private Button changeButton;
private Button revertButton;
private Button FBButton;
private ProgressDialog mProgressDialog;
// To hold Facebook profile picture
private ImageView profilePicture;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container,
false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
//Add YOUR Firebase Reference URL instead of the following URL
myFirebaseRef = new Firebase("https://fitmaker-ee2c0.firebaseio.com/");
mAuth = FirebaseAuth.getInstance();
name = (TextView) view.findViewById(R.id.text_view_name);
welcomeText = (TextView) view.findViewById(R.id.text_view_welcome);
changeButton = (Button) view.findViewById(R.id.button_change);
revertButton = (Button) view.findViewById(R.id.button_revert);
FBButton = (Button) view.findViewById(R.id.button_fb);
profilePicture = (ImageView) view.findViewById(R.id.profile_picture);
//Get the uid for the currently logged in User from intent data passed to this activity
String uid = getActivity().getIntent().getExtras().getString("user_id");
//Get the imageUrl for the currently logged in User from intent data passed to this activity
String imageUrl = getActivity().getIntent().getExtras().getString("profile_picture");
Log.d(TAG, "MainFrag - OnCreateView Check");
new ImageLoadTask(imageUrl, profilePicture).execute();
//Referring to the name of the User who has logged in currently and adding a valueChangeListener
myFirebaseRef.child(uid).child("name").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the name of the User changes in your Firebase Database
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
name.setText("Hello " + data + ", ");
}
//onCancelled is called in case of any error
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//A firebase reference to the welcomeText can be created in following ways :
// You can use this :
//Firebase myAnotherFirebaseRefForWelcomeText=new Firebase("https://androidbashfirebaseupdat-bd094.firebaseio.com/welcomeText");*/
//OR as shown below
myFirebaseRef.child("welcomeText").addValueEventListener(new ValueEventListener() {
//onDataChange is called every time the data changes in your Firebase Database
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Inside onDataChange we can get the data as an Object from the dataSnapshot
//getValue returns an Object. We can specify the type by passing the type expected as a parameter
String data = dataSnapshot.getValue(String.class);
welcomeText.setText(data);
}
//onCancelled is called in case of any error
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getActivity().getApplicationContext(), "" + firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
//onClicking changeButton the value of the welcomeText in the Firebase database gets changed
changeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Android App Development # AndroidBash");
}
});
FBButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// log user out
// add choice dialog later
LogOut();
}
});
//onClicking revertButton the value of the welcomeText in the Firebase database gets changed
revertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myFirebaseRef.child("welcomeText").setValue("Welcome to Learning # AndroidBash");
}
});
return view;
}
#Override
public void onResume() {
Log.d(TAG, "onResume of MainFragment");
CheckIfLoggedOut();;
super.onResume();
}
public void CheckIfLoggedOut() {
// here, check if user still logged in.
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "MainFrag - Signed In (onResume)");
} else {
// User is signed out
Log.d(TAG, "check resume: starting log out for " + mUser.getUid());
LogOut();
}
}
public void LogOut(){
Log.d(TAG, "CHECK #2: USER SIGNED OUT");
getActivity().getIntent().removeExtra("user_id");
getActivity().getIntent().removeExtra("profile_picture");
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
Log.d(TAG, "signed out" + mUser.getUid());
// mAuth.unauth();
Intent intent = new Intent(getActivity().getApplicationContext(),
LoginActivity.class);
myFirebaseRef.unauth();
LoginManager.getInstance().logOut();
startActivity(intent);
Log.d(TAG, "CHECK 3: FINISIHED SIGNED OUT");
Log.d(TAG, "onAuthStateChanged:signed_out");
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
FirebaseAuth.getInstance().signOut();
Adding this piece of line solved my problem.
Related
I am trying to implement Firebase authentication for an android app and I keep getting an error. I am new to Android and at best a Java novice so I am sure it is something simple that I am missing. Any suggestions/advice is much appreciated!
Here is my code base:
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "LoginActivity";
//Firebase
private FirebaseAuth mAuth;
private Context mContext;
private ProgressBar mProgressBar;
private EditText mEmail, mPassword;
private TextView mPleaseWait;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mPleaseWait = (TextView) findViewById(R.id.pleaseWait);
mEmail = (EditText)findViewById(R.id.input_email);
mPassword = (EditText) findViewById(R.id.input_password);
mContext = LoginActivity.this;
Log.d(TAG, "onCreate: Login started.");
mPleaseWait.setVisibility(View.GONE);
mProgressBar.setVisibility(View.GONE);
}
private boolean isStringNull(String string){
Log.d(TAG, "isStringNull: checking if null.");
if(string.equals("")){
return true;
}else {
return false;
}
}
/**
* FireBase Code
*
*/
private void init(){
//initialize the button for logging in
Button btnLogin = (Button) findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: attempting to login. ");
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if (isStringNull(email) && isStringNull(password)){
Toast.makeText(mContext, "You must fill out all fields.", Toast.LENGTH_SHORT).show();
}else{
mProgressBar.setVisibility(View.VISIBLE);
mPleaseWait.setVisibility(View.VISIBLE);
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithEmail:success");
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithEmail:failure", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
}
});
}
/**
* Checks to see if the #param 'user' is logged in.
*/
private void updateUI(FirebaseUser currentUser) {
Log.d(TAG, "updateUI: checking if user is logged in.");
if(currentUser == null){
Intent intent = new Intent(mContext, LoginActivity.class);
startActivity(intent);
}
}
#Override
public void onStart() {
Log.d(TAG, "onStart: Starting LoginActivity onStart method.");
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
if(currentUser != null){
Log.d(TAG, "onStart:signed_in. " + currentUser);
}else{
Log.d(TAG, "onStart:signed_out. ");
}
}
}
When I run the code I get the following error message:
D/LoginActivity: onCreate: Login started.
onStart: Starting LoginActivity onStart method. D/AndroidRuntime: Shutting down VM .......java.lang.NullPointerException: Attempt to
invoke virtual method 'com.google.firebase.auth.FirebaseUser
com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null
object reference
The error message is suggesting that mAuth is null, its default value. You likely never assigned it a value.
So my concern is that I am using Shared Preference to store Name in android and can also retrieve the same when logged in again.But, when some other person logs in from the same device, still the name stored is of the previous user. How can I change this and fetch the value of the New user name from firebase? P.S I am new to Android
Following is my code for Manual Login:-
public class ManualLogin extends AppCompatActivity implements View.OnClickListener{
private Button buttonRegister;
private EditText editTextEmail;
private EditText editTextPassword;
private TextView textViewSignup;
private EditText editTextName;
DatabaseReference databaseUsers;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
private static final String TAG = "FACELOG";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_manual_login);
databaseUsers = FirebaseDatabase.getInstance().getReference("Users");
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser()!=null){
//profile activity here
finish();
startActivity(new android.content.Intent(getApplicationContext(), AccountActivity.class));
}
progressDialog = new ProgressDialog(this);
buttonRegister = (Button)findViewById(R.id.buttonRegister);
editTextEmail = (EditText)findViewById(R.id.editTextEmail);
editTextPassword = (EditText)findViewById(R.id.editTextPassword);
editTextName = (EditText)findViewById(R.id.editTextName);
textViewSignup = (TextView)findViewById(R.id.textViewSignup);
buttonRegister.setOnClickListener(this);
textViewSignup.setOnClickListener(this);
}
public void registerUser() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
final String name = editTextName.getText().toString().trim();
if(!TextUtils.isEmpty(name)) {
String id = databaseUsers.push().getKey();
Users users = new Users(id, name);
databaseUsers.child(id).setValue(users);
//Toast.makeText(this, "User Created", Toast.LENGTH_SHORT).show();
}else{
//email is empty
Toast.makeText(this, "Enter Name", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
if(TextUtils.isEmpty(email)){
//email is empty
Toast.makeText(this, "Enter Email id", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
if(TextUtils.isEmpty(password)){
//password is empty
Toast.makeText(this, "Enter Password", Toast.LENGTH_SHORT).show();
//stop function execution
return;
}
//if validations are fine
//show progressBar
progressDialog.setMessage("Registering User...");
progressDialog.show();
firebaseAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
//user is successfully registered & logged in
//profile activity here
finish();
startActivity(new android.content.Intent(getApplicationContext(), AccountActivity.class));
userProfile();
Toast.makeText(ManualLogin.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(ManualLogin.this, "Failed to Register", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
SharedPreferences sharedPref = getSharedPreferences("userName", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", editTextName.getText().toString());
editor.commit();
//Toast.makeText(ManualLogin.this, "Name Saved", Toast.LENGTH_SHORT).show();
}
});
}
//set User Display name
private void userProfile(){
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user != null){
UserProfileChangeRequest profileUpdate = new UserProfileChangeRequest.Builder()
.setDisplayName(editTextName.getText().toString().trim()).build();
user.updateProfile(profileUpdate).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.d("Testing", "User Profile Updated");
}
}
});
}
}
#Override
public void onClick(View v) {
if(v == buttonRegister){
registerUser();
}
if(v == textViewSignup){
//open login activity
finish();
startActivity(new android.content.Intent(this, LoginActivity.class));
}
}
}
Below is the code for AccountActivity:-
public class AccountActivity extends AppCompatActivity {
private Button logout;
private TextView textViewUserName;
private FirebaseAuth mAuth;
private FirebaseAuth firebaseAuth;
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
logout = (Button)findViewById(R.id.logout);
textViewUserName = (TextView)findViewById(R.id.textViewUserName);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
if(firebaseAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this, LoginActivity.class));
}
FirebaseUser sname = firebaseAuth.getCurrentUser();
textViewUserName.setText("Welcome "+ sname.getDisplayName());
SharedPreferences sharedPref = getSharedPreferences("userName", Context.MODE_PRIVATE);
String name = sharedPref.getString("name", "");
textViewUserName.setText("Welcome "+ name);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
LoginManager.getInstance().logOut();
updateUI();
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
updateUI();
}
}
private void updateUI() {
Toast.makeText(this, "You have Logged out", Toast.LENGTH_SHORT).show();
Intent accountIntent = new Intent(this, MainActivity.class);
startActivity(accountIntent);
finish();
}
}
when you login that time store data into sharedpreference like below
private void saveData(String value){
SharedPreferences sharedPreferences=getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("User",value);
editor.commit();
}
In read new user data into firebase database.
private void readData() {
// define only root node.
mFirebaseDatabase.child("User").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
User user = dataSnapshot.getValue(User.class);
mEtPwd.setText(user.pwd);
mEtName.setText(user.name);
mEtEmail.setText(user.email);
saveData(user.name);
// }
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
I am using google firebase oAuth in my app for login
My problem is that everytime i open the app it ask to login .
I want to automate using token service but i dont know how to and what to do.
private static int RC_SIGN_IN = 0 ;
private static String TAG = "LOGIN_ACTIVITY";
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
Context context = LoginActivity.this;
public FirebaseAuth.AuthStateListener mAuthListener;
private EditText mEmailField,mPasswordField;
TextView register;
private String Email ;
Model_userDetails model_userDetails = new Model_userDetails(); ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
register = (TextView) findViewById(R.id.register);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null) {
// new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d("AUTH","User logged out");
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id)).requestEmail().build();
mGoogleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this,this).addApi(Auth.GOOGLE_SIGN_IN_API,gso).build();
findViewById(R.id.sign_in_button).setOnClickListener(this);
findViewById(R.id.email_sign_in_button).setOnClickListener(this);
mEmailField = (EditText) findViewById(R.id.email);
mPasswordField = (EditText) findViewById(R.id.password);
register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this,NewUserActivity.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if (mAuthListener !=null)
mAuth.removeAuthStateListener(mAuthListener);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==RC_SIGN_IN)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess())
{
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
Email = mAuth.getCurrentUser().getEmail();
new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d(TAG,"Google login failed ");
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct){
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(),null);
mAuth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("AUTH","sign in with credentials: complete "+ task.isSuccessful());
}
});
}
private void signIn()
{
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent,RC_SIGN_IN);
}
private void emailSignIn()
{
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
if (TextUtils.isEmpty(email)|| TextUtils.isEmpty(password))
{
Toast.makeText(LoginActivity.this,"Fields are empty ",Toast.LENGTH_SHORT).show();
}
else
{
final ProgressDialog progressDialog = ProgressDialog.show(LoginActivity.this, "Please wait...", "Proccessing...", true);
(mAuth.signInWithEmailAndPassword(email,password))
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()) {
Toast.makeText(LoginActivity.this, "Login successful", Toast.LENGTH_LONG).show();
Intent i = new Intent(LoginActivity.this, AccountActivity.class);
i.putExtra("Email", mAuth.getCurrentUser().getEmail());
startActivity(i);
} else {
Log.e("ERROR", task.getException().toString());
Toast.makeText(LoginActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
}
}
});}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Log.d(TAG," Connection Failed");
}
This is my code
please help me with this
i got it myself . We have to call the new activity when checking if the user is login or not.
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user!=null) {
new HttpCall().checkGoogleEmail(context, Email);
}
else
Log.d("AUTH","User logged out");
}
};
I'm writing an app that is supposed to connect to firebase database. Everything works fine, except the fact that when I check autenthication key (using getAuth() method), it always returns null. I use facebook for autenthication in my app, and I wanted to turn on autenthication on my database with:
{
"rules": {
".read": "auth != null",
".write":"auth != null"
}
}
My project has 2 classes, one is LoginActivity, that allows user to create account in database using Facebook account:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
firebaseAutenthication = FirebaseAuth.getInstance();
//Get current user ID
FirebaseUser mUser = firebaseAutenthication.getCurrentUser();
if (mUser != null) {
// Club is signed in
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = firebaseAutenthication.getCurrentUser().getUid();
String image = firebaseAutenthication.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if (image != null || !Objects.equals(image, "")) {
intent.putExtra("profile_picture", image);
}
startActivity(intent);
finish();
Log.e(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
//Setup firebase autenthication listener
firebaseAutenthicatorListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// Club is signed in
Log.e(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// Club is signed out
Log.e(TAG, "onAuthStateChanged:signed_out");
}
}
};
//Initialize facebook SDK
FacebookSdk.sdkInitialize(getApplicationContext());
if (BuildConfig.DEBUG) {
FacebookSdk.setIsDebugEnabled(true);
FacebookSdk.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
}
//Create callback manager for facebook login
//onSucces calls login method
//TODO: onCancel and OnError should display popup with information that login failed
callbackManagerFromFacebook = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManagerFromFacebook, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.e(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.e(TAG, "facebook:onError", error);
}
});
}
#Override
protected void onStart() {
super.onStart();
firebaseAutenthication.addAuthStateListener(firebaseAutenthicatorListener);
}
#Override
public void onStop() {
super.onStop();
if (firebaseAutenthicatorListener != null) {
firebaseAutenthication.removeAuthStateListener(firebaseAutenthicatorListener);
}
}
//FaceBook
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManagerFromFacebook.onActivityResult(requestCode, resultCode, data);
}
private void signInWithFacebook(AccessToken token) {
Log.e(TAG, "signInWithFacebook:" + token);
showProgressDialog();
credential = FacebookAuthProvider.getCredential(token.getToken());
firebaseAutenthication.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.e(TAG, "signInWithCredential: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()) {
Log.e(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
String uid = task.getResult().getUser().getUid();
String name = task.getResult().getUser().getDisplayName();
String email = task.getResult().getUser().getEmail();
Uri imageUri = task.getResult().getUser().getPhotoUrl();
String image = "";
if(imageUri != null) {
image = imageUri.toString();
}
//Create a new User and Save it in Firebase database
User user = new User(uid, name, null, email, null, null, "About Me");
firebaseUsers.child(uid).setValue(user);
//Start MainActivity and pass user data to it
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("user_id", uid);
intent.putExtra("profile_picture", image);
startActivity(intent);
finish();
}
}
});
And 2nd one is MainActivity, supposed to get user information form his facebook profile and put them into the database:
void getValueFromFirebase() {
Log.e(TAG, "Started getValueFromFirebase()");
firebase.child(userID).child("name").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String data = dataSnapshot.toString();
Toast.makeText(getApplicationContext(), data, Toast.LENGTH_LONG).show();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(), firebaseError.toString(), Toast.LENGTH_LONG).show();
}
});
}
void createFirebaseConnection() {
this.firebase = new Firebase(AppConstants.FIREBASE_URL_USERS);
this.firebaseAuthentication = FirebaseAuth.getInstance();
this.firebaseUser = firebaseAuthentication.getCurrentUser();
//Create listener for firebase autenthication
//Log if user is disconnected
this.firebaseAutenthicationStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.e(TAG, "onAuthStateChanged:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged: user is not signed in!");
}
}
};
firebaseAuthentication.addAuthStateListener(this.firebaseAutenthicationStateListener);
//Check if auth is done
//If not, autenthicate with Facebook Token
if(this.firebase.getAuth() == null) {
Log.e(TAG, "firebase.getAuth() == null, starting authWithFacebook()...");
authWithFacebook();
}
}
void authWithFacebook() {
Log.e(TAG, "authWithFacebook() started!");
AccessToken accessToken = AccessToken.getCurrentAccessToken();
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
Log.e(TAG, "Facebook Token: " + accessToken.getToken());
Log.e(TAG, "Auth: " + firebase.getAuth());
}
void readDataFromLoginActivity() {
//Get the uid for the currently logged in Club from intent data passed to this activity
this.userID = getIntent().getExtras().getString("user_id");
//Get the imageUrl for the currently logged in Club from intent data passed to this activity
//Load image to ImageView
this.userImageUrl = getIntent().getExtras().getString("profile_picture");
}
#Override
public void onBackPressed() {
if (userProfile.moveState == 1) {
userProfile.slideBottom();
} else {
super.onBackPressed();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e(TAG, "onCreate() called...");
setContentView(R.layout.activity_main);
lay = (RelativeLayout) findViewById(R.id.lay);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
Log.e(TAG, "readDataFromLoginActivity() called...");
readDataFromLoginActivity();
Log.e(TAG, "createFirebaseConnection() called...");
createFirebaseConnection();
}
#Override
protected void onStart() {
super.onStart();
Log.e(TAG, "onStart() called...");
addTopTabBar();
addProfileFragment();
addLeftSideBar();
Log.e(TAG, "Binding UI Elements...");
bindUIElements();
getValueFromFirebase();
}
Yet, the toast I display always shows "permission Error". How can I fix this?
You are using both the legacy 2.x.x SDK and the new 10.x.x SDK in the same app. This is not good practice and likely the source of the problem. Remove this line from your dependencies and make the needed code changes to use only the capabilities of the new SDK.
compile 'com.firebase:firebase-client-android:2.x.x'
The package names of the new SDK start with com.google.firebase. Those of the legacy SDK start with com.firebase.client.
Helpful tips are in the Upgrade Guide.
Facebook logs in correctly. In the Firebase console, I can see the user has logged. However, I cannot access any of the user's info.
I am getting below error log in LogCat:
signInWithFacebook:{AccessToken token:ACCESS_TOKEN_REMOVED
permissions:[public_profile, contact_email, user_friends, email]}
Afterwards, I also receive a FirebaseError: Permission denied in the LogCat and as a toast inside the app.
Following this tutorial, I have made a project that integrates Facebook and Firebase. I've tried copy and pasting the source code, and replacing the necessary lines (such as Facebook ID and Firebase URL) but it isn't working for me.
here is the specific void
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential: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()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
mRef.child(uid).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
here is the full code
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "AndroidBash";
public User user;
private EditText email;
private EditText password;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private ProgressDialog mProgressDialog;
private DatabaseReference mDatabase;
//Add YOUR Firebase Reference URL instead of the following URL
private Firebase mRef=new Firebase("https://firebase.firebaseio.com");
//FaceBook callbackManager
private CallbackManager callbackManager;
//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDatabase = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
FirebaseUser mUser = mAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
String image=mAuth.getCurrentUser().getPhotoUrl().toString();
intent.putExtra("user_id", uid);
if(image!=null || image!=""){
intent.putExtra("profile_picture",image);
}
startActivity(intent);
finish();
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
}
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser mUser = firebaseAuth.getCurrentUser();
if (mUser != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + mUser.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
//FaceBook
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
signInWithFacebook(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d(TAG, "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook:onError", error);
}
});
//
}
#Override
protected void onStart() {
super.onStart();
email = (EditText) findViewById(R.id.edit_text_email_id);
password = (EditText) findViewById(R.id.edit_text_password);
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
//FaceBook
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
//
protected void setUpUser() {
user = new User();
user.setEmail(email.getText().toString());
user.setPassword(password.getText().toString());
}
public void onSignUpClicked(View view) {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
public void onLoginClicked(View view) {
setUpUser();
signIn(email.getText().toString(), password.getText().toString());
}
private void signIn(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, 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()) {
Log.w(TAG, "signInWithEmail", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
String uid = mAuth.getCurrentUser().getUid();
intent.putExtra("user_id", uid);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
//
}
private boolean validateForm() {
boolean valid = true;
String userEmail = email.getText().toString();
if (TextUtils.isEmpty(userEmail)) {
email.setError("Required.");
valid = false;
} else {
email.setError(null);
}
String userPassword = password.getText().toString();
if (TextUtils.isEmpty(userPassword)) {
password.setError("Required.");
valid = false;
} else {
password.setError(null);
}
return valid;
}
private void signInWithFacebook(AccessToken token) {
Log.d(TAG, "signInWithFacebook:" + token.getToken());
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential: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()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
String uid=task.getResult().getUser().getUid();
String name=task.getResult().getUser().getDisplayName();
String email=task.getResult().getUser().getEmail();
String image=task.getResult().getUser().getPhotoUrl().toString();
//Create a new User and Save it in Firebase database
User user = new User(uid,name,null,email,name);
mRef.child(uid).setValue(user);
Log.d(TAG, uid);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("user_id",uid);
intent.putExtra("profile_picture",image);
startActivity(intent);
finish();
}
hideProgressDialog();
}
});
}
public void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
public void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}