My error;
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.melikerdemkoc.myvetapp/com.melikerdemkoc.myvetapp.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a
null object reference
My code;
import javax.annotation.Nullable;
public class MainActivity extends AppCompatActivity {
private static final int GALLERY_INTENT_CODE = 1023 ;
TextView fullName,email,phone,verifyMsg;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String userId;
Button resendCode;
Button resetPassLocal,changeProfileImage;
FirebaseUser user;
ImageView profileImage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.profilePhone);
fullName = findViewById(R.id.profileName);
email = findViewById(R.id.profileEmail);
resetPassLocal = findViewById(R.id.resetPasswordLocal);
profileImage = findViewById(R.id.profileImage);
changeProfileImage = findViewById(R.id.changeProfile);
FirebaseApp.initializeApp(this);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 6 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(), com.melikerdemkoc.myvetapp.EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
//
}
});
}
.
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(), com.melikerdemkoc.myvetapp.Login.class));
finish();
}
}
I wanna start my app using the firebase database but ı cant do that when ı start the app; my app is crashing.
don't read;
I'm writing because I can't post my questionI'm writing because I can't post my question
Problem
Seems your trying to access a current user does not exist.
Possible Solution
Try checking if user is signed in else should not run the code which needs the current user confirmation.
Here is your refined code.
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.profilePhone);
....
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
if (fAuth.getCurrentUser() != null) {
verifyUser();
}
else {
Log.d("tag", "The user is not authenticated");
}
}
verifyUser Method
public void verifyUser()
{
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 6 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(), com.melikerdemkoc.myvetapp.EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
}
});
}
Hope it solves the problem.
Related
I have implemented the code to upload the user photo to storage and retrieve it to the firestore and realtimeDB. the problem is when I set the imageuri to database :
then I'm (or user) updating a photo to firebase, the URI is successfully updated to the profile string..(firestore) and image srting (realtimeDB). but after some time/after the app closes, the photo not loading properly.(or its gone), it didn't use the firebase token as the download Uri.
its like this :
content://com.android.providers.media.documents/document/image%3A81399
then I attached another code to get the updated image URL from storage. But another problem
for now, Both Databases didn't store the URLs
I have attached the code below.
public class ProfileFragment extends Fragment {
public ProfileFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
CircleImageView profileImageView;
FragmentProfileBinding binding;
private Uri photoUri;
private String imageUrl;
FirebaseFirestore firestore;
FirebaseStorage storage;
FirebaseAuth auth;
StorageReference storageReference;
DocumentReference documentReference;
DatabaseReference DBreference;
String currentUserId;
User user; //class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false);
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = fUser.getUid();
documentReference = firestore.collection("Users").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference().child("Profile Pictures");
DBreference = FirebaseDatabase.getInstance().getReference().child("Users");
update = binding.updateBtn;
profileImageView= binding.profilePhoto;
clickListener();
return binding.getRoot();
}
private void clickListener() {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//noinspection deprecation
startActivityForResult(intent, 3);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.show();
StorageReference reference = storage.getReference().child("Profile Pictures")
.child(FirebaseAuth.getInstance().getUid());
reference.putFile(photoUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imageUrl = uri.toString();
updateUserProfileToFirestore();
updateUserProfileToDataBase();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull #NotNull UploadTask.TaskSnapshot snapshot) {
long totalSi = snapshot.getTotalByteCount();
long transferS = snapshot.getBytesTransferred();
long totalSize = (totalSi / 1024);
long transferSize = transferS / 1024;
progressDialog.setMessage("Uploaded " + ((int) transferSize) + "KB / " + ((int) totalSize) + "KB");
}
});
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (data.getData() != null) {
photoUri = data.getData();
// profileImageView.setImageURI(imageUri);
}
Toast.makeText(getContext(), "Photo selected!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getContext(), "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private void updateUserProfileToFirestore() {
Map<String, Object> profile = new HashMap<>();
profile.put("profile", imageUrl);
final DocumentReference sDoc = firestore.collection("Users").document(FirebaseAuth.getInstance().getUid());
firestore.runTransaction(new Transaction.Function<Void>() {
#Override
public Void apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(sDoc);
transaction.update(sDoc, profile);
// transaction.update(sDoc, "name", binding.nameBox.getText() );
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.setMessage("updated!");
progressDialog.dismiss();
Toast.makeText(getContext(), "Photo Updated!", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.setMessage("Can't upload");
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed to update, try again later", Toast.LENGTH_SHORT).show();
}
});
// final DatabaseReference
}
// Realtime database
private void updateUserProfileToDataBase() {
HashMap<String, Object> map = new HashMap<>();
map.put("image", imageUrl);
DBreference.child(FirebaseAuth.getInstance().getUid())
.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
Solved! It's based on the storage reference. just changed to "reference".
because I already declared the storage reference. but I entered it twice
In my app, First, I am verifying phone numbers by using phone authentication of firebase.
I am doing this process in the OTPVerificationActivity class. Every thing is working fine in this class, I am getting the OTP code also and the user gets signed in.
If the phone number is verified, then I am verifying the email by sending the verification email. I am doing this process in the EmailVerificationActivity class. In this class first, i am checking is the user exists or not. if the user is there, then I am logging out the user.
Then i create the account using createUserWithEmailAndPassword function. After this, i want to send a verification email to the user.
PROBLEM:- Now the problem is, after creating the account,onCreate method gets called again. Due to this, I am unable to send the verification email and the further task. So how to stop onCreate method from getting called again.
NOTE :-
I tried to run only EmailVerificationActivity not OTPVerificationActivity.
In that case every thing was working properly. I was able to send verification email and also able to verify the user.
But when i am using the OTPVerificationActivityand EmailVerificationActivity together i am getting this problem.
So please help me to solve this problem.
public class OTPVerificationActivity extends AppCompatActivity {
String verificationID;
TextView messageTV;
EditText OTPET;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
signInWithCredential(phoneAuthCredential);
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
}
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationID = s;
Log.i("onSend",s);
}
};
String phoneNumber;
public void sendVerificationCode(View view)
{
String code = OTPET.getText().toString();
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationID,code);
signInWithCredential(credential);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otpverification);
messageTV = (TextView) findViewById(R.id.messageTextView);
OTPET = (EditText) findViewById(R.id.OTPEditText);
mAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null)
{
firebaseAuth.signOut();
if(firebaseAuth.getCurrentUser() == null)
{
Intent intent = new Intent(OTPVerificationActivity.this,EmailVerification.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else
{
Log.i("firebaseAuth","user is not null");
}
}
}
};
String message = "Please type the verification code sent to ";
messageTV.setText(message+" " + "+91 " + getIntent().getStringExtra("phoneNumber"));
phoneNumber = "+91" + getIntent().getStringExtra("phoneNumber");
sendPhoneNumber(phoneNumber);
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mAuth.getCurrentUser() != null)
{
mAuth.signOut();
}
}
public void sendPhoneNumber(String number)
{
Log.i("sendPhoneNumber","inside it");
PhoneAuthProvider.getInstance().verifyPhoneNumber(
number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
Log.i("sendPhoneNumber","outside it");
}
private void signInWithCredential(final PhoneAuthCredential credential)
{
mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(!task.isSuccessful())
{
Toast.makeText(OTPVerificationActivity.this, "Sign in Failed.", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(OTPVerificationActivity.this, "Phone number verified.", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("FailedListener",e.getMessage());
}
});
}
}
Below is the code of EmailVerificationActivity class.
public class EmailVerification extends AppCompatActivity {
EditText emailET, passwordET, confirmPasswordET;
AlertDialog.Builder builder;
AlertDialog alertDialog;
ProgressDialog progressDialog;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthStateListener;
public void login(View view)
{
startActivity(new Intent(EmailVerification.this,MainActivity.class));
}
public void submit(View view)
{
String email = emailET.getText().toString();
String password = passwordET.getText().toString();
String confirmPassword = confirmPasswordET.getText().toString();
if(!(TextUtils.isEmpty(email) && TextUtils.isEmpty(password)))
{
if(password.equals(confirmPassword))
{
progressDialog.show();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
//acount created...
mAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Log.i("verificationEmail","send");
progressDialog.dismiss();
if(!EmailVerification.this.isFinishing())
{
alertDialog.show();
}
Toast.makeText(EmailVerification.this, "Email send successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("verificationEmail","Not send");
//failed to create account...
progressDialog.dismiss();
Toast.makeText(EmailVerification.this, "Failed to create account", Toast.LENGTH_SHORT).show();
}
});
}
else
{
//account not created...
progressDialog.dismiss();
Log.i("taskNotSuccessful",task.getException().getMessage());
Toast.makeText(EmailVerification.this, "Problem in creating account", Toast.LENGTH_SHORT).show();
}
}
});
}
else
{
Toast.makeText(this, "Confirm Password is not same as Password.", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(this, "Fields are empty.", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_email_verification);
Log.i("onCreate","inside it");
initializeWidgets();
progressDialog = new ProgressDialog(EmailVerification.this);
progressDialog.setMessage("Sending verification email.");
builder= new AlertDialog.Builder(EmailVerification.this);
builder.setTitle("Email Verification")
.setMessage("We sent you a verification email, Please verify email before moving further.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(EmailVerification.this,SignInActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
alertDialog = builder.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE).setTextColor(R.style.MyProgressDialogStyle);
}
});
mAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null)
{
// user is signed up...
Log.i("mAuthStateChanged","user is not null.");
}
else
{
Log.i("mAuthStateChanged","user is null");
}
}
};
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
}
private void initializeWidgets()
{
emailET = (EditText) findViewById(R.id.EmailEditText);
passwordET = (EditText) findViewById(R.id.PasswordEditText);
confirmPasswordET = (EditText) findViewById(R.id.ConfirmPasswordEditText);
}
}
This is the android life cycle. onCreate() will be called again, if your activity was destroyed due to release memory, explicitly killing and etc.
When you switch activities usually activities won't get killed. but it may be killed in some cases. so please move your codes from onCreate() to somewhere else.
You can not control android life cycle. It will happen anyway. therefore you need to obey them
I'm making an Android project, and for starters I have been figuring out how signing up works. By the way, I used Firebase for this. Here's my code:
package com....
import...
public class MainActivity extends AppCompatActivity {
//VIEW AND WIDGETS
Button createUser, moveToLoginBtn;
EditText userEmailEdit, userPasswordEdit;
//FIREBASE AUTH FIELDS
FirebaseAuth nAuth;
FirebaseAuth.AuthStateListener nAuthlistener;
DatabaseReference mDatabaseRef, mUserCheckData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ASSIGN ID
createUser = (Button) findViewById(R.id.createUserBtn);
moveToLoginBtn = (Button) findViewById(R.id.moveToLogin);
userEmailEdit = (EditText) findViewById(R.id.emailEditTextCreate);
userPasswordEdit = (EditText) findViewById(R.id.passEditTextCreate);
//ASSIGN INSTANCE
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUserCheckData = FirebaseDatabase.getInstance().getReference().child("Users");
nAuth = FirebaseAuth.getInstance();
nAuthlistener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
final String emailForVer = user.getEmail();
mUserCheckData.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkUserValidation(dataSnapshot, emailForVer);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
}
}
};
//ON CLICK LISTENER
createUser.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final String userEmailString, userPassString;
userEmailString = userEmailEdit.getText().toString().trim();
userPassString = userPasswordEdit.getText().toString().trim();
if (!TextUtils.isEmpty(userEmailString) && !TextUtils.isEmpty(userPassString))
{
nAuth.createUserWithEmailAndPassword(userEmailString,userPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("emailUser").setValue(userEmailString);
mChildDatabase.child("passWordUser").setValue(userPassString);
Toast.makeText(MainActivity.this, "User Account Created!", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, Profile.class));
}
else
{
Toast.makeText(MainActivity.this, "User Account Creation Fail", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
}
});
}
}
});
//MOVE TO LOGIN
moveToLoginBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot) iterator.next();
if(String.valueOf(dataUser.child("emailUser").getValue()).equals(emailForVer) && dataUser.child("emailUser") != null)
{
if(String.valueOf(dataUser.child("isVerified").getValue()).equals("unverified") && dataUser.child("isVerified") != null)
{
Intent in = new Intent(MainActivity.this, Profile.class);
in.putExtra("USER_KEY" , String.valueOf(dataUser.child("userKey").getValue()));
startActivity(in);
//in.putExtra("NAME_KEY" , String.valueOf(dataUser.child("nameKey").getValue()));
}else
{
startActivity(new Intent(MainActivity.this, Welcome.class));
}
}
}
}
#Override
protected void onStart() {
super.onStart();
nAuth.addAuthStateListener(nAuthlistener);
}
#Override
protected void onStop() {
super.onStop();
nAuth.removeAuthStateListener(nAuthlistener);
}
}
I think I have implemented my methods correctly. But it toasts:
User Account Creation Failed
Is my
checkUseValidation() method wrong? Any kind of help is appreciated.
Also please pay attention to my:
public void onComplete
method, I have set it right I think. I don't know why the data isn't getting saved to the firebase database. Or why is the task unsuccesful as show in line:
if (task.isSuccessful())
Thank you very much.
First, you should change the toast, in your fail condition, to
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
So that you get what wrong in the task.
But before that did you enable Email/Password in the console????
See Sign up new users from url: https://firebase.google.com/docs/auth/android/start/?authuser=0
If task.isSuccessful() is false.You can add this to get error
Log.w(TAG, "createUserWithEmail:failure",task.getException());
Update you code as:
createUser.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final String userEmailString, userPassString;
userEmailString = userEmailEdit.getText().toString().trim();
userPassString = userPasswordEdit.getText().toString().trim();
if (!TextUtils.isEmpty(userEmailString) && !TextUtils.isEmpty(userPassString))
{
nAuth.createUserWithEmailAndPassword(userEmailString,userPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("emailUser").setValue(userEmailString);
mChildDatabase.child("passWordUser").setValue(userPassString);
Toast.makeText(MainActivity.this, "User Account Created!", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, Profile.class));
}
else
{
Log.w("TAG", "createUserWithEmail:failure",task.getException());
Toast.makeText(MainActivity.this, "User Account Creation Fail", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
}
});
}
}
});
You should see warning in logcat:
In my application, I have two users--Event Member and Client--they have separate user login and registration. If a client log in he will go to the the client activity; if an event member will log in he will go to the event member activity. How will I make sure that the email is a client or an event member?
Below image shows my firebase structure:
Here is my code:
SignupClient.java
signupClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String cemail = clie_email.getText().toString().trim();
final String cpassword = clie_password.getText().toString().trim();
String ccpassword = clie_cpassword.getText().toString().trim();
final String cfname = clie_firstname.getText().toString().trim();
final String clname = clie_lastname.getText().toString().trim();
final String cbday = clie_birthday.getText().toString().trim();
final String ccountry = clie_country.getSelectedItem().toString();
final String cmobile = clie_mobile.getText().toString().trim();
auth.createUserWithEmailAndPassword(cemail, cpassword)
.addOnCompleteListener(_5_SignupClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(_5_SignupClient.this, "createUserWithEmail: onComplete" + task.isSuccessful(), Toast.LENGTH_LONG).show();
if (!task.isSuccessful()){
Toast.makeText(_5_SignupClient.this, "Authentication Failed" + task.getException(),
Toast.LENGTH_LONG).show();
}
else {
AccountInfo accountInfo = new AccountInfo(cfname, clname, cemail, cpassword, cbday, ccountry, cmobile);
mDatabaseReference.child("client").push().setValue(accountInfo);
startActivity(new Intent(_5_SignupClient.this, _7_ViewClient.class));
finish();
}
}
});
}
});
LoginClient.java
loginClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String clie_unameemail = clie_emailuname.getText().toString();
final String clie_pass = clie_password.getText().toString();
if(TextUtils.isEmpty(clie_unameemail)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(clie_pass)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(clie_unameemail, clie_pass)
.addOnCompleteListener(_3_LoginClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
ref = FirebaseDatabase.getInstance().getReference().child("client");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(FirebaseAuth.getInstance().getCurrentUser().getUid().equals(snapshot.getKey())){
startActivity(new Intent(_3_LoginClient.this, _7_ViewClient.class));
}
}
// startActivity(new Intent(_3_LoginClient.this, Normal_memberActivity.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
// User is signed out
}
// ...
}
};
if (!task.isSuccessful()) {
// there was an error
if (clie_pass.length() < 8) {
clie_password.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(_3_LoginClient.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(_3_LoginClient.this, "Successfully Registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(_3_LoginClient.this, _7_ViewClient.class);
startActivity(intent);
finish();
}
}
});
}
});
I hope you could help me. Thank you!
On your db there should be one more field like we say it USER_TYPE. While registering the user send its USER_TYPE. suppose if you are registering a user as a CLIENT then inser db value USER_TYPE="CLIENT" and if its as an Event member registration then inser db value USER_TYPE="EVENT" and now once you logged in check its USER_TYPE and redirect him based upon his USER_TYPE
I'm developing an android app. Some data is getting retrieved from the FirebaseDatabase and is getting shown in a RecyclerView in my app.
The RecyclerView has cards in it. In every card, the images and text is shown. On the card there is a 'share' button, by clicking on which a dynamic-link is generated and is getting shared with anybody. When I click on the shared dynamic-link, the app gets open and what happens is that the image which was on the same card the share button was clicked is getting displayed, but the text is always getting displayed of the last saved data. I hope you got my point.
Here's how I'm generating dynamic-link:
Button btnShare = (Button) holder.itemView.findViewById(R.id.btn_share);
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Uri BASE_URL = Uri.parse("http://www.appwebsite.com/");
holder.APP_URI = BASE_URL.buildUpon().path(imageUIDh).build();
packageName = holder.itemView.getContext().getPackageName();
deepLinkTS = Uri.parse("https://u9p25.app.goo.gl/?link="+holder.APP_URI+"&apn="+packageName+"&amv="+16+"&ad="+0);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Please help this needy: " + deepLinkTS.toString() + "\n-shared through app.");
holder.itemView.getContext().startActivity(Intent.createChooser(intent, "Share via..."));
}
});
Here's how I'm handling dynamic-link in onCreate() method of MainActivity.class:
boolean autoLaunchDeepLink = false;
AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, MainActivity.this, autoLaunchDeepLink)
.setResultCallback(
new ResultCallback<AppInviteInvitationResult>() {
#Override
public void onResult(#NonNull AppInviteInvitationResult result) {
if (result.getStatus().isSuccess()) {
// Extract deep link from Intent
Intent intent = result.getInvitationIntent();
final String deepLink = AppInviteReferral.getDeepLink(intent);
// Handle the deep link. For example, open the linked
// content, or apply promotional credit to the user's
// account.
final ProgressDialog openingSharedRequest = new ProgressDialog(MainActivity.this);
openingSharedRequest.setMessage("Opening shared help-request...");
openingSharedRequest.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent helpRequestIntent = new Intent(MainActivity.this, HelpRequestThroughDeepLink.class);
helpRequestIntent.putExtra("deepLink", deepLink);
// helpRequestIntent.putExtra("deepLinkTS", HelpRequest.deepLinkTS.toString());
// helpRequestIntent.putExtra("APP_URI", HelpRequest.ViewHolder.APP_URI.toString());
helpRequestIntent.putExtra("postedFrom", postedFromS);
// new AlertDialog.Builder(MainActivity.this)
// .setMessage(deepLink)
// .setPositiveButton("OK", null)
// .create()
// .show();
startActivity(helpRequestIntent);
openingSharedRequest.dismiss();
}
}, 1200);
// [START_EXCLUDE]
// Display deep link in the UI
// ((TextView) findViewById(R.id.link_view_receive)).setText(deepLink);
// [END_EXCLUDE]
} else {
// Log.d(TAG, "getInvitation: no deep link found.");
// Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
}
});
// [END get_deep_link]
Here's code from HelpRequestThroughDeepLink.java:
public class HelpRequestThroughDeepLink extends AppCompatActivity {
String deepLink, deepLinkTS, APP_URI, imageUID, imageUIDFD, hDescription;
Button btn_accept, btn_reject;
ImageView hImageHDL;
TextView imageUIDHDL, hDescriptionHDL;
DatabaseReference databaseReference1, databaseReferenceUsers;
MapView mapView;
ProgressBar progressBar;
CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help_request_through_deep_link);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.myCoordinatorLayout);
databaseReference1 = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/");
databaseReferenceUsers = FirebaseDatabase.getInstance().getReferenceFromUrl("https://humanehelper-e8a22.firebaseio.com/users");
if (getIntent().getExtras() != null) {
deepLink = getIntent().getExtras().getString("deepLink");
deepLinkTS = getIntent().getExtras().getString("deepLinkTS");
APP_URI = getIntent().getExtras().getString("APP_URI");
postedFrom = getIntent().getExtras().getString("postedFrom");
String imageUIDD = deepLink.substring(28);
try {
imageUID = URLDecoder.decode(imageUIDD, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
} else {
Toast.makeText(getBaseContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
hImageHDL = (ImageView) findViewById(R.id.hImageHDL);
imageUIDHDL = (TextView) findViewById(R.id.imageUIDHDL);
hDescriptionHDL = (TextView) findViewById(R.id.homelessDescriptionHDL);
btn_accept = (Button) findViewById(R.id.btn_accept);
btn_reject = (Button) findViewById(R.id.btn_reject);
progressBar = (ProgressBar) findViewById(R.id.progressBar_loading_image);
}
public void operateDeepLinkRequest() {
if (deepLink.contains(imageUID)) {
if ((imageUID.startsWith("https://firebasestorage.googleapis.com/") || imageUID.startsWith("content://"))) {
retrieveRespectiveRequest();
}
}
}
public void retrieveRespectiveRequest() {
databaseReference1.child("help-requests").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
imageUIDFD = newRequest.get("imageUIDh");
hDescription = newRequest.get("hDescription");
progressBar.setVisibility(View.VISIBLE);
imageUIDHDL.setText(imageUID);
doSomethingWithPicaso(imageUID, hImageHDL);
hDescriptionHDL.setText(hDescription);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
databaseReference1.child("help-requests").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void doSomethingWithPicaso(String imageUIDh, ImageView target){
// Picasso.with(itemView.getContext()).cancelRequest(homelessImage);
Picasso.with(getBaseContext())
.load(imageUIDh)
.error(R.drawable.ic_warning_black_24dp)
.into(target, new Callback() {
#Override
public void onSuccess() {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onError() {
Toast.makeText(getBaseContext(), "Error occurred while loading images. Please retry.", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.INVISIBLE);
}
});
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) HelpRequestThroughDeepLink.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public void ifNetworkAvailable(){
if (isNetworkAvailable()) {
operateDeepLinkRequest();
} else {
Snackbar.make(findViewById(R.id.myCoordinatorLayout), "No internet connection!", Snackbar.LENGTH_LONG)
.setAction("RETRY", new View.OnClickListener() {
#Override
public void onClick(View view) {
ifNetworkAvailable();
}
})
.setDuration(Snackbar.LENGTH_INDEFINITE)
.show();
}
}
}
Please let me know how can I achieve this?