The email address is badly formatted Firebase/ android project - java

hi i am working on a android project where i am using firebase as back-end and i am building a signup and login form . When ever i sign up the code is working well and . When i try to retrieve it using "signInWithEmailAndPassword i am getting the fallowing error. The email address is badly formatted Firebase`
login Activity
public class login extends AppCompatActivity {
Button create_Account, login_btn;
EditText l_email, l_password;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
fAuth = FirebaseAuth.getInstance();
create_Account = findViewById(R.id.l_signup_btn);
create_Account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(login.this, MainActivity.class));
}
});
l_password = findViewById(R.id.et_lpassword);
l_email = findViewById(R.id.et_lpassword);
login_btn = findViewById(R.id.l_login_btn);
login_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (l_email.getText().toString().isEmpty()) {
l_email.setError("Email is Missing");
return;
}
if (l_password.getText().toString().isEmpty()) {
l_password.setError("Password is Missing");
return;
}
fAuth.signInWithEmailAndPassword(l_email.getText().toString(), l_password.getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
startActivity(new Intent(getApplicationContext(), dashboard.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(login.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
#Override
protected void onStart() {
super.onStart();
if (FirebaseAuth.getInstance().getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), dashboard.class));
finish();
}
}
}

Can you see what mistake you have
l_password = findViewById(R.id.et_lpassword);
l_email = findViewById(R.id.et_lpassword);

Related

How do I make the terms and conditions appear only when I log in to Google for the first time?

I want to add terms and conditions when users use my app.
But I have to show terms and conditions only one time.
I'm using firebase google login. But I have a problem when I show terms and conditions and how code remembers users accept terms and conditions and shows only one time.
Here's a google login code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//새로운 코드다 마
signInButton = findViewById(R.id.signInButton);
GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
googleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this,this)
.addApi(Auth.GOOGLE_SIGN_IN_API, googleSignInOptions)
.build();
auth = FirebaseAuth.getInstance(); //파이어 베이스 인증 객체 초기화
signInButton.setOnClickListener(new View.OnClickListener() { // 구글 로그인 버튼을 클릭했을때 이곳을 수행
#Override
public void onClick(View view) {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent,REQ_SIGN_GOOGLE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) { // 구글 로그인 인증을 요청했을때 결과 값을 되돌려 받는 곳
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_SIGN_GOOGLE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if(result.isSuccess() == true) { // true 생략 가능, 인증 결과가 성공적이면
GoogleSignInAccount account = result.getSignInAccount(); //account 라는 데이터는 구글 로그인 정보를 담고 있습니다. - 닉네임,프로필사진uri,이메일 주소등
resultLogin(account); // 로그인 결과 값 출력 수행하라는 메서드
}
}
}
private void resultLogin(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
long curTime=System.currentTimeMillis();
long gapTime=curTime-backBtnTime;
if(0<=gapTime && 2000>= gapTime){
moveTaskToBack(true);
finishAndRemoveTask();
android.os.Process.killProcess(android.os.Process.myPid());
}
else {
backBtnTime = curTime;
Toast.makeText(this,"뒤로 버튼을 한 번 더 누르면 종료됩니다.",Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
Here is a code I want to show (terms and conditions)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terms);
CheckBox checkBox=findViewById(R.id.checkbox);
CheckBox checkBox2=findViewById(R.id.checkbox2);
CheckBox checkBox3=findViewById(R.id.checkbox3);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox2.setChecked(true);
checkBox3.setChecked(true);
}else {
checkBox2.setChecked(false);
checkBox3.setChecked(false);
}
}
});
checkBox2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
checkBox3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkBox.isChecked()){
checkBox.setChecked(false);
}else if(checkBox2.isChecked()&&checkBox3.isChecked()){
checkBox.setChecked(true);
}
}
});
Button btn_agr = findViewById(R.id.btn_agr1);
btn_agr.setText(R.string.app_name);
btn_agr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("서비스 이용약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_agr2 = findViewById(R.id.btn_agr2);
btn_agr2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(TermsActivity.this);
builder.setTitle("위치 정보 이용 약관 ");
builder.setMessage(R.string.app_name);
builder.setNegativeButton("닫기",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
System.out.println(TAG + "이용약관 닫기");
}
});
builder.show();
}
});
Button btn_complete = findViewById(R.id.button_complete);
btn_complete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
I tried my self - transmit variables when the user accept terms and conditions but when the user reopens the app user has to open it again
Maybe there is a way to transmit certain variables to firebase and confirm it when the user clicks the login button??
There is a way to transmit certain variables to firebase and confirm it when the user clicks the login button?
The simplest solution would be to call AuthResult#getAdditionalUserInfo() method on the Task object, because it returns an object of type AdditionalUserInfo. In this class, you can find a very useful method called isNewUser(), which can help you check if the user signs in for the first time. In code should look like this:
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
auth.signInWithCredential(credential).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) { //로그인이 성공했으면
boolean isNewUser = task.getResult().getAdditionalUserInfo().isNewUser();
if (isNewUser) {
//Display Terms & Conditions
}
Intent intent = new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
else{
Toast.makeText(LoginActivity.this,"로그인 실패",Toast.LENGTH_SHORT).show();
}
}
});

