Retrieve Firebase Data And Display In Listview In Android Studio
I am currently building an Android app and using Firebase as its backend database, however i'm having difficulties to retrieve the data and display them in a ListView. I tried few
Solution 1:
You are getting that error, because you are missing a child. To solve this, please change the following line of code:
String value = dataSnapshot.getValue(String.class);
to
String value = dataSnapshot.child("Name").getValue(String.class);
The output in your logat will be the name of all clients.
P.S. Also be aware that you'll encounter other errors in your project because the name of your fields inside your Client
class are all lowercase while in your database all start with a capital letter. The name should be the same. Please also take a look here.
publicclassClient {
privateString name, location, latitude, longitude;
publicClient() {}
publicClient(String name, String location, String latitude, String longitude) {
this.name = name;
this.location = location;
this.latitude = latitude;
this.longitude = longitude;
}
publicStringgetName() { return name; }
publicStringgetLocation() { return location; }
publicStringgetLatitude() { return latitude; }
publicStringgetLongitude() { return longitude; }
}
Solution 2:
create POJO
class ArrayList
and add this in your list check below code
publicclassClientLIstActivityextendsAppCompatActivity {
privateButton clientSelect;
privateListView clientlistView;
privateFirebaseDatabase database;
privateDatabaseReference databaseReference;
privateArrayList<Client> list = newArrayList>(); // 1=change hereprivateArrayAdapter<String> adapter;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_list);
clientlistView = (ListView) findViewById(R.id.clientListView);
adapter = newArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
clientlistView.setAdapter(adapter);
adapter.notifyDataSetChanged();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Clients");
clientSelect = (Button) findViewById(R.id.selectClient);
clientSelect.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
onBackPressed();
}
});
databaseReference.addChildEventListener(newChildEventListener() {
@OverridepublicvoidonChildAdded(DataSnapshot dataSnapshot, String s) {
Client value = dataSnapshot.getValue(Client.class); // 2=change here
list.add(value);
}
@OverridepublicvoidonChildChanged(DataSnapshot dataSnapshot, String s) {
}
@OverridepublicvoidonChildRemoved(DataSnapshot dataSnapshot) {
}
@OverridepublicvoidonChildMoved(DataSnapshot dataSnapshot, String s) {
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
}
});
}
}
Post a Comment for "Retrieve Firebase Data And Display In Listview In Android Studio"