encrypt and decrypt with AESCrypt in android - android

I'm developing an app, but I found a problem. I can encrypt but I can not decipher. Can you help me fix it?
the app comes to sensitive data and I would like to send in Firebase encrypted data but they remain decrypted on the list.
This is my code:
public class UserActivity extends AppCompatActivity {
private EditText input_tipo, input_id, input_password;
private ListView list_data;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mDatabaseReference;
private FirebaseAnalytics firebaseAnalytics;
private List<User> list_users = new ArrayList<>();
private User selectedUser;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
private String encryptPass, decryptPass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
Toolbar tool = (Toolbar) findViewById(R.id.toolbar);
tool.setTitle("MySecurity");
setSupportActionBar(tool);
input_tipo = (EditText) findViewById(R.id.tipo);
input_id = (EditText) findViewById(R.id.id);
input_password = (EditText) findViewById(R.id.password);
list_data = (ListView) findViewById(R.id.list_data);
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
list_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
User user = (User) adapterView.getItemAtPosition(i);
selectedUser = user;
input_tipo.setText(user.getTipo());
input_id.setText(user.getId());
input_password.setText(user.getPassword());
}
});
initFirebase();
addEventFirebaseListener();
findNetwork();
}
private void findNetwork() {
ConnectivityManager CM = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo ninfo = CM.getActiveNetworkInfo();
if (ninfo != null && ninfo.isConnectedOrConnecting()) {
Toast.makeText(getBaseContext(), "Connesso in Firebase:" + ninfo.getTypeName(), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Connessione internet assente", Toast.LENGTH_LONG).show();
}
}
private void addEventFirebaseListener() {
list_data.setVisibility(View.VISIBLE);
mDatabaseReference.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (list_users.size() > 0)
list_users.clear();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
User user = postSnapshot.getValue(User.class);
list_users.add(user);
}
ListViewAdapter adapter = new ListViewAdapter(UserActivity.this, list_users);
list_data.setAdapter(adapter);
list_data.setVisibility(View.VISIBLE);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void initFirebase() {
FirebaseApp.initializeApp(this);
mFirebaseDatabase = FirebaseDatabase.getInstance();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
firebaseAnalytics = FirebaseAnalytics.getInstance(this);
firebaseAnalytics.setAnalyticsCollectionEnabled(true);
firebaseAnalytics.setMinimumSessionDuration(5000);
mDatabaseReference = mFirebaseDatabase.getReference().child("users").child(mUser.getUid());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_add) {
createUser();
} else if (item.getItemId() == R.id.menu_remove) {
deleteUser(selectedUser);
} else if (item.getItemId() == R.id.menu_deselect) {
DeselectedUser(selectedUser);
}else if(item.getItemId()== R.id.menu_decrypt){
DecryptUser(selectedUser);
}
return true;
}
private void DecryptUser(User selectedUser) {
if (selectedUser != null) {
mDatabaseReference.child("users").child(selectedUser.getUid());
String password = selectedUser.getPassword().trim();
String Message= selectedUser.getPassword().trim();
try {
decryptPass= AESCrypt.decrypt( password, Message);
input_tipo.setText(input_tipo.getText().toString());
input_id.setText(input_id.getText().toString());
input_password.setText(decryptPass);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void DeselectedUser(User selectedUser) {
if (selectedUser != null) {
mDatabaseReference.child("users").child(selectedUser.getUid());
clearEditText();
}
}
private void deleteUser(User selectedUser) {
if (selectedUser != null) {
mDatabaseReference.child("users").child(selectedUser.getUid()).removeValue();
clearEditText();
}
}
private void createUser() {
String password = input_password.getText().toString().trim();
String Message= input_password.getText().toString().trim();
try {
encryptPass = AESCrypt.encrypt(password, Message);
User user1= new User(UUID.randomUUID().toString(), input_tipo.getText().toString(),
input_id.getText().toString(), encryptPass);
mDatabaseReference.child("users").child(user1.getUid()).setValue(user1);
clearEditText();
} catch (Exception e) {
e.printStackTrace();
}
}
private void clearEditText() {
input_tipo.setText("");
input_id.setText("");
input_password.setText("");
}
#Override
protected void onStop() {
super.onStop();
finish();
}
}

The password and Message variables are assigned the same thing (selectedUser.getPassword().trim()). What you are doing is trying to decrypt the user password, using the user password. Probably you need to assign the ciphertext that you want to decrypt to the Message variable.

Related

How to allow users to change password before they logging in?

I would like to allow the users to change their password before logging in. In practice I have LoginActivity that with a clickable textview redirects to an activity where the user enters his email and the new password to be set. The problem is that when the user tries to log in, it fails. Is it possible to do this or do I have to change the method?
This is my code:
private EditText emailRetrieve, firstPassword, passwordConfirm;
private Button resetPasswordBtn;
private String email, password, passwordToConfirm = "";
private FirebaseAuth mAuth;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_password);
uploadUI();
mAuth = FirebaseAuth.getInstance();
resetPasswordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setNewPassword();
}
});
}
// Validation email and password
private boolean validation() {
boolean valid = true;
email = emailRetrieve.getText().toString();
password = firstPassword.getText().toString();
passwordToConfirm = passwordConfirm.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
emailRetrieve.setError("Insert valid email address");
valid = false;
} else {
emailRetrieve.setError(null);
}
if (password.isEmpty() || password.length() < 8) {
firstPassword.setError("Insert valid password");
valid = false;
} else {
firstPassword.setError(null);
}
if(passwordToConfirm.isEmpty() || (!passwordToConfirm.equals(password))) {
passwordConfirm.setError("Passwords must be equals");
valid = false;
} else {
passwordConfirm.setError(null);
}
return valid;
}
private String getPasswordToConfirm(TextView textView) {
String confirm = textView.getText().toString();
return confirm;
}
private void setNewPassword() {
if(!validation())
return;
Utils.loadProgressDialog(SetPasswordActivity.this, "Uploading...");
//progressBar.setVisibility(View.VISIBLE);
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference().child("users");
myRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.getValue() != null) {
for(DataSnapshot datasnap : snapshot.getChildren()) {
if(datasnap.child("email").getValue().toString().equals(email)) {
datasnap.child("password").getRef().setValue(getPasswordToConfirm(passwordConfirm))
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
Toast.makeText(SetPasswordActivity.this, "Password successfully changed",
Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
#Override
public void uploadUI() {
emailRetrieve = findViewById(R.id.email_retrieve);
firstPassword = findViewById(R.id.first_password);
passwordConfirm = findViewById(R.id.password_confirm);
resetPasswordBtn = findViewById(R.id.reset_password_btn);
}
Thanks in advance to everyone!
I guess, you are navigating user to LoginActivity before the password is changed, Firebasedatabase call is asynchronous and you have to take user to LoginActivity only on Success, that is when you are showing toast to user. Basically move startActivity in setNewpassword to onSuccess of firebase query
private void setNewPassword() {
if(!validation())
return;
Utils.loadProgressDialog(SetPasswordActivity.this, "Uploading...");
FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference().child("users");
myRef.orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.getValue() != null) {
for(DataSnapshot datasnap : snapshot.getChildren()) {
if(datasnap.child("email").getValue().toString().equals(email)) {
datasnap.child("password").getRef().setValue(getPasswordToConfirm(passwordConfirm))
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
Toast.makeText(SetPasswordActivity.this, "Password successfully changed",
Toast.LENGTH_SHORT).show();
}
});
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
}

Sign up /Sign in with Email/password or Phone Fire base android

I am currently using Email/Password in sign in and sign up .
I want to add Phone number in sign up (with vérification of otp )
and will be sign in with (Email or Phone (EditText)+ password (EditText)).
the problem is if i can do it ? or not ?
if i can there is my code what will i add
This activity of Sign in :
private TextInputLayout mEmail,mPass;
private Button mLogin,mCallRegister ;
private ProgressDialog mProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener fbAutLis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_login);
//progress bar
mProgress =new ProgressDialog(this);
String titleId="Signing in...";
mProgress.setTitle(titleId);
mProgress.setMessage("Please Wait...");
mAuth= FirebaseAuth.getInstance();
fbAutLis= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
mProgress.dismiss();
Intent inte =new Intent(ClientLoginAct.this,ClientMapAct.class);
startActivity(inte);
finish();
return ;
}
}
};
mEmail =(TextInputLayout)findViewById(R.id.email);
mPass =(TextInputLayout)findViewById(R.id.pass);
mLogin =(Button)findViewById(R.id.login);
mCallRegister =(Button) findViewById(R.id.callRegister);
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if( !validateEmail()|!validatePassword()){
return;
}
mProgress.show();
final String email=mEmail.getEditText().getText().toString();
final String password=mPass.getEditText().getText().toString();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(ClientLoginAct.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
mProgress.dismiss();
Snackbar.make(v, "Email or Password incorrect", Snackbar.LENGTH_LONG).show();
//Toast.makeText(ClientLoginAct.this,"Email or Password incorrect ",Toast.LENGTH_SHORT).show();
}
}
});
}
});
mCallRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ClientLoginAct.this,ClientRegAct.class);
startActivity(intent);
}
});
}
private Boolean validateEmail() {
String val = mEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
mEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
mEmail.setError("Invalid email address");
return false;
} else {
mEmail.setError(null);
mEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = mPass.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
//"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=.*[a-zA-Z0-9])" + //any letter
"(?=\\S+$)" + //no white spaces
".{6,}" + //at least 6 characters
"$";
if (val.isEmpty()) {
mPass.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
mPass.setError("Password is too weak(at least 6 characters & no white spaces)");
return false;
} else {
mPass.setError(null);
mPass.setErrorEnabled(false);
return true;
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(fbAutLis);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(fbAutLis);
}
}
This is activity of Sign up :
private TextInputLayout mEmail,mPass;
private Button mRegister,mCallLogin;
private ProgressDialog mProgress;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener fbAutLis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_reg);
//progress bar
mProgress =new ProgressDialog(this);
String titleId="Signing up...";
mProgress.setTitle(titleId);
mProgress.setMessage("Please Wait...");
mAuth= FirebaseAuth.getInstance();
fbAutLis= new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser();
if (user != null){
mProgress.dismiss();
Intent inte =new Intent(ClientRegAct.this,ClientMapAct.class);
startActivity(inte);
finish();
return ;
}
}
};
mEmail =(TextInputLayout)findViewById(R.id.email);
mPass =(TextInputLayout)findViewById(R.id.pass);
// mPhone =(TextInputLayout)findViewById(R.id.phone);
mRegister =(Button)findViewById(R.id.register);
mCallLogin =(Button) findViewById(R.id.callLogin);
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
if( !validateEmail()|!validatePassword()){
return;
}
mProgress.show();
final String email=mEmail.getEditText().getText().toString();
final String password=mPass.getEditText().getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(ClientRegAct.this,new OnCompleteListener<AuthResult>(){
#Override
public void onComplete(#NonNull Task<AuthResult> task){
if (!task.isSuccessful()){
mProgress.dismiss();
Snackbar.make(v, "This email is already exist", Snackbar.LENGTH_LONG).show();
//Toast.makeText(ClientRegAct.this,"This email is already exist",Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child("Clients").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
mCallLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
private Boolean validateEmail() {
String val = mEmail.getEditText().getText().toString();
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if (val.isEmpty()) {
mEmail.setError("Field cannot be empty");
return false;
} else if (!val.matches(emailPattern)) {
mEmail.setError("Invalid email address");
return false;
} else {
mEmail.setError(null);
mEmail.setErrorEnabled(false);
return true;
}
}
private Boolean validatePassword() {
String val = mPass.getEditText().getText().toString();
String passwordVal = "^" +
//"(?=.*[0-9])" + //at least 1 digit
//"(?=.*[a-z])" + //at least 1 lower case letter
//"(?=.*[A-Z])" + //at least 1 upper case letter
//"(?=.*[##$%^&+=])" + //at least 1 special character
"(?=.*[a-zA-Z0-9])" + //any letter
"(?=\\S+$)" + //no white spaces
".{6,}" + //at least 6 characters
"$";
if (val.isEmpty()) {
mPass.setError("Field cannot be empty");
return false;
} else if (!val.matches(passwordVal)) {
mPass.setError("Password is too weak(at least 6 characters & no white spaces)");
return false;
} else {
mPass.setError(null);
mPass.setErrorEnabled(false);
return true;
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(fbAutLis);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(fbAutLis);
}
}
This code of activity Vérify_Otp but i dont know how to link with other activity :
String verificationCodeBySystem;
private Button mVerify;
private EditText mCode;
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_otp_verify);
mVerify = findViewById(R.id.verify_btn);
mCode = findViewById(R.id.verification_code_entered_by_user);
mProgressBar = findViewById(R.id.progress_bar);
String phoneNo = getIntent().getStringExtra("phoneNo");
sendVerificationCodeToUser(phoneNo);
mVerify.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = mCode.getText().toString();
if (code.isEmpty() || code.length() < 6) {
mCode.setError("Wrong OTP...");
mCode.requestFocus();
return;
}
mProgressBar.setVisibility(View.VISIBLE);
verifycode(code);
}
});
}
private void sendVerificationCodeToUser(String phoneNo) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
"+213" + phoneNo, // Phone number to verify
60, // Timeout duration
TimeUnit.SECONDS, // Unit of timeout
TaskExecutors.MAIN_THREAD, // Activity (for callback binding)
mCallbacks); // OnVerificationStateChangedCallbacks
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onCodeSent(#NonNull String s, #NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
verificationCodeBySystem = s ;
}
#Override
public void onVerificationCompleted(#NonNull PhoneAuthCredential phoneAuthCredential) {
String code = phoneAuthCredential.getSmsCode();
if(code!=null){
mProgressBar.setVisibility(View.VISIBLE);
verifycode(code);
}
}
#Override
public void onVerificationFailed(#NonNull FirebaseException e) {
Toast.makeText(OtpVerify.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
};
private void verifycode (String codeByUser){
PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCodeBySystem,codeByUser);
signInTheUserByCredentials(credential);
}
private void signInTheUserByCredentials(PhoneAuthCredential credential){
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
firebaseAuth.signInWithCredential(credential).addOnCompleteListener(OtpVerify.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(OtpVerify.this, "Your Account has been created successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(OtpVerify.this,ClientMapAct.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK );
startActivity(intent);
}else{
Toast.makeText(OtpVerify.this,task.getException().getMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
So please what i change to got what i ask in first lines ...

'java.lang.String com.google.firebase.auth.FirebaseUser.getEmail()' on a null object reference

So the app crashes when the user presses the sign-in button and only if the details he wrote down in the edit texts are correct by the firebaseAuth. reopening the app will make the app behave as nothing happened and the user will be signed in.
Here's the code:
public class LoginActivity extends Activity {
private Button btnRegister, btnSignIn, btnForgot;
private EditText etPhone, etPassword;
private ProgressBar mprogressBar;
private FirebaseAuth fbAuth;
private FirebaseUser fbUser;
private FirebaseFirestore db;
private DocumentReference uDocRef;
private CollectionReference uColctRef;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnRegister = findViewById(R.id.btnRegister);
btnSignIn = findViewById(R.id.btnSignIn);
btnForgot = findViewById(R.id.btnForgot);
etPhone = findViewById(R.id.etPhone);
etPassword = findViewById(R.id.etPassword);
mprogressBar = findViewById(R.id.mprogressBar);
fbAuth = FirebaseAuth.getInstance();
fbUser = fbAuth.getCurrentUser();
initFirebase();
}
private void initFirebase() {
db = FirebaseFirestore.getInstance();
uColctRef = db.collection(UserFirebase.UsersCollection);
if (fbUser != null)
{
Toast.makeText(this, "User already logged in: " + fbUser.getEmail(), Toast.LENGTH_LONG).show();
refreshListAndSubscribe();
Intent zone = new Intent(this, ZoneActivity.class);
startActivity(zone);
}
}
private void refreshListAndSubscribe() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checklist(result);
}
});
}
private void checklist(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (etPhone.getText().toString().trim().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
if (fbUser != null)
{
if (fbUser.getEmail().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}
}
public void onSign(View v)
{
if (isEmpty())
return;
inProgress(true);
fbAuth.signInWithEmailAndPassword(etPhone.getText().toString().trim(), etPassword.getText().toString())
.addOnSuccessListener(new OnSuccessLstnr("User Signed In", true))
.addOnFailureListener(new OnFailLstnr("Sign-in failed!"));
}
public void setPassword(View v)
{
Intent pass = new Intent(this, PasswordActivity.class);
startActivity(pass);
}
public void onRegister(View v)
{
Intent auth = new Intent (this, RegisterActivity.class);
startActivity(auth);
}
private void inProgress(boolean inProgress)
{
if (inProgress)
{
mprogressBar.setVisibility(View.VISIBLE);
btnSignIn.setEnabled(false);
btnRegister.setEnabled(false);
btnForgot.setEnabled(false);
}
else
{
mprogressBar.setVisibility(View.INVISIBLE);
btnSignIn.setEnabled(true);
btnRegister.setEnabled(true);
btnForgot.setEnabled(true);
}
}
private boolean isEmpty()
{
if (TextUtils.isEmpty(etPhone.getText().toString()))
{
etPhone.setError("REQUIRED!");
return true;
}
if (TextUtils.isEmpty(etPassword.getText().toString()))
{
etPassword.setError("REQUIRED!");
return true;
}
return false;
}
private class OnFailLstnr implements OnFailureListener
{
String msg;
public OnFailLstnr(String _msg)
{
this.msg = _msg;
}
#Override
public void onFailure(#NonNull Exception e)
{
inProgress(false);
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
public class OnSuccessLstnr implements OnSuccessListener<AuthResult>
{
String msg;
boolean open;
OnSuccessLstnr(String _msg, boolean _open)
{
this.msg = _msg;
this.open = _open;
}
#Override
public void onSuccess(AuthResult authResult)
{
Toast.makeText(LoginActivity.this, msg, Toast.LENGTH_LONG).show();
inProgress(false);
if (open)
{
refreshListAndSubscribe();
Intent in = new Intent(LoginActivity.this, ZoneActivity.class);
startActivity(in);
finish();
}
}
}
The Logcat:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getEmail()' on a null object reference
at com.a.shon.scoutszone2.Activities.LoginActivity.checklist(LoginActivity.java:127)
at com.a.shon.scoutszone2.Activities.LoginActivity.access$000(LoginActivity.java:42)
at com.a.shon.scoutszone2.Activities.LoginActivity$1.onEvent(LoginActivity.java:101)
at com.a.shon.scoutszone2.Activities.LoginActivity$1.onEvent(LoginActivity.java:91)
I've Tried fixing it using answers to some similliar questions that were already posted in the site, but it didn't really change or fix the problem.
I would like to get help with solving this issue out and every help would be appreciated by A LOT!
Thanks in advance!
Found a solution, Seems like dealing with Already authenticated users (Users who already logged in, just reopening the app) and users who are just logged out from the app in one method (Check the - private void checklist(QuerySnapshot result), to understand what I'm talking about) is quite a messy way to deal with it, and making it really buggy.
The solution:
In InitFirebase() change the calling of refreshListAndSubscribe(); to a different new method, i called it refreshExistingUser(), its the same code as refreshListAndSubscribe()
the only part which is different between the two is the calling for the second method at the end of them.
Ill Add here a part of the code to make it simpler to understand:
private void initFirebase() {
db = FirebaseFirestore.getInstance();
uColctRef = db.collection(UserFirebase.UsersCollection);
if (fbUser != null)
{
Toast.makeText(this, "User already logged in: " + fbUser.getEmail(), Toast.LENGTH_LONG).show();
refreshExistingUser();
Intent zone = new Intent(this, ZoneActivity.class);
startActivity(zone);
}
}
private void refreshListAndSubscribe() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checklist(result);
}
});
}
private void checklist(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (etPhone.getText().toString().trim().equals(email))
{
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}
private void refreshExistingUser() {
uColctRef
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot result,
#Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.e("FirebaseDemo-Query", "Listen failed", e);
e.printStackTrace();
return;
}
Log.i("FirebaseDemo-Query", "Listen succeded");
checkuser(result);
}
});
}
private void checkuser(QuerySnapshot result) {
String email;
boolean isApproved;
sharedPreferences = getSharedPreferences("SaveData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
for (QueryDocumentSnapshot document : result) {
email = document.get(UserFirebase.email).toString();
if (fbUser.getEmail().equals(email)) { //When the user isnt == null (Reopening the app and such)
String branchCode = String.valueOf(document.get(UserFirebase.branchCode));
String role = document.get(UserFirebase.roleType).toString();
isApproved = Boolean.parseBoolean(document.get(UserFirebase.isApproved).toString());
editor.putString("myBranch", branchCode);
editor.putString("myRole", role);
editor.putString("myEmail", email);
editor.putBoolean("isApproved", isApproved);
editor.apply();
}
}
}

Registration Page does not record user data with Firebase

public class RegisterActivity extends AppCompatActivity {
//create variables
private EditText mUsername, mPassword, mEmail, mPhone;
private Button mRegister;
private TextView mLogin;
private FirebaseAuth mAuth;
private ImageView mProfilePicture;
String user_email, user_name, user_phone, user_password;
//on creation of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupViews();
//firebase instance declared
mAuth = FirebaseAuth.getInstance();
//When register is clicked
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if all fields are okay using validation method
if(validate()){
//get user info
String user_email = mEmail.getText().toString().trim();
String user_password = mPassword.getText().toString().trim();
String user_phone = mPhone.getText().toString().trim();
String user_name = mUsername.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
sendEmailVerification();
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//Return user back to login page
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
});
}
//setup views by id from xml
private void setupViews(){
mUsername = (EditText)findViewById(R.id.editTextNewUsername);
mPassword = (EditText)findViewById(R.id.editTextNewPassword);
mEmail = (EditText)findViewById(R.id.editTextNewEmail);
mPhone = (EditText)findViewById(R.id.editTextPhone);
mRegister = (Button)findViewById(R.id.buttonRegister);
mLogin = (TextView)findViewById(R.id.textViewLogin);
mProfilePicture = (ImageView)findViewById(R.id.imageViewProfilePicture);
}
//validate if all fields are okay and not empty
private Boolean validate() {
Boolean result = false;
//convert inputs to strings
String user_name = mUsername.getText().toString();
String user_password = mPassword.getText().toString();
String user_email = mEmail.getText().toString();
String user_phone = mPhone.getText().toString();
//check if any fields are empty, if not then return result
if (user_name.isEmpty() || user_password.isEmpty() || user_email.isEmpty() || user_phone.isEmpty()) {
Toast.makeText(this, "All fields are required for registration.", Toast.LENGTH_SHORT).show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = mAuth.getCurrentUser();
if(firebaseUser!=null){
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegisterActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
mAuth.signOut();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(mAuth.getCurrentUser().getUid());
UserProfile userProfile = new UserProfile(user_phone, user_email, user_name);
myRef.setValue(userProfile);
}
}
Solved the crash with my profile page and got it to save artifical data, but found out my registration page is the problem and is not recording data. Here is my Userprofile.java for reference
public class UserProfile {
public String user_phone;
public String user_email;
public String user_name;
public UserProfile() {
}
public UserProfile(String user_phone, String user_email, String user_name) {
this.user_phone = user_phone;
this.user_email = user_email;
this.user_name = user_name;
}
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
Any help would be appreciated, i'd read extensively on the topic and can't seem to see whatever small issue is causing the hold-up. Any other pointers are also welcome.
Try changing:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
assert userProfile != null;
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
With:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
if(userProfile != null){
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
}

Populating a sub-group in firebase Database

I have an activity where i want to send a custom message to a sub-group in my database when a button is clicked. I tried to check for a user_id and send the message to those user id's, My problem is that when i click the button(status) it only sends that message to one person.
This is my Activity:
public class messageActivity extends AppCompatActivity {
private Button status;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private String user_id;
private String message;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
gettingIntent();
status = (Button)findViewById(R.id.rescue);
status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
addUpdateMessage();
addTeamUpdateChat();
Toast.makeText(getApplicationContext(), "Team Update message was successfully sent",Toast.LENGTH_LONG).show();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Status");
toolbar.setTitleTextColor(android.graphics.Color.WHITE);
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void checkUser() {
if (mCurrentUserId == null) {
sendToStart();
}else{
Toast.makeText(getApplicationContext(), "Logged in",Toast.LENGTH_SHORT).show();
}
}
private void gettingIntent() {
Intent intent =getIntent();
user_id = intent.getStringExtra("user_id");
}
private void addTeamUpdateChat() {
String current_user_ref="Team_Updates/"+mCurrentUserId+"/"+user_id;
String reciever_user_ref= "Team_Updates/"+user_id+"/"+mCurrentUserId;
DatabaseReference team_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(user_id).push();
String push_key = team_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName + " Is now a new Member of the team.");
messageMap.put("type","text");
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(reciever_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addUpdateMessage() {
mRootRef.child("Team_Updates_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Team_Updates_Chat/"+mCurrentUserId+"/"+user_id, chatAddMap);
chatUserMap.put("Team_Updates_Chat/"+user_id+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else{
mCurrentUserId = mAuth.getCurrentUser().getUid();
}
}
#Override
protected void onStop() {
super.onStop();
}
private void sendToStart() {
Intent startIntent = new Intent(messageActivity.this, Home.class);
startActivity(startIntent);
finish();
}
}
I'm Still learning Programming in Android Studio, Is there Any suggestions on how i should approach this?
You are sending a message only to single user because you are getting only a single user. To send a message to multiple users, you need to loop to get all those users and then send the message to all of them.

Categories

Resources