Firebase createUserWithEmailAndPassword task.isSuccessful()

I'm creating an Android application and am implementing the login / register functionality.
I'm at the stage where the register activity is successfully creating user entries in my Firebase application, however, I can't seem to track if the task was successful.
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Register.this, "Success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failure", Toast.LENGTH_LONG).show();
}
});
}
}
Both the if !task.isSuccessful() or else blocks ever get reached but the user is created in Firebase. Any ideas why I can't track the success/if it failed?
IN COMPARISON:
This is working in my login class.
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(Login.this, "Credentials error, user may not exist.", Toast.LENGTH_LONG).show();
}
}
});
Hard to say what's going with the current way of implementation.
Try adding a onSuccess directly
mAuth.createUserWithEmailAndPassword(email, pass).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
//done
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//display toast if registering failed
ToastRect.failed(RegisterActivity.this, getString(R.string.app_activities_error_text)
}
});
public class Register extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private EditText mConfirmPassword;
private Button mRegisterButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_register);
mEmailField = findViewById(R.id.registerEmailField);
mPasswordField = findViewById(R.id.registerPasswordField);
mConfirmPassword = findViewById(R.id.registerConfirmPassword);
mRegisterButton = findViewById(R.id.registerButton);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(Register.this, UploadActivity.class));
}
}
};
// https://stackoverflow.com/questions/10936042/how-to-open-layout-on-button-click-android
Button register = (Button) findViewById(R.id.navigate_to_login);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRegister();
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Register.this, "Success", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Register.this, "Failure", Toast.LENGTH_LONG).show();
}
});
}
}
}
To confirm the FirebaseAuth.AuthStateListener() was kicking in. This was a bad copy and paste job from the my Login class. This was stopping me handle the successful user creation.
The fix then looked like:
public class Register extends AppCompatActivity {
private EditText mEmailField;
private EditText mPasswordField;
private EditText mConfirmPassword;
private Button mRegisterButton;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseApp.initializeApp(this);
setContentView(R.layout.activity_register);
mEmailField = findViewById(R.id.registerEmailField);
mPasswordField = findViewById(R.id.registerPasswordField);
mConfirmPassword = findViewById(R.id.registerConfirmPassword);
mRegisterButton = findViewById(R.id.registerButton);
mAuth = FirebaseAuth.getInstance();
// https://stackoverflow.com/questions/10936042/how-to-open-layout-on-button-click-android
Button register = (Button) findViewById(R.id.navigate_to_login);
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
}
});
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startRegister();
}
});
}
#Override
protected void onStart() {
super.onStart();
}
private void startRegister() {
String email = mEmailField.getText().toString();
String password = mPasswordField.getText().toString();
String confirmPassword = mConfirmPassword.getText().toString();
// Check that fields are not empty
if (TextUtils.isEmpty(email) || TextUtils.isEmpty(password) || TextUtils.isEmpty(confirmPassword)) {
Toast.makeText(Register.this, "Email, password or confirm password field cannot be empty.", Toast.LENGTH_LONG).show();
} else if (!password.equals(confirmPassword)) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
} else {
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Register.this, "Password and confirm password should match", Toast.LENGTH_LONG).show();
}
}
});
}
}
}

facing issue regarding retrofit login in android

