I have a working line of code retrieving each single data, but failed to apply them all to a class. This line is working perfectly.
double value = (double) ds.child("player1score").getValue();
But when it comes to this, it fails and crashes.
int value = (int) ds.child("point").getValue();
Solved this problem by changing it into:
long value = (long ) ds.child("point").getValue();
Yet, when retrieving using class, error occurs.
Here are the whole picture of my codes, appreciate so much for any advice, thanks!!
Round().class
public class Round {
public double player1score;
public double player2score;
public double player3score;
public double player4score;
public int point;
//Constructor
public Round(double player1score, double player2score, double player3score, double player4score, int point) {
this.player1score = player1score;
this.player2score = player2score;
this.player3score = player3score;
this.player4score = player4score;
this.point = point;
//Below are All the getter and setter etc
}
My MainActivity.class.onCreate()
//Declare Variables
UserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference gameInfoRef = rootRef.child("user").child(UserId).child("gameInfo");
DatabaseReference gameRecordRef = rootRef.child("user").child(UserId).child("gameRecord");
String gameKey = "-LLyXhetqj9mj5fgh9bn";
Under onCreate():
gameRecordRef.child(gameKey).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
ListView lv_history = (ListView) findViewById(R.id.lv_history);
//It shows proper results in logcat
System.out.println(ds.getValue());
ArrayList<Round> ResultList = new ArrayList<>();
Round round = (Round) ds.getValue(Round.class);
ResultList.add(round);
ivd_HistoryAdapter adapter = new ivd_HistoryAdapter(id_History.this, ResultList);
lv_history.setAdapter(adapter);
}
}
Firebase structure in text:
"user":
"5xGKRXeHgThQy70lduPEp3mosTj1":
"gameRecord":
"-LLyXhetqj9mj5fgh9bn":
"player1score": 0.5,
"player2score": 0.5,
"player3score": 0.5,
"player4score": 0.5,
"point": 5
Logcat Error: (Edited, not causing by integer type error)
com.google.firebase.database.DatabaseException: Class viwil.mahjongcal.Round does not define a no-argument constructor. If you are using ProGuard, make sure these constructors are not stripped.
at com.google.android.gms.internal.zzelx.zze(Unknown Source)
at com.google.android.gms.internal.zzelw.zzb(Unknown Source)
at com.google.android.gms.internal.zzelw.zza(Unknown Source)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source)
at viwil.mahjongcal.id_History$1.onDataChange(id_History.java:51)
at com.google.android.gms.internal.zzegf.zza(Unknown Source)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source)
at com.google.android.gms.internal.zzeig.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
Error pointed to this line: (id_History.java:51)
Round round = ds.getValue(Round.class);
Firebase screenshot:
To solve this, please change the following line of code:
int value = (int) ds.child("point").getValue();
to
long score = ds.child("point").getValue(Long.class);
You need to cast that object to an object of type Long and not to a primitive int. Even if you are defining your score property in your model class as an int, in the database that property is stored as a long. By default, the numbers are stored in the Firebase Realtime Database as long numbers and not as ints.
Related
[Hi all, i've database in firebase, but i had error cannot convert Long to string and string to long when a value is null.This is "meta" variable.
This is model
`public class ModelAnhKhang {
private String id;
private String tenhang;
private String macuon;
private String dvt;
private String ngaynhap;
private String phanloai;
private Long somet;
private Long meta;
private Double tytrong;`
This is Adapter
`#Override
public void onBindViewHolder(#NonNull AnhKhangViewHolder holder, int position) {
final ModelAnhKhang modelAnhKhang = listModelAnhKhang.get(position);
Locale localeUS = new Locale("us","US");
NumberFormat us = NumberFormat.getInstance(localeUS);
holder.txtMaCuon.setText(modelAnhKhang.getMacuon());
holder.txtTenHang.setText(modelAnhKhang.getTenhang());
holder.txtDvt.setText(modelAnhKhang.getDvt());
holder.txtNgayNhap.setText(modelAnhKhang.getNgaynhap());
holder.txtSoMet.setText(String.valueOf(us.format(modelAnhKhang.getSomet())));
holder.txtMetA.setText(String.valueOf(us.format(modelAnhKhang.getMeta())));`
This is Fragment
`private void getHangNhapAnhKhang() {
Query query = reference.child(ANH_KHANG).orderByChild("ngaynhap");
listModelAnhKhang.clear();
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.hasChildren() || snapshot.exists()) {
for (DataSnapshot dss : snapshot.getChildren()) {
ModelAnhKhang modelAnhKhang = dss.getValue(ModelAnhKhang.class);
listModelAnhKhang.add(modelAnhKhang);
}
}
anhKhangAdapter = new AnhKhangAdapter(getContext(), listModelAnhKhang);
rcv_AnhKhang.setAdapter(anhKhangAdapter);
anhKhangAdapter.notifyDataSetChanged();
txtTotal.setText(+anhKhangAdapter.getItemCount()+ " cuộn");
}`
4.This is firebase
dvt: "Kg"
giaban: 23317.99
khoiluong: 7130
macuon: "00340121080180602"
meta: ""
metb: ""
metc: ""
ngaynhap: "2021/09/06"
phanloai: "L2"
somet: 402
tenhang: "Thép dày mạ kẽm Z275 phủ CR3: 1.80mmx1250mm TCT..."
thanhtien: 166257251
tytrong: 17.736318407960198
this is firebase
[1][2]
[1]: https://i.stack.imgur.com/C8jIo.png
[2]: https://i.stack.imgur.com/FD6VB.png
Looks like you are trying to pass "null" to a format
holder.txtMetA.setText(String.valueOf(us.format(modelAnhKhang.getMeta())));
You should handle null values in some way, otherwise java will throw NullPointerExceptions.
Try something like:
if(modelAnhKhang.getMeta() != null){
holder.txtMetA.setText(String.valueOf(us.format(modelAnhKhang.getMeta())));
}else holder.txtMetA.setText("");
This is error when I get data from firebase: field meta = null.
If meta is not null or not equal to "", I will get no error.
Your issue is that you cannot convert ""(blank) or null to long it is not allowed in java. In your line
ModelAnhKhang modelAnhKhang = dss.getValue(ModelAnhKhang.class);
you are doing exactly that, passing incompatible values to a variable of type long. If you are using variable "meta" only to show it on some text (which looks like you do), simply change variable meta to String type and your problem will be solved.
If there is some reason why it needs to be of type long then I'd stil suggest the same solution, only where after you pass value from firebase to meta (which is String now) you later pass it to some long type variable while handling "" and null cases.
I want to get the values from firebase, but I get this error, where is the problem?
private RecyclerView recyclerView;
private CamperSiteAdapter camperSiteAdapter;
private List<CamperSiteModel> camperSiteModel;
EditText seatch_bar;
private void readCampSite(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Campsite");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(seatch_bar.getText().toString().equals("")){
camperSiteModel.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
CamperSiteModel camperSiteModel1 = snapshot.getValue(CamperSiteModel.class);
camperSiteModel.add(camperSiteModel1);
}
camperSiteAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
this is model code
public CamperSiteModel() {
}
public CamperSiteModel(String camperSiteID, String camperSiteName, String camperSiteImage, String camperSiteType, String camperSiteDistance, String camperSiteInfo, String camperSiteSummary, String camperSiteAddress, String camperSiteLatitude, String camperSiteLongitude, String camperSitePrice1, String camperSitePrice2, String camperSiteEmail, String camperSiteSub) {
CamperSiteID = camperSiteID;
CamperSiteName = camperSiteName;
CamperSiteImage = camperSiteImage;
CamperSiteType = camperSiteType;
CamperSiteDistance = camperSiteDistance;
CamperSiteInfo = camperSiteInfo;
CamperSiteSummary = camperSiteSummary;
CamperSiteAddress = camperSiteAddress;
CamperSiteLatitude = camperSiteLatitude;
CamperSiteLongitude = camperSiteLongitude;
CamperSitePrice1 = camperSitePrice1;
CamperSitePrice2 = camperSitePrice2;
CamperSiteEmail = camperSiteEmail;
CamperSiteSub = camperSiteSub;
}
this is the firebase database
Campsite
CamperSiteAddress: "90 Tasman Hwy, Orford TAS 7190"
CamperSiteDistance: ""
CamperSiteEmail: ""
CamperSiteImage: "https://media-cdn.tripadvisor.com/media/photo-s..."
CamperSiteInfo: "Raspins Beach"
CamperSiteLatitude: ""
CamperSiteLongitude: ""
CamperSiteName: "Raspins Beach"
CamperSitePrice1: "free"
CamperSitePrice2: "free"
CamperSiteSub: "TAS"
CamperSiteSummary: "Raspins Beach"
CamperSiteType: "Camp"
I don't know why this line was an error.
have I missed something? or where is the error?
is the model problem? or somewhere?
CamperSiteModel camperSiteModel1 = snapshot.getValue(CamperSiteModel.class);
error log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.luvtas.campingau, PID: 11763
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.luvtas.campingau.Model.CamperSiteModel
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertBean(CustomClassMapper.java:436)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.deserializeToClass(CustomClassMapper.java:232)
at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToCustomClass(CustomClassMapper.java:80)
at com.google.firebase.database.DataSnapshot.getValue(DataSnapshot.java:203)
at com.luvtas.campingau.Fragment.ExploreFragment$3.onDataChange(ExploreFragment.java:128)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Remove the for loop, since when you are looping you are retrieving the values of type String and not of the model class:
if(seatch_bar.getText().toString().equals("")){
camperSiteModel.clear();
CamperSiteModel camperSiteModel1 = dataSnapshot.getValue(CamperSiteModel.class);
camperSiteModel.add(camperSiteModel1);
camperSiteAdapter.notifyDataSetChanged();
}
Also in your database add a push id after the node Campsite, and you need to follow the javabean convention
The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), to and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.
You need to follow the camelCase naming convention to be able to map the database fields to the model class.
Does anyone know how to fix this problem?
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
ERROR LINE
String data = (String) dataSnapshot.child("money").getValue();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
final String userUid = user.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(userUid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ERROR LINE String data = (String) dataSnapshot.child("money").getValue();
moneyText.setText(data);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
In your error line, you are trying to cast one object into another which is not supported. The correct way of doing this is to use the valueOf method within the String class like so:
String data = String.valueOf(dataSnapshot.child("money").getValue());
Change your code this way
String data = ((Long) dataSnapshot.child("money").getValue()).toString();
Your data is Long and you are casting in to String
Long to String Example:
long testL ong = 10;
String stringLoc = Long.toString(testLong );
System.out.println("str : " + stringLoc );
In your code trying to cast Long to String. You can try below code.
String data = Long.toString(dataSnapshot.child("money").getValue());
Your dataSnapshot.child("money").getValue()
is Long type and you directly casting to string you can use like below to avoid error.
String data = String.valueOf(dataSnapshot.child("money").getValue());
I'm working on a iot project and I want to transfer data from firebase to my android app's textview help me out guys!!
This is my code
code
Firebase JSON
{
"Water_level" : 10,
"valve_1" : 0,
"valve_2" : 0
}
This is my logcat error
10-07 13:49:26.433 25077-25077/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.blogspot.techyfruit360.watercontroller, PID: 25077
com.google.firebase.database.DatabaseException: Failed to convert value of type java.lang.Long to String
at com.google.android.gms.internal.zzelw.zzb(Unknown Source:663)
at com.google.android.gms.internal.zzelw.zza(Unknown Source:0)
at com.google.firebase.database.DataSnapshot.getValue(Unknown Source:10)
at com.blogspot.techyfruit360.watercontroller.Main2Activity$1.onDataChange(Main2Activity.java:40)
at com.google.android.gms.internal.zzegf.zza(Unknown Source:13)
at com.google.android.gms.internal.zzeia.zzbyc(Unknown Source:2)
at com.google.android.gms.internal.zzeig.run(Unknown Source:65)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6518)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
in onDataChange delete everything you have written an try the following
myRef.addListenerForSingleValueEvent( new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot){
if(dataSnapshot.exists()){
Map<String, Object> objectMap = (HashMap<String, Object>) dataSnapshot.getValue();
String value = (String) objectMap.get( "Water_level" );
Log.d("Water_level", "Value is: " + value);
textView.setText(value);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
} );
This should solve your issue. Make sure your Database ref is set correctly.
Failed to convert value of type java.lang.Long to String
Inside your onDataChange(),
String value = datasnapshot.getValue(String.class)
It's converting a long value to String that's why you're getting the error.
Try this instead:
String waterLevel = dataSnapshot.child("Water_level").getValue(String.class);
textView.setText(waterLevel)
Or just use toString().
I am trying to get a specific value from a firebase database that I have already created. I have followed this youtube tutorial and another similar question which is quite related to what I am trying to achieve.
This is how my Firebase Database looks like Database Tree
I am trying to fetch all the individual items like Name, Snippet, Lat, Long from this db.
Here is what I have tried so far. Right now I have only tried to get Name item
In Oncreate Method :
final TextView nametext = (TextView)findViewById(R.id.name);
Firebase.setAndroidContext(this);
final Firebase ref = new Firebase("https://fir-with-maps.firebaseio.com/Group 2");
final List<PlumbersList> listofplumbers = new ArrayList<>();
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
PlumbersList plumberslist = dataSnapshot.getValue(PlumbersList.class);
listofplumbers.add(plumberslist);
String name = plumberslist.Name;
nametext.setText(name);
}
#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) {
}
});
}
PlumberList class
public class PlumbersList {
String Name;
String Snippet;
String Lat;
String Long;
public PlumbersList() {
}
public PlumbersList(String name, String snippet, String lat, String aLong) {
Name = name;
Snippet = snippet;
Lat = lat;
Long = aLong;
}
public String getName() {
return Name;
}
public String getSnippet() {
return Snippet;
}
public String getLat() {
return Lat;
}
public String getLong() {
return Long;
}
The app crashes after a few seconds. Here is what error logcat looks like
09-09 23:41:19.381 1375-1375/digiart.mapwithfirebase E/UncaughtException: com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5833)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Snippet" (class digiart.mapwithfirebase.PlumbersList), not marked as ignorable (0 known properties: ])
at [Source: java.io.StringReader#297f6a4e; line: 1, column: 13] (through reference chain: digiart.mapwithfirebase.PlumbersList["Snippet"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5833)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
09-09 23:41:19.711 1375-1375/digiart.mapwithfirebase E/AndroidRuntime: FATAL EXCEPTION: main Process: digiart.mapwithfirebase, PID: 1375
com.firebase.client.FirebaseException: Failed to bounce to type
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:183)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5833)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
Caused by: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Snippet" (class digiart.mapwithfirebase.PlumbersList), not marked as ignorable (0 known properties: ])
at [Source: java.io.StringReader#297f6a4e; line: 1, column: 13] (through reference chain: digiart.mapwithfirebase.PlumbersList["Snippet"])
at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1160)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:121)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2888)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2034)
at com.firebase.client.DataSnapshot.getValue(DataSnapshot.java:181)
at digiart.mapwithfirebase.checkingfirebase$1.onChildAdded(checkingfirebase.java:36)
at com.firebase.client.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:48)
at com.firebase.client.core.view.DataEvent.fire(DataEvent.java:45)
at com.firebase.client.core.view.EventRaiser$1.run(EventRaiser.java:38)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:210)
at android.app.ActivityThread.main(ActivityThread.java:5833)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1113)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:879)
I am new in android coding so I might be making some very silly mistake here.
As per your data tree, you are reading from "Group 2" i.e. you are downloading everything under "Group 2" including the "1". What are you trying to achieve here is the main problem. Will there be data "2", "3", "4" and so on? Are those information required to be retrieved?
NO, I only intened to read information from "1"
- Based on you setting the textview to a single name, I assume you only need the first item. Hence, you should use a addValueEventListener instead, and directly read from https://fir-with-maps.firebaseio.com/Group 2/1
// add child "1"
ref.child("1").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
PlumbersList plumberslist = dataSnapshot.getValue(PlumbersList.class);
}
});
YES, I need everything under "Group 2" - Then you just need to go one level deeper.
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
DataSnapshot childSnapshot = dataSnapshot.getValue(); // get the values of "1"
PlumbersList plumberslist = childSnapshot.getValue(PlumbersList.class);
listofplumbers.add(plumberslist);
String name = plumberslist.Name;
nametext.setText(name);
}
});
Suggestion/Question(?) Why is the object called PlumbersList? it looks more like a single Plumber object.
Getting every plumber in node "group 2" (1,2,3....n), your need to iterate over all the child at that node
ArrayList<Plumber> mPlumbersList = new ArrayList<>();
ref = FirebaseDatabase.getInstance().getReference().child("group 2");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
for (DataSnapshot data : dataSnapshot.getChildren())
{
Plumber plumber = data.getValue(Plumber.class);
mPlumbersList.add(plumber);
}
// Notify the adapter after the foreach loop ends, if this list is backing one
mAdapter.notifyDataSetChanged();
}
...
});