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

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

Related

Display Detail firebase data from listview onitemclick Android Studio

The problem I am facing is that I cannot display the detail of the ListView on which I clicked, any suggestion to display the detail of the Firebase data, I'm done for itemOnClick and change to another activity, but the problem is that it shows only the text of ListView and not the detail, thank you
LISTVIEW JAVA CLASS
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
final String value = dataSnapshot.getValue(Sample.class).toString();
arrayList.add(0,value);
listcase.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), Report.class);
//String sample = String.valueOf(arrayList.get(i));//arrayAdapter.getItem(i);
intent.putExtra("sample", String.valueOf(arrayList.get(i)));
startActivity(intent);
overridePendingTransition(R.anim.slide_right_entering, R.anim.slide_right_exiting);
finish();
}
});
}
});
CONSTRUCTOR
public Sample() {
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public String getSymthom() {
return symthom;
}
public void setSymthom(String symthom) {
this.symthom = symthom;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public String getDateDiag() {
return DateDiag;
}
public void setDateDiag(String dateDiag) {
DateDiag = dateDiag;
}
public String toString (){
return "Sample Name : " + Name + "\n"+ "Status : ";
}
DETAIL JAVA CLASS
Intent intent = getIntent();
if (intent.hasExtra("sample"))
{
textView.setText(intent.getStringExtra("sample"));
}
I have no idea how to display detail of my Firebase object to another activity, thank you for helping me
Your ArrayList contains an only String, not a detail object.
final String value = dataSnapshot.getValue(Sample.class).toString();
So when you get by index it returns item value. If you share the value of value JSON structure it would be good to understand better.
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot){
Log.d("data", "onDataChange: "+ dataSnapshot);
Sample Sample = snapshot.getValue(Sample.class);
sampleList.add(Sample);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

How to properly initialize value from firebase with model class

I am making a firebase app where the user is able to rate another user. I am occasionally getting a null pointer on this like of code:
averageStars+=Double.parseDouble(rate.getRates());
I seem to mess things up like this often, where I create a model class and then somehow never initialize it. However, even with some research, I am not sure why these are not considered initialized. Would anyone have an idea on how I initialize classes like this(Firebase). My main code for the activity looks like:
public class RateActivity extends AppCompatActivity {
Button btnSubmit;
MaterialRatingBar ratingBar;
MaterialEditText edtComment;
FirebaseDatabase database;
DatabaseReference rateDetailRef;
DatabaseReference driverInformationRef;
double ratingStars= 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate);
database = FirebaseDatabase.getInstance();
rateDetailRef = database.getReference(Common.rate_detail_tbl);
driverInformationRef = database.getReference(Common.user_driver_tbl);
btnSubmit = (Button)findViewById(R.id.btnSumbit);
ratingBar = (MaterialRatingBar)findViewById(R.id.ratingBar);
edtComment = (MaterialEditText)findViewById(R.id.edtComment);
ratingBar.setOnRatingChangeListener(new MaterialRatingBar.OnRatingChangeListener() {
#Override
public void onRatingChanged(MaterialRatingBar ratingBar, float rating) {
ratingStars = rating;
}
});
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitRateDetails(Common.driverId);
}
});
}
private void submitRateDetails(String driverId) {
SpotsDialog alertDialog = new SpotsDialog(this);
alertDialog.show();
Rate rate = new Rate();
rate.setRates(String.valueOf(ratingStars));
rate.setComments(edtComment.getText().toString());
rateDetailRef.child(Common.driverId)
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.push()
.setValue(rate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
rateDetailRef.child(Common.driverId)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
double averageStars = 0.0;
int count = 0;
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
Rate rate = postSnapshot.getValue(Rate.class);
averageStars+=Double.parseDouble(rate.getRates());
count++;
}
double finalAverage = averageStars/count;
DecimalFormat df = new DecimalFormat("#.#");
String valueUpdate = df.format(finalAverage);
Map<String,Object> driverUpdateRate = new HashMap<>();
driverUpdateRate.put("rates",valueUpdate);
driverInformationRef.child(Common.driverId)
.updateChildren(driverUpdateRate)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
alertDialog.dismiss();
Toast.makeText(RateActivity.this, "Thank you for your feedback", Toast.LENGTH_SHORT).show();
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
alertDialog.dismiss();
Toast.makeText(RateActivity.this, "Rating did not go through", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
alertDialog.dismiss();
Toast.makeText(RateActivity.this,"Rating failed?",Toast.LENGTH_SHORT).show();
}
});
}
}
My model class for the "getRates" feature looks like
public class Rate {
private String rates;
private String comments;
public Rate(String rates, String comments) {
this.rates = rates;
this.comments = comments;
}
public Rate(){}
public String getRates() {
return rates;
}
public void setRates(String rates) {
this.rates = rates;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
Thank you.
Due to request, here is my logcat:
2020-01-26 17:59:25.792 25184-25184/com.example.usubx E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.usubx, PID: 25184
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.trim()' on a null object reference
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1838)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
at com.example.usubx.RateActivity$4$1.onDataChange(RateActivity.java:102)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##19.2.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##19.2.0:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##19.2.0:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Here is the value of my datasnapshot
DataSnapshot { key = RateDetails, value = {UE7cSOf5Thbum6OwEmg9seAPD463={-LzZH15-YVs1m67EuJlD={comments=Colin, rates=4.5}, -LzZHvuClxb5Ef3jk23_={comments=, rates=5.0}}, -LzJrTz5FrzEaoWorqP-={comments=, rates=5.0}, -LzKQn7F1ybKVAxUj9NX={comments=heck cool, rates=5.0}, -LzNyBwBh0tVHKvMfgEk={comments=, rates=5.0}, vAdqbIhLKJasOtyXKYrCkrOSVq33={-Lz-hH6TXxKTUVvIUYnK={comments=he was cool, rates=5.0}, -LzNz80QZDhnZA1tJ27Y={comments=, rates=3.5}, -Lz-h35N3l0xnLVVNvwa={comments=, rates=1.5}, -LzJqTWwUXOsfKPDZh2E={comments=, rates=5.0}, -LzNzEjdyg_aYMAfdI14={comments=, rates=5.0}, -LzJomtnZH4zJ6nddk0c={comments=HECK YES IT WORKS, rates=5.0}}, -LzJt7VA3iVPLopRFD34={comments=let's go, rates=5.0}, -LzNxj1zaWAZukLPyTEw={comments=, rates=5.0}, -LzNv9bTAz7_3vXioMRe={comments=heck, rates=5.0}} }
I agree with the other answer that, just putting a null should suffice to handle the case here. However, from your question, it looks like you want to initialize the Rate class with default values so that you do not end up with some invalid/null values at any point in time. In that case, I would actually suggest modifying the Rate class getters as follows.
public class Rate {
private String rates;
private String comments;
public Rate(String rates, String comments) {
this.rates = rates;
this.comments = comments;
}
public Rate(){}
public String getRates() {
if (rates == null) return "0.0";
else return rates;
}
public void setRates(String rates) {
this.rates = rates;
}
public String getComments() {
if (comments == null) return ""; // Return empty string
else return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
}
I hope that helps!
Because your database has null rates. Please check your database. some data did not have rates string.
and check null like this to avoid NullPointerException
if(rate.getRates() != null)
averageStars+=Double.parseDouble(rate.getRates());

How to retrieve data from firebase realtime database and display it in profile dashboard

So I'm trying to display the data related to the user that has logged in but the data related to it is returning me null I've tried multiple solutions but it didn't work
public class HomeViewModel extends ViewModel {
private MutableLiveData<String> mText;
DatabaseReference userdata;
String namedata;
public HomeViewModel() {
userdata = FirebaseDatabase.getInstance().getReference();
userdata.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap : dataSnapshot.getChildren()){
User user = snap.getValue(User.class);
namedata = user.getUserId();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mText = new MutableLiveData<>();
mText.setValue("Welcome back! " +namedata);
}
public LiveData<String> getText() {
return mText;
}}`
here is the User.class I want to get those data and display it in the views
public class User {
String userId;
String userPhone;
String userGender;
public User() {
}
public User(String userId, String userPhone, String userGender) {
this.userId = userId;
this.userPhone = userPhone;
this.userGender = userGender;
}
public String getUserId() {
return userId;
}
public String getUserPhone() {
return userPhone;
}
public String getUserGender() {
return userGender;
}}
You have to call the "userId"
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()){
HashMap<String, String> map = (HashMap<String, String>) snap.getValue();
if (map.containsKey("userId")) {
if (map.get("userId").equals("william henry")) {
String userGender = map.get("userGender");
}
}
}
}
or
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()){
HashMap<String, String> map = (HashMap<String, String>) snap.getValue();
if (map.containsKey("userId")) {
String userGender = map.get("userId");
}
}
}
You are getting null because you are not fetching value from correct node. There are child of users and you want to get values of child of user.
userdata = FirebaseDatabase.getInstance().getReference().child("User");
userdata.addOnChildEventListener( new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snap, String previousChildName) {
//get value here.
User user = snap.getValue(User.class);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
You want to get single user data then
userdata = FirebaseDatabase.getInstance().getReference().child("User").child(userIdOfthatuser);
userdata.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snap) {
User user = snap.getValue(User.class);
namedata = user.getUserId();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
first FirebaseDatabase.getInstance().getReference() point to your root ( which is the link above your database).so you need to point to what you want to get ( which is User tree).
Second of all,you must set your data inside onDataChange cause it not synchonize function ( mean your name data is always not follow the data return from onDataChange)
FirebaseDatabase.getInstance().getReference().child("User").orderByChild("userId").equalTo(*your_logged_in_user_id*).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Iterator iterator = dataSnapshot.getChildren().iterator()
if(iterator.hasNext()){
User user = iterator.next().getValue(User.class)
}
name = user.getName();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

addChildEventListener is not working

In my app I want to add data to my Firebase database and read the data simultaneously. So I am using addChildEventListener() method to retrieve data. But this method is not working and the app is getting crashed everytime.
The code is given below:
public class ChatActivity extends AppCompatActivity {
LinearLayout layout;
RelativeLayout layout_2;
ImageView sendButton;
EditText messageArea;
ScrollView scrollView;
//Firebase reference1, reference2;
private DatabaseReference reference1, reference2,reference3;
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
private String username,userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
layout = (LinearLayout) findViewById(R.id.layout1);
layout_2 = (RelativeLayout)findViewById(R.id.layout2);
sendButton = (ImageView)findViewById(R.id.sendButton);
messageArea = (EditText)findViewById(R.id.messageArea);
scrollView = (ScrollView)findViewById(R.id.scrollView);
username=getIntent().getStringExtra("abc");
userId=getIntent().getStringExtra("abcd");
reference1= FirebaseDatabase.getInstance().getReferenceFromUrl("https://career-dna-bec2e.firebaseio.com/CHAT/user/" +username);
reference2=FirebaseDatabase.getInstance().getReferenceFromUrl("https://career-dna-bec2e.firebaseio.com/CHAT/admin/"+username);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String messageText = messageArea.getText().toString();
if(!messageText.equals("")){
Map<String, String> map = new HashMap<String, String>();
map.put("message", messageText);
map.put("user",userId);
reference1.push().setValue(map);
reference2.push().setValue(map);
messageArea.setText("");
}
}
});
try
{
reference1.addChildEventListener(new com.google.firebase.database.ChildEventListener() {
#Override
public void onChildAdded(com.google.firebase.database.DataSnapshot dataSnapshot, String s) {
Map<String, String> map = dataSnapshot.getValue(Map.class);
String message = map.get("message").toString();
String userName = map.get("user").toString();
if(userName.equals(userId)){
addMessageBox("You:-\n" + message, 1);
}
else{
addMessageBox("admin"+ ":-\n" + message, 2);
}
}
#Override
public void onChildChanged(com.google.firebase.database.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.google.firebase.database.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.google.firebase.database.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"error:"+e,Toast.LENGTH_SHORT).show();
}
}
The app is crashing with this error:
02-23 20:43:15.832 12583-12583/com.ankush.anthroplace.careerdna
E/AndroidRuntime: FATAL EXCEPTION: main Process:
com.ankush.anthroplace.careerdna, PID: 12583
com.google.firebase.database.DatabaseException: Class java.util.Map
has generic type parameters, please use GenericTypeIndicator instead
Try using :
Map<String, Object> map = new HashMap<String, Object>();
While retrieving data use this :
Map<String, Object> map = dataSnapshot.getValue(Map.class);
But, if you really want to use Map class with 2 Strings as parameters, use this inside onChildAdded method :-
GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator);
There's no need to enter the full URL, use this instead
DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference().child("CHAT").child("user").child(username);
DatabaseReference reference2 = FirebaseDatabase.getInstance().getReference().child("CHAT").child("admin").child(username);
And, one more thing you are doing wrong is, you are adding ChildEventListener everytime the sendButton is clicked, which is not neccesary, just create a ChildEventListener inside onCreate() and not in onClick() like this:-
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Map<String, String> map = dataSnapshot.getValue(Map.class);
String message = map.get("message").toString();
String userName = map.get("user").toString();
if(userName.equals(userId)){
addMessageBox("You:-\n" + message, 1);
}
else{
addMessageBox("admin"+ ":-\n" + message, 2);
}
}
#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) {
Log.e("TAG", databaseError.toString());
}
};
//attaching the ChildEventListener to the DatabaseReference
reference1.addChildEventListener(childEventListener);
Don't forget to remove the listener in onStop()
#Override
protected void onStop() {
super.onStop();
reference1.removeEventListener(childEventListener);
}
I have solved the problem myself by using an object to store the data instead of hashmap. I am not sure why map is not working,but use of object is doing fine.
the code is given below:
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String messageText = messageArea.getText().toString();
if(!messageText.equals("")){
map=new messageModel(messageText,userId);
reference1.child(""+n).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
reference2.child(""+n2).setValue(map).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful())
{
messageArea.setText("");
}
}
});
}
else
{
Toast.makeText(getApplicationContext(),"server problem try again",Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
try
{
reference1.addChildEventListener(new com.google.firebase.database.ChildEventListener() {
#Override
public void onChildAdded(com.google.firebase.database.DataSnapshot dataSnapshot, String s) {
map = dataSnapshot.getValue(messageModel.class);
String message = map.myMessage;
String userName = map.user;
if(userName.equals(userId)){
addMessageBox("You:\n" + message, 1);
}
else{
addMessageBox("USER:\n" + message, 2);
}
}
#Override
public void onChildChanged(com.google.firebase.database.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(com.google.firebase.database.DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(com.google.firebase.database.DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),"error:"+e,Toast.LENGTH_SHORT).show();
}
as u can see no part of the code has been changed except the map portion.The code of messageModel class is as following:
public class messageModel {
public String myMessage;
public String user;
public messageModel()
{
}
public messageModel(String a,String b)
{
myMessage=a;
user=b;
}
}

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