Data getting inserted into firebase but app crashes in Android - java

Alright so let me explain it better, i have made an application which has three fields as name, email and address, i want to store it into realtime firebase database, i'm able to store it but the app crashes after button click. I don't know what causing the app crashing.! help appreciated Thanks..
I have made a java class for user here:
public class User {
public String name;
public String email;
public String address;
public User(String name, String email, String address) {
this.name = name;
this.email = email;
this.address = address;
}
}
my mainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Displaying toolbar icon
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.ic_launcher);
txtDetails = (TextView) findViewById(R.id.txt_user);
inputName = (EditText) findViewById(R.id.name);
inputEmail = (EditText) findViewById(R.id.email);
inputAddr = (EditText) findViewById(R.id.address);
btnSave = (Button) findViewById(R.id.btn_save);
mFirebaseInstance = FirebaseDatabase.getInstance();
// get reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
// store app title to 'app_title' node
mFirebaseInstance.getReference("app_title").setValue("Realtime Database");
// app_title change listener
mFirebaseInstance.getReference("app_title").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.e(TAG, "App title updated");
String appTitle = dataSnapshot.getValue(String.class);
// update toolbar title
getSupportActionBar().setTitle(appTitle);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read app title value.", error.toException());
}
});
// Save / update the user
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = inputName.getText().toString();
String email = inputEmail.getText().toString();
String address = inputAddr.getText().toString();
// Check for already existed userId
if (TextUtils.isEmpty(userId)) {
createUser(name, email,address);
} else {
updateUser(name, email,address);
}
}
});
toggleButton();
}
// Changing button text
private void toggleButton() {
if (TextUtils.isEmpty(userId)) {
btnSave.setText("Save");
} else {
btnSave.setText("Update");
}
}
/**
* Creating new user node under 'users'
*/
private void createUser(String name, String email, String address) {
// TODO
// In real apps this userId should be fetched
// by implementing firebase auth
if (TextUtils.isEmpty(userId)) {
userId = mFirebaseDatabase.push().getKey();
}
User user = new User(name, email, address);
mFirebaseDatabase.child(userId).setValue(user);
addUserChangeListener();
}
/**
* User data change listener
*/
private void addUserChangeListener() {
// User data change listener
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
// Check for null
if (user == null) {
Log.e(TAG, "User data is null!");
return;
}
Log.e(TAG, "User data is changed!" + user.name + ", " + user.email);
// Display newly updated name and email
txtDetails.setText(user.name + ", " + user.email);
// clear edit text
Toast.makeText(MainActivity.this, "Data Sent", Toast.LENGTH_SHORT).show();
inputEmail.setText("");
inputName.setText("");
inputAddr.setText("");
toggleButton();
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.e(TAG, "Failed to read user", error.toException());
}
});
}
private void updateUser(String name, String email, String address) {
// updating the user via child nodes
if (!TextUtils.isEmpty(name))
mFirebaseDatabase.child(userId).child("name").setValue(name);
if (!TextUtils.isEmpty(email))
mFirebaseDatabase.child(userId).child("email").setValue(email);
if (!TextUtils.isEmpty(address))
mFirebaseDatabase.child(userId).child("address").setValue(address);
}
}
my logcat:
com.google.firebase.database.DatabaseException: Class raj.realtime.db.User is missing a constructor with no arguments
at com.google.android.gms.internal.zzamy$zza.zze(Unknown Source)
at com.google.android.gms.internal.zzamy$zza.zzce(Unknown Source)
at com.google.android.gms.internal.zzamy.zze(Unknown Source)
at com.google.android.gms.internal.zzamy.zzb(Unknown Source)
at com.google.android.gms.internal.zzamy.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at raj.realtime.db.MainActivity$3.onDataChange(MainActivity.java:127)
at com.google.android.gms.internal.zzajp.zza(Unknown Source)
at com.google.android.gms.internal.zzakp.zzcxi(Unknown Source)
at com.google.android.gms.internal.zzaks$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Add a no argument constructor in User.java:
public class User {
public User(){}
public String name;
public String email;
public String address;
public User(String name, String email, String address) {
this.name = name;
this.email = email;
this.address = address;
}
}
For reference check the below:
setValue

You are just missing Default constructor.
public User() {
}
There is a reason to add a Default constructor in your modal class. Default constructor required for calls to DataSnapshot.getValue(User.class). Read How get value from dataSnapshot?

Related

How to read and display from realtime database [Firebase]?

