Can't save a message in firebase database - java

I am trying to save a message object in the firebase database, when I run the code I get no errors, everything looks to be fine but when I go to firebase website, nothing appears in the database
public class MainChatActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_chat);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
private void sendMessage() {
String input = mInputText.getText().toString();
if(!input.equals("")){
InstantMessage chat=new InstantMessage(input, mDisplayName);
mDatabaseReference.child("children").push().setValue(chat);
mInputText.setText("");
}
}
}
public class InstantMessage {
private String message;
private String author;
public InstantMessage(String message, String author) {
this.message = message;
this.author = author;
}
public InstantMessage() {
}
public String getMessage() {
return message;
}
public String getAuthor() {
return author;
}
}
I expect to save the message with author name in a directory named "messages" in firebase, but that's not happening

Change your firebase database rules to the following:
{
"rules": {
".read": true
".write": true
}
}
It allows read/write access to all users under any conditions.
Warning: NEVER use this ruleset in production; it allows anyone to overwrite your entire database.

try this:
public class MainChatActivity extends AppCompatActivity {
private DatabaseReference mDatabaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_chat);
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendMessage();
}
});
}
private void sendMessage() {
String input = mInputText.getText().toString();
if(!input.equals("")){
InstantMessage chat=new InstantMessage(input, mDisplayName);
String key = mDatabaseReference.push().getKey();
mDatabaseReference.child("messages").child(key).setValue(chat) //here you can add a Listener to check success;
mInputText.setText("");
}
}
}
public class InstantMessage {
private String message;
private String author;
public InstantMessage(String message, String author) {
this.message = message;
this.author = author;
}
public InstantMessage() {
}
public String getMessage() {
return message;
}
public String getAuthor() {
return author;
}
}

It seems its permission issue
Make sure you are permission for READ/WRITE on the database, check the rules and make them public
{
"rules": {
".read": true
".write": true
}
}

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

Unable to write to Firebase Realtime Database

