I would like to implement a system where when they sign up they provide their username,phone number and a password along with some other data and it all gets saved to the database. So that the user can then signin with their username/phone and password
I am checking if username and password entered is equal to the username and password in the firebase database but it runs the else part even the if part is true, help me to sort out the issue tried with finish() and break statement too.
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
ImageView logo;
public EditText loginPhone, logInpasswd;
//Button btnLogIn;
TextView signup,phonetext,btnLogIn;
DatabaseReference dbview;
SessionManager sessionManager;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
//SessionManager session = new SessionManager(MainActivity.this);
dbview=FirebaseDatabase.getInstance().getReference("Users");
logo = (ImageView) findViewById(R.id.imageView);
logo.animate().rotation(360).start();
loginPhone = findViewById(R.id.loginPhone);
logInpasswd = findViewById(R.id.loginpaswd);
btnLogIn = findViewById(R.id.btnLogIn);
signup = findViewById(R.id.SignIn);
logo.setImageResource(R.drawable.mgenomics);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this, register.class);
startActivity(in);
}
});
btnLogIn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
verifyUser();
}
});
}
public void verifyUser(){
sessionManager = new SessionManager(MainActivity.this);
dbview.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for(DataSnapshot data:snapshot.getChildren()) {
User user = data.getValue(User.class);
String Phone = loginPhone.getText().toString().trim();
String Passwd = logInpasswd.getText().toString().trim();
String uphone = user.getuPhone();
String upass = user.getuPass();
String uname = user.getuUname();
String uid = user.getuID();
//Bundle data_pass = new Bundle();
// data_pass.putString("name",uname);
if(uname!=null && (uname.equals(Phone) || uphone.equals(Phone)) && upass.equals(Passwd)){
Intent i = new Intent(MainActivity.this,logged_user.class);
sessionManager.saveSession(uname);
sessionManager.loginUser(uname,true);
startActivity(i);
finish();
break;
}
else
{
logInpasswd.setError("Invalid Username/Password");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.i(TAG, "onCancelled: Error: " + error.getMessage());
}
});
}
}
In if statement if(uname!=null && (uname.equals(Phone) || uphone.equals(Phone)) && upass.equals(Passwd)) this will only works if only username not equal to null it means if you enter uphone number as you described username could be username/phone number this wont work. If we use && operator if the first condition fails it won't check for the rest of the conditions simple it will goto else condition. Please check your values for username.
Rewritten if statement based on your explanation:
if(((uname!=null && uname.equals(Phone)) || ( uphone !=null|| uphone.equals(Phone))) && upass.equals(Passwd))
Related
I am creating a sign up page and in previous activity I ask user to select if they are an existing or new user. I have written code for new user (i.e. registration), but when I click on new user activity (intent), a white screen pops up and it again gets back to select type of user.
Here's the code for new user registration:
package com.example.houserentappproject;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class activity_registration_user extends AppCompatActivity {
EditText userFullName , userEmail , userPassword , userContact ;
Button btn_register ;
FirebaseDatabase firebaseDatabase ;
DatabaseReference databaseReference ;
userInfo userInfo ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registration_user);
userFullName = findViewById(R.id.id_fullname_newuser);
userEmail = findViewById(R.id.id_email_newuser);
userPassword = findViewById(R.id.id_password_newuser);
userContact = findViewById(R.id.id_mobileno_newuser);
btn_register = findViewById(R.id.btn_regitser);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("userInfo");
userInfo = new userInfo();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = userFullName.getText().toString();
String email = userEmail.getText().toString();
String password = userPassword.getText().toString();
String mobileNo = userContact.getText().toString();
if(TextUtils.isEmpty(name) && TextUtils.isEmpty(email) && TextUtils.isEmpty(password) && TextUtils.isEmpty(mobileNo)) {
Toast.makeText(activity_registration_user.this, "Please Add some data", Toast.LENGTH_SHORT).show();
}
else {
addUserInfoToFirebase(name, email , password , mobileNo);
}
Intent intent = new Intent(getApplicationContext() , activity_successful_google_signin.class);
startActivity(intent);
finish();
}
private void addUserInfoToFirebase(String name, String email, String password, String mobileNo) {
userInfo.setUserFullName(name);
userInfo.setUserEmail(email);
userInfo.setUserPassword(password);
userInfo.setUserContact(mobileNo);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
databaseReference.setValue(userInfo);
Toast.makeText(activity_registration_user.this, "Successfully Registered", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(activity_registration_user.this, "Registration Failed" + databaseError, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
Here is my class code, my problem is that I do not know where to place edtChair in order to push its data under the parent table?
I tried adding edtChair in this line of code ( Table table = new Table(edtPassword.getText().toString) by placing it beside edtpassword and adding comma.Still does not work at all. How should I construct the code?
import android.app.ProgressDialog;
import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.example.alber.tbmcmapp.Model.Chairs;
import com.example.alber.tbmcmapp.Model.Table;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.rengwuxian.materialedittext.MaterialEditText;
public class SignUp extends AppCompatActivity {
MaterialEditText edtTable, edtPassword,edtChair;
Button btnSignUp;
//DatabaseReference cDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
edtTable = (MaterialEditText)findViewById(R.id.edtTable);
edtChair = (MaterialEditText)findViewById(R.id.edtChair);
edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);
btnSignUp = (Button)findViewById(R.id.btnSignUp);
//Firebase
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference table_user = database.getReference("Table");
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ProgressDialog mDialog = new ProgressDialog(SignUp.this);
mDialog.setMessage("Please wait...");
mDialog.show();
table_user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Check if already exist
if(dataSnapshot.child(edtTable.getText().toString()).exists())
{
mDialog.dismiss();
Toast.makeText(SignUp.this, "Table already registered", Toast.LENGTH_SHORT).show();
}
else
{
mDialog.dismiss();
Table table = new Table(edtPassword.getText().toString());
table_user.child(edtTable.getText().toString()).setValue(table);
Toast.makeText(SignUp.this, " Table Created ", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
}
}
I made a simple app with a LoginActivity. It is crashing and throwing an IllegalArgumentException if the EditText(s) are empty. I use Firebase Authentication. I tried by using assert but still it did not work.
Dummy credentials to reproduce the issue:
Email: abc#abc.com
Password: 123456
StartActivity.java
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import android.content.Intent;
import android.app.Activity;
import android.content.SharedPreferences;
import java.util.Objects;
public class StartActivity extends AppCompatActivity {
private static final String TAG = "EmailPassword";
private FirebaseAuth mAuth;
private LinearLayout linear1;
private TextInputLayout textinputlayout1;
private TextInputLayout textinputlayout2;
private TextInputEditText edittext1;
private TextInputEditText edittext2;
private Button button1;
private TextView textview1;
private Intent i =new Intent();
private SharedPreferences user;
private ProgressDialog prog;
private OnCompleteListener<AuthResult> _mAuth_sign_in_listener;
private void reload(){}
private void updateUI(FirebaseUser user){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
setContentView(R.layout.activity_start);
LinearLayout _nav_view = (LinearLayout) findViewById(R.id._nav_view);
TextInputLayout textinputlayout1 = findViewById(R.id.textinputlayout1);
TextInputLayout textinputlayout2 = findViewById(R.id.textinputlayout2);
edittext1 = findViewById(R.id.edittext1);
edittext2 = findViewById(R.id.edittext2);
Button button1 = findViewById(R.id.button1);
TextView textview1 = findViewById(R.id.textview1);
SharedPreferences user = getSharedPreferences("user", Activity.MODE_PRIVATE);
Intent i= new Intent();
textview1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
i.setClass(getApplicationContext(), ForgotPassword.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
i.setClass(getApplicationContext(), MainActivity.class);
startActivity(i);
}
}
private void signIn(){
Toast.makeText(StartActivity.this,"Button clicked",Toast.LENGTH_SHORT).show();
String email=Objects.requireNonNull(edittext1.getText()).toString();
String password= Objects.requireNonNull(edittext2.getText()).toString();
if(edittext1!=null && edittext2!=null){
final ProgressDialog prog= new ProgressDialog(StartActivity.this);prog.setMax(100);prog.setMessage("Logging in...");prog.setIndeterminate(true);prog.setCancelable(true);
prog.show();
mAuth.signInWithEmailAndPassword(email,password).addOnCompleteListener(StartActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
final boolean success= task.isSuccessful();
if(success){
i.setClass(getApplicationContext(),MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
prog.cancel();
}
else{
final String error=task.getException()!=null?task.getException().getMessage():"";
prog.cancel();
Toast.makeText(StartActivity.this,""+error,Toast.LENGTH_LONG).show();
}
}
});
}
else {
prog.cancel();
Toast.makeText(getApplicationContext(),"Email/Password cannot be empty!", Toast.LENGTH_SHORT).show();
}
}
public void onClick(View view) {
}
}
MainActivity.java
package com.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toolbar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private Toolbar toolbar1;
private Button button2;
private LinearLayout linear2;
private Intent i=new Intent();
private FirebaseUser user;
private TextView textview5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user= mAuth.getCurrentUser();
setContentView(R.layout.activity_main);
Toolbar toolbar1=findViewById(R.id.toolbar1);
LinearLayout linear2=findViewById(R.id.linear2);
textview5=findViewById(R.id.textview5);
Button button2=findViewById(R.id.button2);
assert user != null;
textview5.setText(user.getEmail());
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
i.setClass(getApplicationContext(),StartActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
});
toolbar1.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
}
Screenshot of the crash
You are getting IllegalArgumentException because you let the user sign in with empty credentials. This is happening because you checking against nullity the EditText objects and not the actual values:
if(edittext1!=null && edittext2!=null) { ... }
Which is not correct. You should check if the values that are inserted by the user are different than the empty String. The following if statement should do the trick:
if(!email.isEmpty() && !password.isEmpty()) { ... }
It would be also better if you display a message to the user when the email or the password is empty.
Don't know why I am getting this error can anyone tell me that how to fix it.
this is login activity in java connected with firebase auth I am stuck in this before 3 days and still.
I pasted my code and also uploded my screen shot where you can see all the error.
Error where I always get on TAG and updateUI there two words always get error.
Download screen short of error message and code with error:
package com.eassycars.www.licencespot;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class Activity_Login extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private Button singups,forgotpass,logins;
RelativeLayout really1, really2;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
really1.setVisibility(View.VISIBLE);
really2.setVisibility(View.VISIBLE);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(Activity_Login.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity__login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
singups = (Button) findViewById(R.id.singup);
logins = (Button) findViewById(R.id.logins);
forgotpass = (Button) findViewById(R.id.forgotpass);
singups.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity_Login.this, singup.class));
}
});
forgotpass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity_Login.this, ForgotPassword.class));
}
});
really1 = (RelativeLayout) findViewById(R.id.rellayl);
really2 = (RelativeLayout) findViewById(R.id.really2);
handler.postDelayed(runnable, 2000);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
logins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(Activity_Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
});
}
}
Can anyone help fix this error because I am beginner and I don't have much knowledge so I am trying to get it.
You are getting the error because you are missing TAG and UpdateUI method in the class :
Please add the following private static final String TAG = Activity_Login.class.getName(); as mentioned in the comment
Also, use the following method as you are using Firebase Auth
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null) {
mStatusTextView.setText(getString(R.string.google_status_fmt, user.getEmail()));
mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
findViewById(R.id.sign_in_button).setVisibility(View.GONE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
mStatusTextView.setText(R.string.signed_out);
mDetailTextView.setText(null);
findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
After this you are good to go
You have to add TAG variable and updateUI method:
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class Activity_Login extends AppCompatActivity {
private static final String TAG = "Activity_Login";
private EditText inputEmail, inputPassword;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private Button singups,forgotpass,logins;
RelativeLayout really1, really2;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
really1.setVisibility(View.VISIBLE);
really2.setVisibility(View.VISIBLE);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
startActivity(new Intent(Activity_Login.this, MainActivity.class));
finish();
}
// set the view now
setContentView(R.layout.activity__login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
singups = (Button) findViewById(R.id.singup);
logins = (Button) findViewById(R.id.logins);
forgotpass = (Button) findViewById(R.id.forgotpass);
singups.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity_Login.this, singup.class));
}
});
forgotpass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Activity_Login.this, ForgotPassword.class));
}
});
really1 = (RelativeLayout) findViewById(R.id.rellayl);
really2 = (RelativeLayout) findViewById(R.id.really2);
handler.postDelayed(runnable, 2000);
//Get Firebase auth instance
mAuth = FirebaseAuth.getInstance();
logins.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "createUserWithEmail:failure", task.getException());
Toast.makeText(Activity_Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
updateUI(null);
}
}
});
}
});
}
private void updateUI(FirebaseUser user) {
//implement your logic here
}
}
Image of DB in firebase console
I don't really know what's wrong here, I am able to add data on the other activity. I am getting error "java.lang.NullPointerException: Can't pass null for argument 'pathString' in child()" and don't know how to fix. There are 3 other classes created only one other is adding data to firebase realtime database storage.
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Profile extends AppCompatActivity {
EditText fName, lName, PhNo, BDay, Zip;
Button svBtn;
DatabaseReference mDataReference;
String keyUser;
String fNameStr, lNameStr, PhNoStr, BDayStr, ZipStr;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
keyUser = getIntent().getStringExtra("USER_KEY");
mDataReference = FirebaseDatabase.getInstance().getReference().child("Users").child(keyUser);//error in this line
fName = (EditText) findViewById(R.id.fName);
lName = (EditText) findViewById(R.id.lName);
PhNo = (EditText) findViewById(R.id.phno);
BDay = (EditText) findViewById(R.id.bday);
Zip = (EditText) findViewById(R.id.zip);
svBtn = (Button) findViewById(R.id.svBtn);
svBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fNameStr = fName.getText().toString();
lNameStr = lName.getText().toString();
PhNoStr = PhNo.getText().toString();
BDayStr = BDay.getText().toString();
ZipStr = Zip.getText().toString();
if(!TextUtils.isEmpty(fNameStr) && !TextUtils.isEmpty(lNameStr) && !TextUtils.isEmpty(PhNoStr)) {
DatabaseReference mDataRef = mDataReference.child("Users").push();
mDataRef.child("firstName").setValue(""+fNameStr);
mDataRef.child("lastName").setValue(""+lNameStr);
mDataRef.child("phoneNumber").setValue(""+PhNoStr);
mDataRef.child("isVerified").setValue("verified");
if(!TextUtils.isEmpty(BDayStr)){
mDataRef.child("birthday").setValue(""+BDayStr);
}else{
mDataRef.child("birthday").setValue("null");
}
if(!TextUtils.isEmpty(ZipStr)){
mDataRef.child("zipcode").setValue("ZipStr");
}else{
mDataRef.child("zipcode").setValue("null");
}
Toast.makeText(Profile.this, "User profile added", Toast.LENGTH_LONG).show();
startActivity(new Intent(Profile.this, welcome.class));
}else{
Toast.makeText(Profile.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.akshay.katiroll.R;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class katiRoll extends AppCompatActivity {
EditText userEdit;
EditText passEdit;
String sUser, sPass;
Button sign;
Button reg;
Boolean signInVLogIn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kati_roll);
float Re = 255;
float Gr = 148;
float Bl = 0;
userEdit = (EditText)findViewById(R.id.user);
passEdit = (EditText)findViewById(R.id.pass);
sign = (Button) findViewById(R.id.sign);
reg = (Button) findViewById(R.id.reg);
userEdit.setTextColor(Color.rgb(Re,Gr,Bl));
passEdit.setTextColor(Color.rgb(Re,Gr,Bl));
sign.setTextColor(Color.rgb(Re,Gr,Bl));
reg.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference().child("Users");
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass)){
signInVLogIn = true;
}else{
signInVLogIn = false;
}
if(user != null && signInVLogIn) {
}else{
//Toast.makeText(katiRoll.this, "Log In Failed", Toast.LENGTH_LONG).show();
}
}
};
sign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sUser = userEdit.getText().toString().trim();
sPass = passEdit.getText().toString().trim();
if(!TextUtils.isEmpty(sUser) && !TextUtils.isEmpty(sPass))
{
mAuth.signInWithEmailAndPassword(sUser, sPass).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkUserValidation(dataSnapshot, sUser);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
Toast.makeText(katiRoll.this, "User Login Doesn't Exist" , Toast.LENGTH_LONG).show();
}
}
});
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(katiRoll.this, signUp.class));
}
});
}
private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(katiRoll.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(katiRoll.this, welcome.class));
}
}
}
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.FirstScreen;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.akshay.katiroll.SecondScreen.welcome;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.akshay.katiroll.R;
import com.google.firebase.database.ValueEventListener;
import java.util.Iterator;
public class signUp extends AppCompatActivity {
EditText nUser, nPass;
Button registerBtn, backToMain;
ImageButton passVis;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference mDatabaseRef, mUserCheckData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
nUser = (EditText) findViewById(R.id.nUser);
nPass = (EditText) findViewById(R.id.nPass);
registerBtn = (Button) findViewById(R.id.registerBtn);
backToMain = (Button) findViewById(R.id.backToMain);
passVis = (ImageButton)findViewById(R.id.passVis);
passVis.setImageResource(R.drawable.open);
passVis.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable drawable = passVis.getDrawable();
if(drawable.getConstantState().equals(getResources().getDrawable(R.drawable.open,null).getConstantState())){
passVis.setImageResource(R.drawable.closed);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}else{
passVis.setImageResource(R.drawable.open);
nPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD);
}
}
});
float Re = 255;
float Gr = 148;
float Bl = 0;
nUser.setTextColor(Color.rgb(Re, Gr, Bl));
nPass.setTextColor(Color.rgb(Re, Gr, Bl));
registerBtn.setTextColor(Color.rgb(Re, Gr, Bl));
backToMain.setTextColor(Color.rgb(Re, Gr, Bl));
mAuth = FirebaseAuth.getInstance();
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUserCheckData = FirebaseDatabase.getInstance().getReference().child("User");
mAuthListener = 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) {
checkForValidation(dataSnapshot, emailForVer);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
Log.d("TAG", "onAuthStateChanged:signed_out");
}
}
};
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String nUserString, nPassString;
nUserString = (nUser.getText().toString().trim());
nPassString = (nPass.getText().toString().trim());
if(nPassString.length()>=6){
if (!TextUtils.isEmpty(nUserString) && !TextUtils.isEmpty(nPassString)) {
mAuth.createUserWithEmailAndPassword(nUserString, nPassString).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(nUserString);
mChildDatabase.child("PasswordUser").setValue(nPassString);
Toast.makeText(signUp.this, "User Account Created, Check Email For Confirmation", Toast.LENGTH_LONG).show();
FirebaseUser user = mAuth.getCurrentUser();
if (user != null) {
user.sendEmailVerification();
}
startActivity(new Intent(signUp.this, Profile.class));
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(signUp.this, "Failed to create User Account", Toast.LENGTH_LONG).show();
}
}
});
backToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(signUp.this, katiRoll.class));
}
});
}
private void checkForValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot)iterator.next();
if (dataUser.child("emailUser").getValue().toString().equals(emailForVer)){
if(dataUser.child("isVerified").getValue().toString().equals("unverified"))
{
Intent in = new Intent(signUp.this, Profile.class);
in.putExtra("USER KEY", dataUser.child("userKey").getValue().toString());
startActivity(in);
Log.d("USERKEY",dataUser.child("userKey").getValue().toString());
}
else{
startActivity(new Intent(signUp.this, welcome.class));
}
}
}
}
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
package com.example.akshay.katiroll.SecondScreen;
import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.akshay.katiroll.FirstScreen.katiRoll;
import com.example.akshay.katiroll.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class welcome extends AppCompatActivity {
Button logOutBtn;
FirebaseAuth mAuth;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
float Re = 255;
float Gr = 148;
float Bl = 0;
logOutBtn = (Button)findViewById(R.id.logOutBtn);
logOutBtn.setTextColor(Color.rgb(Re,Gr,Bl));
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if(user !=null) {
}else{
}
}
};
logOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mAuth.signOut();
finish();
startActivity(new Intent(welcome.this, katiRoll.class));
}
});
}
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onStop() {
super.onStop();
mAuth.removeAuthStateListener(mAuthListener);
}
}
The problem that is telling to you is that you are doing wrong the reference, you are trying to get something inside Firebase Database that is not there
This line is telling you that the child("Users").child(KeyUser); does not exist in your current DB structure
To fix this you should see your databse structure and then redo your reference.
if you post a photo of your Firebase DB i will be glad to refactor your code to your needs.
also here you are getting wrong your USER_KEY
keyUser = getIntent().getStringExtra("USER_KEY");
To fix this a short way would be doing this
keyUser = getIntent().getExtras().getString("USER_KEY");
you are geting an intent from where? if you are trying to get a putExtra from another Activity, you are doing it wrong, post where you are seting the extra ("USER_KEY");
Intent.getStringExtra() and Intent.getExtras() returns null if there are no extras, so you need to check for that before trying to call getString()
one quick example to check for extras first would be this
String keyUser;
Bundle extras = getIntent().getExtras();
if(extras == null) {
Log.e("keyUser is null","");
} else {
keyUser= extras.getString("USER_KEY");
}
happy coding