I tried following various youtube videos for guides in order to display the current user information in user profile.However, I still failed on displaying those data. Those data are name, gmail and phone numbers.
My current java code on ProfileActivity
FirebaseUser user;
DatabaseReference reference;
String userID;
Button MainMenu,Logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
user = FirebaseAuth.getInstance().getCurrentUser();
reference = FirebaseDatabase.getInstance().getReference("users");
userID = user.getUid();
final TextView ViewName = (TextView) findViewById(R.id.Name);
final TextView ViewEmail = (TextView) findViewById(R.id.Email);
final TextView ViewPhonenumber = (TextView) findViewById(R.id.Phonenumber);
reference.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
users userProfile = snapshot.getValue(users.class);
if(userProfile != null){
String name = userProfile.Name;
String email = userProfile.Email;
String phonenumber = userProfile.Phonenumber;
ViewName.setText(name);
ViewEmail.setText(email);
ViewPhonenumber.setText(phonenumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(ProfileActivity.this,"Something wrong happened",Toast.LENGTH_LONG).show();
}
});
My current file for users.java
public String Name;
public String Email;
public String Phonenumber;
public users(){
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhonenumber() {
return Phonenumber;
}
public void setPhonenumber(String phonenumber) {
Phonenumber = phonenumber;
}
}
My realtime database in Firebase
UPDATED with Register.java class so you guys might get clear view on how my code looks like
EditText mFullName,mEmail,mPassword,mPhone;
Button mRegisterButton;
TextView mLoginButton;
FirebaseAuth fAuth;
ProgressBar progressBar;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference root = db.getReference().child("users");
users users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
mFullName = findViewById(R.id.Name);
mEmail = findViewById(R.id.Email);
mPassword = findViewById(R.id.Password);
mPhone = findViewById(R.id.Phonenumber);
mRegisterButton = findViewById(R.id.registerbutton);
mLoginButton = findViewById(R.id.loginpage);
fAuth = FirebaseAuth.getInstance();
progressBar = findViewById(R.id.progressBar);
if(fAuth.getCurrentUser() != null)
{
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
mRegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
String name = mFullName.getText().toString();
String number =mPhone.getText().toString();
HashMap<String , String> userMap = new HashMap<>();
userMap.put("name",name);
userMap.put("email",email);
userMap.put("phone",number);
if(TextUtils.isEmpty(email))
{
mEmail.setError("Email is required!");
return;
}
if(TextUtils.isEmpty(password))
{
mPassword.setError("Password is required!");
return;
}
if(password.length() < 6)
{
mPassword.setError(("Password must be longer than 6"));
return;
}
progressBar.setVisibility(View.VISIBLE);
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
root.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(userMap);
Toast.makeText(Register.this,"User Created",Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}else{
Toast.makeText(Register.this,"Error" + task.getException().getMessage(),Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
}
});```
You're getting no data from the database because the names of the properties inside the users class are different than the ones in the database. See Name (capital N) in the class vs. name (lower case letter n) in the database?
To solve this, you should simply change the class to look like this:
class users
private String name;
private String email;
private String phonenumber;
public users(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
}
Please also note that the fields now are set private instead of public. Besides that, to refer to the class members, you have to use this, which is an instance of the class.
P.S. Also remember that in your database you're using pushed IDs and not UIDs that are coming from the authentication operation.
Follow these steps
Change your User class fields to :
public String name;
public String email;
public String phone;
also rename getter and setters
Log error in onCancelled() if this does not work

Firebase Realtime Database still remain void while using app. How is it possible? It's very strange

This are the rules on my Firebase Realtime Database:
{
"rules": {
".read": true,
".write": true
}
}
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
private EditText mUserName, mEmail, mPassword;
private Button registerBtn;
private TextView toLogin;
private ProgressBar progressBar;
private ImageView mImage;
// Firebase stuff
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
private FirebaseDatabase mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupUI();
mAuth = FirebaseAuth.getInstance();
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userName = mUserName.getText().toString();
String email = mEmail.getText().toString();
String password = mPassword.getText().toString();
if(TextUtils.isEmpty(userName)) {
Toast.makeText(getApplicationContext(),"Username is required", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(),"Email is required", Toast.LENGTH_SHORT).show();
}
if(TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(),"Password is required", Toast.LENGTH_SHORT).show();
}
if(userName.length() < 4) {
Toast.makeText(RegisterActivity.this, "Username too short", Toast.LENGTH_SHORT).show();
}
if (android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
Toast.makeText(getApplicationContext(),"Valid email address", Toast.LENGTH_SHORT).show();
}
if(password.length() < 8) {
Toast.makeText(getApplicationContext(),"Password must contain at least 8 characters", Toast.LENGTH_SHORT).show();
}
userRegister(email, password);
startActivity(new Intent(getApplicationContext(), MenuActivity.class));
finish();
}
});
toLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
});
}
private void userRegister(String email, String password) {
final ProgressDialog progressDialog = new ProgressDialog(RegisterActivity.this,
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Creating account...");
progressDialog.show();
//register user in firebase
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
User user = new User(email, password);
FirebaseDatabase.getInstance().getReference("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(RegisterActivity.this, "User successful created",
Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else {
Toast.makeText(RegisterActivity.this, "Failed to register",
Toast.LENGTH_SHORT).show();
}
}
});
}
else {
Toast.makeText(RegisterActivity.this, "Error! " +
task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void setupUI() {
mImage = findViewById(R.id.image);
mUserName = findViewById(R.id.userName_register);
mEmail = findViewById(R.id.email_register);
mPassword = findViewById(R.id.password_register);
registerBtn = findViewById(R.id.register_button);
toLogin = findViewById(R.id.toLogin);
progressBar = findViewById(R.id.progress_bar_register);
}
}
User.java
public class User {
public String userName, email, password;
public User() { }
public User(String email, String password) {
this.email = email;
this.password = password;
}
public User(String userName, String email, String password) {
this.userName = userName;
this.email = email;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I have tried many things found on web but none have worked and nothing changes, it still remain void. I'm very desperate guys. Am I forgetting to add something? Unfortunately I'm new in Android and Firebase. Thanks in advance.
Did you setup the application by downloading the google-services.json from Firebase console and putting it in the Android Studio project?
Also, did you add your app's signature to the allowed apps in Firebase console?
Refer to this.

Android: How do I display only the data of the user who is currently logged in?

I did the registration through Firebase. The data is stored like this:
Each user can fill out a form and the data from it is displayed on a separate screen in RecyclerView. The problem is that now the users are not separated in any way. This is what user records look like:
How can I make only those entries created by a particular user be displayed? I need to check exactly by user id.
Now I output the data this way:
protected void onCreate(Bundle savedInstanceState) {
...
dRef = FirebaseDatabase.getInstance().getReference().child("User Data");
dRef.addListenerForSingleValueEvent(valueEventListener);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userData = new ArrayList<UserData>();
}
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren()) {
UserData uData = dataSnapshot1.getValue(UserData.class);
userData.add(uData);
}
userAdapter = new UserAdapter(MainActivity.this, userData);
recyclerView.setAdapter(userAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
};
How can I do that? The IDs are different everywhere.
UPD:
Create user:
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(fullName, age, email, phone);
FirebaseDatabase.getInstance().getReference("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(RegisterUser.this, "Successful", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
} else {
Toast.makeText(RegisterUser.this, "Failed", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
} else {
Toast.makeText(RegisterUser.this, "Failed", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
});
User:
public class User {
public String fullName, age, email, phone;
public User() {
}
public User(String fullName, String age, String email, String phone) {
this.fullName = fullName;
this.age = age;
this.email = email;
this.phone = phone;
}
}
UserData:
public class UserData {
String id, userName, userLastName, userOtchestvo, userAppeal, userOrganisation, userPhone, userEmail, userVK, userFB;
public UserData(String id, String userName, String userLastName, String userOtchestvo, String userAppeal, String userOrganisation, String userPhone, String userEmail, String userVK, String userFB) {
this.id = id;
this.userName = userName;
this.userLastName = userLastName;
this.userOtchestvo = userOtchestvo;
this.userAppeal = userAppeal;
this.userOrganisation = userOrganisation;
this.userPhone = userPhone;
this.userEmail = userEmail;
this.userVK = userVK;
this.userFB = userFB;
}
public UserData() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
...
I add data to Firebase at the click of a button:
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userId, userName, userLastName, userOtchestvo, userAppeal, userOrganisation, userPhone, userEmail, userVK, userFB;
userId = database.push().getKey();
userName = title_input.getText().toString();
userLastName = author_input.getText().toString();
userOtchestvo = pages_input.getText().toString();
userAppeal = appeal_input.getText().toString();
userOrganisation = organisation_input.getText().toString();
userPhone = phone_input.getText().toString();
userEmail = email_input.getText().toString();
userVK = vk_input.getText().toString();
userFB = fb_input.getText().toString();
UserData userData = new UserData(userId, userName, userLastName, userOtchestvo, userAppeal, userOrganisation, userPhone, userEmail, userVK, userFB);
database.child(userId).setValue(userData);
}
});
database.push().getKey()
This doesn't give you the userid, this only gives you a random unique key which is not equals to userid.
So do this instead.
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
This will give you the userId of the current logged in user.

How to retrieve certain database child and display inside the ListView

How to retrieve/call userInfo from the following database, It is an authenticated user information
StudentInformation java class.
public class StudentInformation {
String name;
String ID;
String studentID;
String email;
String phone_num;
public StudentInformation() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone_num() {
return phone_num;
}
public void setPhone_num(String phone_num) {
this.phone_num = phone_num;
}
}
I've tried a lot of method, but the ListView still display none and the app suddenly stopped.
public class StudentInfoActivity extends AppCompatActivity {
//add Firebase Database stuff
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;
private String userID;
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_info);
mListView = (ListView) findViewById(R.id.listview);
//declare the database reference object. This is what we use to access the database.
//NOTE: Unless you are signed in, this will not be useable.
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
FirebaseUser user = mAuth.getCurrentUser();
userID = user.getUid();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
toastMessage("User Information");
} else {}
// ...
}
}; //end authlistener
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} // end oncreate
private void showData(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
StudentInformation sInfo = new StudentInformation();
sInfo.setName(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getName());
sInfo.setID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getID());
sInfo.setStudentID(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getStudentID());
sInfo.setEmail(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getEmail());
sInfo.setPhone_num(ds.child(userID).child("userInfo").getValue(StudentInformation.class).getPhone_num());
ArrayList<String> array = new ArrayList<>();
array.add(sInfo.getName());
array.add(sInfo.getID());
array.add(sInfo.getStudentID());
array.add(sInfo.getEmail());
array.add(sInfo.getPhone_num());
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,array);
mListView.setAdapter(adapter);
}
} //end showdata
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_SHORT).show();
}
} // end class
This is the code Im using. I've been wondering about the getchildren method, did I do something wrong in the code ?. Can anyone help me with this ?
You can go with FirebaseListAdapter .Here you won't have to manage any changes or attach listener and everything in the list gets updated when there is any change in server
To get the data please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userInfoRef = rootRef.child("users").child(userID).child("userInfo");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ID = ds.child("ID").getValue(String.class);
String email = ds.child("email").getValue(String.class);
String name = ds.child("name").getValue(String.class);
String phone_num = ds.child("phone_num").getValue(String.class);
String studentID = ds.child("studentID").getValue(String.class);
Log.d("TAG", ID + " / " + email + " / " + name + " / " + phone_num + " / " + studentID);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userInfoRef.addListenerForSingleValueEvent(eventListener);

Why does My app stops after i press the button

this is how i have registered the users..but it is not sending anything to database though the registration completes just fine
private void registerUser(){
//getting email and password from edit texts
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
//checking if email and passwords are empty
if(TextUtils.isEmpty(email)){
Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
return;
}
//if the email and password are not empty
//displaying a progress dialog
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
//creating a new user
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
//checking if success
if(task.isSuccessful()){
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}else{
//display some message here
Toast.makeText(MainActivity.this,"Registration Error",Toast.LENGTH_LONG).show();
}
progressDialog.dismiss();
}
});
}
then here is my login.activity. i can log in just fine but i wonder what cretiria is this code using to log in users??
private void userLogin(){
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
//checking if email and passwords are empty
if(TextUtils.isEmpty(email)){
Toast.makeText(this,"Please enter email",Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(password)){
Toast.makeText(this,"Please enter password",Toast.LENGTH_LONG).show();
return;
}
//if the email and password are not empty
//displaying a progress dialog
progressDialog.setMessage("Registering Please Wait...");
progressDialog.show();
//logging in the user
firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
//if the task is successfull
if(task.isSuccessful()){
//start the profile activity
finish();
startActivity(new Intent(getApplicationContext(), ProfileActivity.class));
}
}
});
}
change your person class like this
public class Person {
private String Username;
private String Email;
public Person(String email,String userName) {
this.Username=userName;
this.Email=email;
/*Blank default constructor essential for Firebase*/
}
//Getters and setters
public String getUsername() {
return Username;
}
public void setUsername(String Username) {
this.Username = Username;
}
public String getEmail() {
return Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
}
then use it like this
Person person=new Person();
person.setUsername(Username);
person.setEmail(Email);
Firebase newRef = ref.child("Users").push();
newRef.setValue(person);
then use this to get values
newRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Person person = dataSnapshot.getValue(Person.class);
String string = "Username: "+person.getName()+"\nEmail: "+person.getEmail()+"\n\n";
}
#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(FirebaseError firebaseError) {
}
});
The problem is described here:
com.fasterxml.jackson.databind.JsonMappingException: Can not
instantiate value of type [simple type, class
com.example.moses.bstation.Person] from String value; no single-String
constructor/factory method
It seems that the mapping between the JSON response and the Person class is incorrect.
Double check your Person class implementation, also please share your Person class implementation and a sample from the JSON response.

Categories