I am facing an issue with retrofit login. when i run the application in my cell phone , i logged in with a registered user... login successful... but when i logged out and want to re-login with another account the "application logged me in with the previous account" ... i am not understanding what is this issue please help.
i am not understanding why this issue is occurring with my application.
Note: i am using retrofit (with Firebase) in the application for signup and login.
Thanks
here is the code of my Login Class
private Button forgot ;
private TextView CreactAccount_text;
private EditText login_email , login_password;
private ProgressDialog mLoginProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_);
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
Toolbar toolbar = (Toolbar) findViewById(R.id.login_page_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar()!= null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
FirebaseApp.initializeApp(this);
// Realm.init(this);
// User Session Manager
Window window = getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
window.setStatusBarColor(getColor(R.color.login_statusbar_color));
}
else {
window.setStatusBarColor(getResources().getColor(R.color.login_statusbar_color));
}
mLoginProgress = new ProgressDialog(this);
CreactAccount_text = (TextView) findViewById(R.id.ui_crateaccount_text);
forgot = (Button) findViewById(R.id.ui_btn_forgot);
forgot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent forgot_password = new Intent(Login_Activity.this , Forgot_Password_Activity.class);
startActivity(forgot_password);
}
});
CreactAccount_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent move_signup = new Intent(Login_Activity.this , Signup_Activity.class);
startActivity(move_signup);
}
});
login_email = (EditText) findViewById(R.id.ui_login_email);
login_password = (EditText) findViewById(R.id.ui_login_password);
findViewById(R.id.ui_signin).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usersignin();
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home)
finish();
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(
R.anim.no_anim, R.anim.slide_right_out);
AppUtils.hideSoftKeyboard(this);
}
public void usersignin(){
final String email = login_email.getText().toString().trim();
final String password = login_password.getText().toString().trim();
if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
login_email.setError("Email is not correctly formated");
login_email.requestFocus();
return;
}
if (password.isEmpty()){
login_password.setError("password is required");
login_password.requestFocus();
return;
}
if (password.length() < 6){
login_password.setError("Password should be atleast 6 characters");
login_password.requestFocus();
return;
}
if(!TextUtils.isEmpty(email) || !TextUtils.isEmpty(password)){
mLoginProgress.setTitle("Logging In");
mLoginProgress.setMessage("Please wait while we check your credentials.");
mLoginProgress.setCanceledOnTouchOutside(false);
mLoginProgress.show();
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME,email);
SharedPreferenceUtil.storeStringValue(Login_Activity.this,Constants.PASSWORD,password);
RetrofitUtil.createProviderAPI().userLogin(email , password).enqueue(loginUser(this));
}
}
#Override
public void onLoginUser(RetrofitClientLogin data) {
if(data.getType().equals(Constants.SUCCESS)){
FirebaseInstanceId.getInstance().getToken();
UtilFirebaseAnalytics.logEvent(Constants.EVENT_LOGIN,Constants.KEY_EMAIL,login_email.getText().toString());
SharedPreferenceUtil.storeBooleanValue(this,Constants.ISUSERLOGGEDIN,true);
if(getIntent() != null && getIntent().getBooleanExtra(Constants.IS_RESULT_ACTIVITY,false)){
setResult(RESULT_OK);
}else{
hideProgressDialog();
openAcitivty(Home_Activity.class);
}
loginOnFirebase();
}
}
private void loginOnFirebase(){
final FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
final String email = login_email.getText().toString();
final String password = login_password.getText().toString();
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(Login_Activity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
hideProgressDialog();
finish();
}
});
}else{
hideProgressDialog();
finish();
}
}
});
}
}
protected void openAcitivty(Class<?> cls) {
Intent intent = new Intent(this, cls);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
protected void showProgressDialog(String msg) {
try {
if (mLoginProgress != null && !mLoginProgress.isShowing()) {
mLoginProgress.setMessage(msg);
mLoginProgress.show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void hideProgressDialog() {
try {
if (mLoginProgress != null && mLoginProgress.isShowing()) {
mLoginProgress.dismiss();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onSignup(RetrofitClientLogin data) {
}
#Override
public void OnError(String error) {
hideProgressDialog();
Toast.makeText(this,error,Toast.LENGTH_LONG).show();
}
You're using SharedPreferences for storing login credentials. Once user enters valid login credentials (login ID and password) you store it in SharedPreferences in usersignin() method.
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME, email);
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.PASSWORD, password);
Now, I am assuming (you only posted LoginActivity and didn't mention other parts) that your app has Splash page. Which appears before Login page. In which you decide whether the user has already logged in or not (using SharedPreference values). If yes, redirect to Home page else Login page.
The fix for this issue is very simple. When user logs out from the app, you need to clear SharedPreferences as well.
Like this,
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.USERNAME, null);
SharedPreferenceUtil.storeStringValue(Login_Activity.this, Constants.PASSWORD, null);

Firebase NullPointException when logging in

Hello im trying to create a firebase logging in auth with 2 different users, the admin, and user. but like when i was trying to log in, The application would crash. Heres the error i think
my database
and here is my code on the login
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
auth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//db
mFirebaseInstance = FirebaseDatabase.getInstance();
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, signup.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// 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.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
onAuthSuccess(task.getResult().getUser());
}
}
private void onAuthSuccess(FirebaseUser user) {
if (user !=null){
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user.getUid()).child("type");
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
if(Integer.parseInt(value) == 1) {
startActivity(new Intent(LoginActivity.this, UserActivity.class));
Toast.makeText(LoginActivity.this, "Welcome User", Toast.LENGTH_SHORT).show();
finish();
}else {
startActivity(new Intent(LoginActivity.this, AdminActivity.class));
Toast.makeText(LoginActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
});
}
I feel like the problem lies on the ondata change one but I don't know what to do to fix this, so im asking for your help :O
Try this:
mFirebaseDatabase = FirebaseDatabase.getInstance().getReference().child("Accounts").child("Users").child(user.getUid());
mFirebaseDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.child("type").getValue(String.class);
if(Integer.parseInt(value) == 1) {
startActivity(new Intent(LoginActivity.this, UserActivity.class));
Toast.makeText(LoginActivity.this, "Welcome User", Toast.LENGTH_SHORT).show();
finish();
}else {
startActivity(new Intent(LoginActivity.this, AdminActivity.class));
Toast.makeText(LoginActivity.this, "Welcome", Toast.LENGTH_SHORT).show();
finish();
}
}
try the above, have the reference at the userid then inside onDataChange retrieve the type. you need to reference in order and specify the child name like this:
String value = dataSnapshot.child("type").getValue(String.class);

Why my getUID always be null?

I made an app that can let user log in and set marker on the google map and the marker connect to a chatroom that belongs to the user who set it.
I use firebase mail authentication ,the problem is that i can't get the uid and it's null,i tried a lot of ways,but it still didn't work.
Actually I can sotre my account data in firebase in createActivity with uid and it work,but when I switch to other activity ,the uid became null,I ask this before and someone told me to use this code:
Intent intent = new Intent(CreateActivity.this, MainActivity.class);
intent.putExtra("uid", currentUid);
startActivity(intent);
But it doesn't work.
can someone please help me find where is the problem ,here is my relative code:
LoginActivity:
public void login(View v){
final EditText edUserid = (EditText) findViewById(R.id.eduser);
final EditText edPass = (EditText) findViewById(R.id.edpass);
final String email = edUserid.getText().toString();
final String password = edPass.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "請輸入電子郵件!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "請輸入密碼", Toast.LENGTH_SHORT).show();
return;
}
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// 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()) {
// there was an error
if (password.length() < 6) {
edUserid.setError("密碼太短,請輸入超過6個字元!");
} else {
Toast.makeText(LoginActivity.this, "登入失敗", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(),"登入成功",Toast.LENGTH_LONG).show();
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
intent.putExtra("uid", currentUid);
startActivity(intent);
finish();
}
}
});
}
CreateActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
auth = FirebaseAuth.getInstance();
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void create(View v){
EditText Edcount = (EditText)findViewById(R.id.edcount);
EditText Edpass = (EditText)findViewById(R.id.edpass);
EditText Eduser = (EditText)findViewById(R.id.userid);
EditText Edpassag = (EditText)findViewById(R.id.edpassag);
final String email = Edcount.getText().toString().trim();
final String id = Eduser.getText().toString().trim();
final String password = Edpass.getText().toString().trim();
String password2 = Edpassag.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "請輸入電子郵件!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(id)) {
Toast.makeText(getApplicationContext(), "請輸入用戶名!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "請輸入密碼!", Toast.LENGTH_SHORT).show();
return;
}
if (password.length() < 6) {
Toast.makeText(getApplicationContext(), "密碼太短,請輸入超過6個字元!", Toast.LENGTH_SHORT).show();
return;
}
if(!password.equals(password2)){
Toast.makeText(getApplicationContext(), "密碼前後不符!", Toast.LENGTH_SHORT).show();
return;
}
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(CreateActivity.this, new OnCompleteListener<AuthResult>() {
public void onComplete( Task<AuthResult> task) {
Toast.makeText(CreateActivity.this, "創建成功,歡迎使用SeeDate", Toast.LENGTH_SHORT).show();
// 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()) {
Toast.makeText(CreateActivity.this, "認證失敗或帳號已存在" ,
Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase database = FirebaseDatabase.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
DatabaseReference myRef = database.getReference("Contacts/" + currentUid);
ContactInfo contact1 = new ContactInfo(email,id,password);
myRef.setValue(contact1);//將會員資料寫入FIREBASE
Intent intent = new Intent(CreateActivity.this, MainActivity.class);
intent.putExtra("uid", currentUid);
startActivity(intent);
finish();
}
}
});
}
}
MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
auth = FirebaseAuth.getInstance();
//get current user
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
// user auth state is changed - user is null
// launch login activity
userUID = getIntent().getStringExtra("uid");
}
else{
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
}
public void onStart() {
super.onStart();
auth.addAuthStateListener(authListener);
}
#Override
public void onStop() {
super.onStop();
if (authListener != null) {
auth.removeAuthStateListener(authListener);
}
}
}
MapFragment(store the marker part):
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
Intent intent = new Intent(getActivity(),LoginActivity.class);
startActivity(intent);
}
else{
MainActivity a ;
a = (MainActivity)getActivity();
a.userUID = userUID1;
Log.d("TAG", userUID1);
// userUID = (String) getActivity().getIntent().getExtras().get("uid");
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
mview = inflater.inflate(R.layout.fragment_map, container, false);
return mview;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = (MapView)mview.findViewById(R.id.mapView);
if(mMapView != null){
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseRef = mFirebaseDatabase.getReference("Map/" + userUID1);
mFirebaseRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
LatLng myLatLon = dataSnapshot.getValue(FirebaseMarker.class).toLatLng();
// stash the key in the title, for recall later
Marker myMarker = mgoogleMap.addMarker(new MarkerOptions()
.position(myLatLon).draggable(true).icon(BitmapDescriptorFactory.fromResource(R.drawable.seedloc2)).title(dataSnapshot.getKey()));
// cache the marker locally
markers.put(dataSnapshot.getKey(), myMarker);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
LatLng myLatLon = dataSnapshot.getValue(FirebaseMarker.class).toLatLng();
// Move markers on the map if changed on Firebase
Marker changedMarker = markers.get(dataSnapshot.getKey());
changedMarker.setPosition(myLatLon);
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Marker deadMarker = markers.get(dataSnapshot.getKey());
deadMarker.remove();
markers.remove(dataSnapshot.getKey());
Log.v(TAG, "moved !" + dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.v(TAG, "canceled!" + databaseError.getMessage());
}
});
}
}
#Override
public void onMapReady(final GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mgoogleMap = googleMap;
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
// Remove map markers from Firebase when tapped
FirebaseDatabase.getInstance().getReference();
// String user = ContactInfo.getAccount();
CustomInfoWindowAdapter adapter = new CustomInfoWindowAdapter(MapFragment.this);
googleMap.setInfoWindowAdapter(adapter);
marker.setTitle("的種子");
marker.setSnippet("點選聊天");
marker.showInfoWindow();
// Intent intent = new Intent(getActivity(),ChatActivity.class);
// startActivity(intent);
return true;
}
});
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng latLng) {
// Taps create new markers in Firebase
// This works because jackson can figure out LatLng
mFirebaseRef.push().setValue(new FirebaseMarker(latLng));
}
});
mgoogleMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
// not implemented
}
#Override
public void onMarkerDrag(Marker marker) {
// not implemented
}
#Override
public void onMarkerDragEnd(Marker marker) {
mFirebaseRef.child(marker.getTitle()).setValue(new FirebaseMarker(marker.getPosition()));
}
});
}
}
If you need more information,I'll update it.
You need to change this line:
userUID = getIntent().getStringExtra("uid");
with this line:
String userUID = user.getUid();
Log.d("TAG", userUID);
Hope it helps.
If I donot miss understand, the MapFragment is a part of your MainActivity. Your problem comes from this:
authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
if (user != null) {
userUID = getIntent().getStringExtra("uid");
}
else{
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
}
};
As I can see, your userUID is null until there's an onAuthStateChanged changed. To sovlve it, I suggest to move this line to the onCreate of MainActiviy as your uid is passed to Intent in previous activity.

Categories

Resources