I'm learning how to write data to Firebase RealTime Database, but after some tests I can't put new data into my DB and I haven't had any error from the app.
Here is my code:
MainActivity.class
public class MainActivity extends AppCompatActivity {
EditText mName;
Button button;
DatabaseReference root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mName = findViewById(R.id.etMess);
button = findViewById(R.id.btInvia);
root = FirebaseDatabase.getInstance().getReference().child("student");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
insertData();
}
});
}
private void insertData() {
String name = mName.getText().toString();
Dati dati = new Dati(name);
root.push().setValue(dati);
Toast.makeText(this,"Data inserted",Toast.LENGTH_SHORT).show();
}
}
Dati.class
public class Dati {
String name;
public Dati(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Rules from my db are:
{
"rules": {
".read": true,
".write": true
}
}
I tried to read something from DB using get() function, but I had an error:
get for query / falling back to disk cache after error: Client is offline java.lang.Exception: Client is offline
Any help appreciated.

How to retrieved data in Firebase to the Android Studio [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need to retrieved data from database Firebase. But I have problem since when I try to retrieve the data, the application will stop.
this is the code for retrievedPoint.java
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("reloadPoint");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ReloadPoint rp = dataSnapshot.getValue(ReloadPoint.class);
System.out.println(rp);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
ReloadPoint newPost = dataSnapshot.getValue(ReloadPoint.class);
System.out.println("Email: " + newPost.getmEmail());
System.out.println("Point: " + newPost.getmPoint());
System.out.println("User id: " + newPost.getmUserid());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
this the code for the ReloadPoint class.
public class ReloadPoint {
private String mEmail;
private String mPoint;
private String mUserid;
public ReloadPoint(String email, String point, String userid) {
this.mEmail = email;
this.mPoint = point;
this.mUserid = userid;
}
public String getmEmail() {
return mEmail;
}
public void setmEmail(String mEmail) {
this.mEmail = mEmail;
}
public String getmPoint() {
return mPoint;
}
public void setmPoint(String mPoint) {
this.mPoint = mPoint;
}
public String getmUserid() {
return mUserid;
}
public void setmUserid(String mUserid) {
this.mUserid = mUserid;
}
}
This is the thing that I want to retrieve from Firebase.
this is the child that I want to retrieve
This is the Android where the retrived data will appear if the retrieved process is success.retrievedPoint.xml
Result from log cat.Log cat result
Please help me.
As the error message implies, your ReloadPoint class needs a no-args constructor, e.g :
public ReloadPoint() {
}
Please include a no-argument constructor in your ReloadPoint class like so
public ReloadPoint() {
}
see this question users does not define no argument constructor
public class ReloadPoint {
private String mEmail;
private String mPoint;
private String mUserid;
//Ni hang lupa ni. apa la sakinah
//Klau da soklan lagi, hbungi kt insta id: nyrtron
public ReloadPoint(){
}
public ReloadPoint(String email, String point, String userid) {
this.mEmail = email;
this.mPoint = point;
this.mUserid = userid;
}
public String getmEmail() {
return mEmail;
}
public void setmEmail(String mEmail) {
this.mEmail = mEmail;
}
public String getmPoint() {
return mPoint;
}
public void setmPoint(String mPoint) {
this.mPoint = mPoint;
}
public String getmUserid() {
return mUserid;
}
public void setmUserid(String mUserid) {
this.mUserid = mUserid;
}
}
I think I have found your problem.
DatabaseReference ref = database.getReference().child("reloadPoint").child("Waniyanazahri");
UPDATED ANSWER:
Its look like you haven't call the class.
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Add this one
ReloadPoint rp = new ReloadPoint();
rp = dataSnapshot.getValue(ReloadPoint.class);
System.out.println(rp);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});

Error while passing a model from an activity to another

So I'm following Coding with Mitch's tutorial on Firestore and I'm changing it to fit my personals needs. I'm building a TO-DO App (This is my first ever app/project) Right now, I'm trying to make a second activity in order to view, update and delete the selected task (This activity is ViewTaskActivity). I'm stuck when trying to pass the current task from the MainActivity to the ViewTaskActivity. When I try to call a method on the task variable, it gives me an error.
Here's the code:
Task Model:
package dev.raphdl.firebasepractice.models;
imports ...
#IgnoreExtraProperties
public class Task implements Parcelable {
private String title;
private String content;
private #ServerTimestamp Date timestamp;
private String note_id;
public Task(String title, String content, Date timestamp, String note_id) {
this.title = title;
this.content = content;
this.timestamp = timestamp;
this.note_id = note_id;
}
public Task(){
}
private Task(Parcel in) {
title = in.readString();
content = in.readString();
note_id = in.readString();
}
public static final Creator<Task> CREATOR = new Creator<Task>() {
#Override
public Task createFromParcel(Parcel in) {
return new Task(in);
}
#Override
public Task[] newArray(int size) {
return new Task[size];
}
};
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public String getNote_id() {
return note_id;
}
public void setNote_id(String note_id) {
this.note_id = note_id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(title);
parcel.writeString(content);
parcel.writeString(note_id);
}
}
MainActivity
package dev.raphdl.firebasepractice;
imports ...
public class MainActivity extends AppCompatActivity implements
View.OnClickListener,
IMainActivity {
#Override
public void updateTask(final Task mTask) {
DocumentReference docRef = db
.collection("users")
.document(mAuth.getCurrentUser().getUid())
.collection("tasks")
.document(mTask.getNote_id());
docRef.update("title", mTask.getTitle(),"content", mTask.getContent()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<Void> task) {
if(task.isSuccessful()){
makeSnackBarMessage("Updated Task");
mAdapter.updateTask(mTask);
} else {
makeSnackBarMessage("Update Failed, Check logs");
}
}
});
}
#Override
public void deleteTask(final Task mTask){
DocumentReference docRef = db
.collection("users")
.document(mAuth.getCurrentUser().getUid())
.collection("tasks")
.document(mTask.getNote_id());
docRef.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull com.google.android.gms.tasks.Task<Void> task) {
if (task.isSuccessful()){
makeSnackBarMessage("Task Deleted");
mAdapter.deleteTask(mTask);
} else {
makeSnackBarMessage("Failed to Delete, Check Logs");
}
}
});
}
#Override
public void onTaskSelected(Task mTask) {
viewTaskActivity(mTask);
}
private void viewTaskActivity(Task task) {
Intent intent = new Intent(this, ViewTaskActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable("Task", task);
intent.putExtras(bundle);
startActivity(intent);
}
}
MainActivityInterface
package dev.raphdl.firebasepractice;
import dev.raphdl.firebasepractice.models.Task;
public interface IMainActivity {
void createNewTask(String title, String content);
void onTaskSelected(Task mTask);
void updateTask (Task mTask);
void deleteTask(Task mTask);
}
ViewTaskActivity
package dev.raphdl.firebasepractice;
imports ...
public class ViewTaskActivity extends AppCompatActivity implements View.OnClickListener {
private IMainActivity mIMainActivity;
private Task mTask;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_task);
Bundle bundle = getIntent().getExtras();
mTask = bundle.getParcelable("Task");
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.save_text_view: {
String title = titleEditText.getText().toString();
String content = contentEditText.getText().toString();
if (mTask != null) {
Toast.makeText(this, "mTask Not NULL", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onClick: mTask Not NULL");
mTask.setTitle(title);
mTask.setContent(content);
//THIS IS THE LINE THAT TRIGGERS THE ERROR
mIMainActivity.updateTask(mTask);
mainActivity();
}else {
Log.d(TAG, "onClick: mTask NULL");
Toast.makeText(this, "mTask NULL", Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.delete_text_view: {
mIMainActivity.deleteTask(mTask);
mainActivity();
break;
}
}
}
private void mainActivity() {
Intent intent = new Intent(this, MainActivity.class);
Toast.makeText(this, "MainActivity", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
}
Finally, the error:
6072-6072/dev.raphdl.firebasepractice E/AndroidRuntime: FATAL EXCEPTION: main
Process: dev.raphdl.firebasepractice, PID: 6072
java.lang.NullPointerException: Attempt to invoke interface method 'void dev.raphdl.firebasepractice.IMainActivity.updateTask(dev.raphdl.firebasepractice.models.Task)' on a null object reference
at dev.raphdl.firebasepractice.ViewTaskActivity.onClick(ViewTaskActivity.java:68)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24697)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Sorry for the big blocks of code.
FYI: the app gives me the same error when trying to delete the task
I'm am still a beginner so this could be me just forgetting something.
Thank you for reading this
First understand the basic concepts of JAVA. You have to create object of the class which is implementing the interface. In your case MainActivity is implementing interface IMainActivity. So you need to initialize mIMainActivity with MainActivity object for ex:
IMainActivity mIMainActivity = new MainActivity();

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);

Categories