Made registration using Firebase. I need that when clicking on the same CardView different DialogFragment opens and the condition is whether the user is logged in or not, i.e. by clicking on the CardView, DialogFragment1 opens in which the user logs in, if everything is successful DialogFragment1 is closed and when the CardView is pressed again, DialogFragment2 is opened, how to do this?
My dialog through which the user logs in
public class FragmentDialogLogin extends Fragment {
public static CardView close_dl, login_LG;
public static boolean isRememberUserLogin;
CardView registration;
public static EditText User_Name_LG;
public static EditText User_Password_LG;
public static String name;
public static String surname;
public static String email;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
#SuppressLint("StaticFieldLeak")
public static LinearLayout Ll_LG;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_dialog_login, container, false);
}
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
firebaseAuth = FirebaseAuth.getInstance();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
close_dl = view.findViewById(R.id.close_dl);
close_dl.setOnClickListener(v -> {
closeDialog();
});
registration = view.findViewById(R.id.registration);
registration.setOnClickListener(v -> {
int current = DialogAuthorization.VP_dialog_authorization.getCurrentItem();
int totalItems = DialogAuthorization.VP_dialog_authorization.getAdapter().getCount();
if (current < totalItems - 1) {
DialogAuthorization.VP_dialog_authorization.setCurrentItem(current + 1, true);
}
});
User_Name_LG = view.findViewById(R.id.User_Name_LG);
User_Password_LG = view.findViewById(R.id.User_Password_LG);
login_LG = view.findViewById(R.id.login_LG);
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = User_Name_LG.getText().toString().trim();
String password = User_Password_LG.getText().toString().trim();
if (TextUtils.isEmpty(email)) {
User_Name_LG.setError("Email is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
User_Password_LG.setError(getText(R.string.Rink));
return;
}
if (password.length() < 6) {
User_Password_LG.setError("Password Must be >= 6 Characters");
return;
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
private void closeDialog() {
Fragment prev = requireActivity().getSupportFragmentManager().findFragmentByTag("DialogAuthorization");
if (prev != null) {
DialogAuthorization df = (DialogAuthorization) prev;
df.dismiss();
}
}
}
The simplest way to check whether user logged in or not is to call getCurrentUser();
private DatabaseReference rootReference;
private DatabaseReference usersRef;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onViewCreated(#NonNull final View view, #Nullable Bundle savedInstanceState) {
...
rootReference = FirebaseDatabase.getInstance().getReference();
usersRef = rootReference.child("Users");
...
login_LG.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
// User already logged in
if (firebaseAuth.getCurrentUser() != null) {
// Todo: close dialog fragment 1 and open dialog fragment 2
return;
}
// user did not log in
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Store that user logged in with email
String currentUserId = firebaseAuth.getCurrentUser().getUid();
rootReference.child("Users").child(currentUserId).setValue("email");
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
You can add the int at the class as increment. You can do something like this.
At the class.
public static String surname;
public static String email;
private int counter = 1; //Add this one.
And then at the method onComplete()
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(getContext(), "Logged in Successfully", Toast.LENGTH_SHORT).show();
if (counter >1){
//DialogFragment2
}else{
DialogProfile dialog = new DialogProfile();
dialog.show(requireFragmentManager(), "DialogProfile");
counter++; //increment
}
} else {
Toast.makeText(getContext(), "Error ! " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
Related
I'm trying to make the data get update in firestore with the method updatedata but for some reason instead of the data being updated, a new user gets created with the data I'm supposed to be updating, I don't get why, I've been stuck on it for hours now and any help will be appreciated, this is the class where I either save data or update it:
public class Admin_add extends AppCompatActivity {
public static final String TAG = "TAG";
EditText mFullName, mEmail, mPassword, mPhone;
Button mAddBtn,leaveAdd;
FirebaseAuth fAuth;
ProgressBar progressBar;
FirebaseFirestore fStore;/*db*/
String UserID;
Button showall;
private String uName,uEmail,uPhone,uPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add);
mFullName = findViewById(R.id.fullName1);
mEmail = findViewById(R.id.Email1);
mPassword = findViewById(R.id.password1);
mPhone = findViewById(R.id.phone1);
mAddBtn = findViewById(R.id.adduserbtn);
leaveAdd=findViewById(R.id.leaveadd);
showall=findViewById(R.id.showallbtn);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
fStore = FirebaseFirestore.getInstance();
Bundle bundle=getIntent().getExtras();
if(bundle!=null){
mAddBtn.setText("update");
uName=bundle.getString("uName");
uEmail=bundle.getString("uEmail");
uPhone=bundle.getString("uPhone");
uPassword=bundle.getString("uPassword");
mFullName.setText(uName);
mPhone.setText(uPhone);
mEmail.setText(uEmail);
mPassword.setText(uPassword);
}else{
mAddBtn.setText("save");
}
leaveAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),AdminAct.class));
finish();
}
});
showall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),Crud_users.class));
}
});
mAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
final String password = mPassword.getText().toString().trim();
final String fullname = mFullName.getText().toString();
final String phone = mPhone.getText().toString();
if (TextUtils.isEmpty(email)) {
mEmail.setError("Email Is Required.");
return;
}
if (TextUtils.isEmpty(password)) {
mPassword.setError("Password Is Required.");
return;
}
if (password.length() < 8) {
mPassword.setError("Password must be>=8 characters");
}
progressBar.setVisibility(View.VISIBLE);
Bundle bundle1=getIntent().getExtras();
if(bundle1!=null){
String id=UserID;
updateToFireStore(fullname,email,password,phone);
}else{
fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(Admin_add.this, "user created", Toast.LENGTH_SHORT).show();
UserID = fAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(UserID);
Map<String, Object> user = new HashMap<>();
user.put("fName", fullname);
user.put("email", email);
user.put("phone", phone);
user.put("Password", password);
//specify if user is admin
user.put("isUser", "1");
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "OnSuccess: user profile is created for" + UserID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "Failure" + e.toString());
}
});
progressBar.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(Admin_add.this, "ERROR" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
//register to firebase
}
});
}
private void updateToFireStore(String fullname, String email, String password, String phone) {
UserID = fAuth.getCurrentUser().getUid();
fStore.collection("users").document(UserID).update("email",email,"Password",password,"fName",fullname,"phone",phone)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(Admin_add.this, "data updated", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Admin_add.this, "Error"+task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Admin_add.this, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
i think there is a problem somewhere in updatetofirestore method, this is my adapater class:
public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.MyViewHolder> {
private Crud_users activity;
private List<usersmodel> mList;
public UsersAdapter(Crud_users activity,List<usersmodel> mList){
this.activity=activity;
this.mList=mList;
}
public void updateData(int position){
usersmodel item=mList.get(position);
Bundle bundle=new Bundle();
bundle.putString("uName",item.getfName());
bundle.putString("uEmail",item.getEmail());
bundle.putString("uPhone",item.getPhone());
bundle.putString("uPassword",item.getPassword());
Intent intent=new Intent(activity,Admin_add.class);
intent.putExtras(bundle);
activity.startActivity(intent);
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(activity).inflate(R.layout.list_item_single,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.name.setText(mList.get(position).getfName());
holder.email.setText(mList.get(position).getEmail());
holder.phone.setText(mList.get(position).getPhone());
holder.isuser.setText(mList.get(position).getIsUser());
}
#Override
public int getItemCount() {
return mList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView name,email,phone,isuser;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
name=itemView.findViewById(R.id.list_name);
email=itemView.findViewById(R.id.list_email);
phone=itemView.findViewById(R.id.list_phone);
isuser=itemView.findViewById(R.id.list_isuser);
}
}
}
I really have no clue i've tried everything i can.
I think you should change the way you pass values to update() method of firebase.
fStore.collection("users").document(UserID).update("email",email,"Password",password,"fName",fullname,"phone",phone)
The correct way is to pass a map<String, Object>. Below is the example:
Map<String, Object> data = new HashMap<String, Object>();
data.put("email", email);
data.put("Password", password);
data.put("fName", fullname);
data.put("phone", phone);
fStore.collection("users").document(UserID).update(data);
You can use set() method of Firebase with SetOptions.merge() as an alternative which is better than update() because update() will update a field only if it exists where set() with SetOptions.merge() will update the existing field and create if it doesn't exist.
Read more about it here.
Map<String, Object> data = new HashMap<String, Object>();
data.put("email", email);
data.put("Password", password);
data.put("fName", fullname);
data.put("phone", phone);
fStore.collection("users").document(UserID).set(data, SetOptions.merge());
I'm trying to authenticate user with phone number using the firebase Authentication method. But it is showing me error after some time by running the code. And I think the sendVerificationCodeToUser() function is not working properly.
package com.example.foodapp;
import ...
public class PhoneVerification<phoneAuthProvider> extends AppCompatActivity {
String verificationCodeBySystem;
Button btn_verify;
EditText phoneenteredbyuser;
ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_verification);
btn_verify = findViewById(R.id.btn_verify);
phoneenteredbyuser = findViewById(R.id.txt_otp);
progressbar = findViewById(R.id.progressbar);
progressbar.setVisibility(View.GONE);
String phoneNo = getIntent().getStringExtra("phone");
sendVerificationCodeToUser(phoneNo);
btn_verify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code= phoneenteredbyuser.toString();
if(code.isEmpty() || code.length()< 6){
phoneenteredbyuser.setError("Wrong OTP...");
phoneenteredbyuser.requestFocus();
return;
}
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
FirebaseAuth mAuth= FirebaseAuth.getInstance();
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber("+92" + phoneNo) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override //Entering OTP by manual way
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s;
}
#Override // Automatically Verifying the OTP by system.
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if (code != null) {
progressbar.setVisibility(View.VISIBLE);
verifyCode(code);
}
}
#Override //In case of error this code will run.
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(PhoneVerification.this, "Error Occured", Toast.LENGTH_SHORT).show();
}
};
private void verifyCode(String codeByUser) {
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem, codeByUser);
signInUserByCredentials(credential);
}
private void signInUserByCredentials(PhoneAuthCredential credential) {
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(PhoneVerification.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Toast.makeText(PhoneVerification.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
//Perform Your required action here to either let the user sign In or do something required
Intent intent = new Intent(getApplicationContext(), User_Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Toast.makeText(PhoneVerification.this, task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
After pressing verify button to send me the code the application opens browser and wait sometime. Nothing happens and no SMS sent to me and this toast appears to me. before you ask i made everything before, firebase and and SHA certificate fingerprints.
public class PhoneSingUp extends AppCompatActivity {
private FirebaseAuth auth;
TextView SignUpTXT , VerifyingTXT , ErrorTXT ;
GifImageView VerifySuccess ;
Button VerifyBTN , ContinueBTN ;
CountryCodePicker ccp;
EditText NumberEnt;
PinView VerifyPIN;
String VerifyCodeBySystem , Code , CountryCodeS ,UserEnteredNumber , PhoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_phone_sing_up);
auth = FirebaseAuth.getInstance();
SignUpTXT = findViewById(R.id.SingUpTXT);
ccp = (CountryCodePicker) findViewById(R.id.ccp);
NumberEnt = (EditText) findViewById(R.id.editText_carrierNumber);
VerifyingTXT = findViewById(R.id.verifyingTXT);
ErrorTXT = findViewById(R.id.ErrorTXT);
VerifyPIN = findViewById(R.id.VerificationPIN);
VerifySuccess = findViewById(R.id.VerifySuccess);
VerifyBTN = findViewById(R.id.VerifyBTN);
VerifyBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CountryCodeS = ccp.getSelectedCountryCode();
UserEnteredNumber = NumberEnt.getText().toString();
PhoneNumber = "+" + CountryCodeS + UserEnteredNumber;
if (PhoneNumber.length() < 13){
ErrorTXT.setVisibility(View.VISIBLE);
VerifyingTXT.setVisibility(View.INVISIBLE);
}else {
if (PhoneNumber.length() == 13) {
ErrorTXT.setVisibility(View.GONE);
VerifyingTXT.setVisibility(View.VISIBLE);
sendVerificationCode(PhoneNumber);
}
}
}
});
ContinueBTN = findViewById(R.id.ContinueBTN);
ContinueBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(PhoneSingUp.this, MainActivity.class));
finish();
}
});
}
private void sendVerificationCode(String phoneNumber) {
PhoneAuthOptions options =
PhoneAuthOptions.newBuilder(auth)
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity(PhoneSingUp.this) // Activity (for callback binding)
.setCallbacks(mCallbacks) // OnVerificationStateChangedCallbacks
.build();
PhoneAuthProvider.verifyPhoneNumber(options);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
VerifyCodeBySystem = s;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
Code = phoneAuthCredential.getSmsCode();
if (Code != null){
VerifyPIN.setText(Code);
VerifyCode(Code);
VerifySuccess.setVisibility(View.VISIBLE);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(PhoneSingUp.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
};
private void VerifyCode(String code) {
PhoneAuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(VerifyCodeBySystem,code);
signInWithPhoneAuthCredential(phoneAuthCredential);
}
private void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) {
auth.signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
} else {
if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
}
}
}
});
}
}
I am working on a project which required firebase utilities so I did all those things required but my authentication is not taking place and thereby my data is not being uploaded in the firestore. I have tried many things and found that during the time of execution my onComplete listener is calling failure and thus a toast is popped authentication failure so I think the main problem lies in the onComplete listener but I couldn't fix it. My code is as follows-
*
private TextView username;
private TextView password;
private AutoCompleteTextView email;
private ProgressBar progress_bar;
private FirebaseAuth firebaseAuth;
private FirebaseAuth.AuthStateListener authStateListener;
private FirebaseUser currentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username_account);
password = findViewById(R.id.password_account);
email = findViewById(R.id.email_account);
Button create_account = findViewById(R.id.create_acct_button);
progress_bar = findViewById(R.id.create_acct_progress);
firebaseAuth = FirebaseAuth.getInstance();
create_account.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!TextUtils.isEmpty(email.getText().toString())
&& !TextUtils.isEmpty(password.getText().toString())
&& !TextUtils.isEmpty(username.getText().toString())) {
String Email = email.getText().toString().trim();
String Password = password.getText().toString().trim();
String Username = username.getText().toString().trim();
createUserEmailAccount(Email, Password, Username);
} else {
Toast.makeText(CreateAccountActivity.this,
"Empty Fields Not Allowed",
Toast.LENGTH_LONG)
.show();
}
}
});
}
private void createUserEmailAccount(String email, String password, final String username) {
if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password) && !TextUtils.isEmpty(username)) {
progress_bar.setVisibility((View.VISIBLE));
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener( CreateAccountActivity.this,new OnCompleteListener<AuthResult>() {
#Override
public void onComplete( #NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Map<String, Object> userobj = new HashMap<>();
userobj.put("userId", "currentuserId");
userobj.put("username", username);
db.collection("journal")
.add(userobj)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot successfully written!");
progress_bar.setVisibility(View.INVISIBLE);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});
} else {
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(CreateAccountActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
progress_bar.setVisibility(View.INVISIBLE);
}
}
});
}
}
}*
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.