Showing Firebase data in ListView
This is a classic issue with asynchronous APIs. In order to make it work, change your model class according to Java Naming Conventions. Your class should look like this:
public class Score {
private String userId, score;
public Score() {}
public Score(String userId, String score) {
this.userId = userId;
this.score = score;
}
public String getUserId() {
return userId;
}
public String getScore() {
return score;
}
@Override
public String toString() {
return "Score{" +
"userId='" + userId + '\'' +
", score='" + score + '\'' +
'}';
}
}
Also note that onDataChange()
method has an asynchronous behavior, which means that is called even before you are trying to add those objects of Score
class to the list. In other words, your list
will always be empty outside that method. A quick fix would be to move the declaration of your list inside onDataChange()
and do what you want to do with it or, if you want to dive into the asynchronous world and use my answer from this post.
Assuming the score
node is a direct child of your Firebase root, to display the data using the String class, please use the following code:
ListView listView = (ListView) findViewById(R.id.list_view);
List<String> list = new ArrayList<>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list);
listView.setAdapter(arrayAdapter);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference scoreRef = rootRef.child("score");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("userId").getValue(String.class);
String score = ds.child("score").getValue(String.class);
list.add(userId + " / " + score);
Log.d("TAG", userId + " / " + score);
}
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
And this how you can display data using the Score
class.
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Score score = ds.getValue(Score.class);
String userId = score.getUserId();
String score = score.getScore();
Log.d("TAG", userId + " / " + score);
list.add(score);
}
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, task.getException().getMessage());
}
};
scoreRef.addListenerForSingleValueEvent(eventListener);
How to retrieve data from Firebase into a ListView (with custom Array Adapter)
You are getting a "blank screen" because the name of the properties in your class do not match the name of the properties in the database. See, you have a field named mPlaceTitle
in your Place
class, while in the database is called placeTitle
and this is not correct. To solve this, you can simply change the name of all properties in your class to match the one in the database, which are named correct according to the Java Naming Conventions regarding variables.
Show Firebase data in ListView
You didn't add the child reference to your DB.
1.
Use This Line InsteadmDatabase = FirebaseDatabase.getInstance().getReference().child(User).child(Instruktor);
2.
getValue(String.class)
will most probably retieve a list of true.
To refer the names withinPredmeti
you can trygetKey()
String []value = subjectssnapshot.child("Predmeti").getValue(String.class);
3.
Use this to update the listarrayAdapter.notifyDataSetChanged();
How to display the firebase data in listview?
You can use FirebaseListAdapter for display data in list.
Like :
Firebase ref = new Firebase("https://<yourapp>.firebaseio.com");
ListAdapter adapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class, android.R.layout.two_line_list_item, mRef)
{
protected void populateView(View view, ChatMessage chatMessage)
{
((TextView)view.findViewById(android.R.id.text1)).setText(chatMessage.getName());
((TextView)view.findViewById(android.R.id.text2)).setText(chatMessage.getMessage());
}
};
listView.setListAdapter(adapter);
Retrieve Firebase Data and Display in ListView in Android Studio
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.
public class Client {
private String name, location, latitude, longitude;
public Client() {}
public Client(String name, String location, String latitude, String longitude) {
this.name = name;
this.location = location;
this.latitude = latitude;
this.longitude = longitude;
}
public String getName() { return name; }
public String getLocation() { return location; }
public String getLatitude() { return latitude; }
public String getLongitude() { return longitude; }
}
How to Read Data from Firebase Database and Display Multiple Fields in ListView with ArrayAdapter
after two days of being stuck I was able to answer my own question! Hopefully this will help future beginners stuck trying to display a custom view within an ArrayAdapter. Basically, I created a custom ArrayAdapter
class which could hold three TextViews
inside of it.
I am in no means an expert and will not be able to explain this as well as others, so instead, I will paste a link to the two video tutorials that I followed and had success with.
Android Beginner Tutorial #8 - Custom ListView Adapter For Displaying Multiple Columns
https://www.youtube.com/watch?v=E6vE8fqQPTE&t=392s
Android Beginner Tutorial #9 - Custom ListView Adapter [With Loading Animation]
https://www.youtube.com/watch?v=SApBLHIpH8A
Here is my updated code below:
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private static ArrayList<SearchModel> searchArrayList;
private LayoutInflater mInflater;
private Context mContext;
private int lastPosition;
/**
* Holds elements in a view
*/
static class ViewHolder {
TextView make;
TextView model;
TextView stock;
}
public CustomAdapter(Context context, ArrayList<SearchModel> results) {
searchArrayList = results;
mContext = context;
mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return searchArrayList.size();
}
@Override
public Object getItem(int position) {
return searchArrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
String make = searchArrayList.get(position).getMake();
String model = searchArrayList.get(position).getModel();
String stock = searchArrayList.get(position).getStock();
final View result;
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder();
holder.make = (TextView) convertView.findViewById(R.id.tv_list_item_make);
holder.model = (TextView) convertView.findViewById(R.id.tv_list_item_model);
holder.stock = (TextView) convertView.findViewById(R.id.tv_list_item_stock);
result = convertView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
result = convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext,
(position > lastPosition) ? R.anim.load_down_anim : R.anim.load_up_anim);
result.startAnimation(animation);
lastPosition = position;
holder.make.setText(make);
holder.model.setText(model);
holder.stock.setText(stock);
return convertView;
}
}
MainActivity.java
(Only the onCreate
method)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
databaseReference.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
String make = snapshot.child("make").getValue(String.class);
String model = snapshot.child("model").getValue(String.class);
String stock = snapshot.child("stock").getValue(Long.class).toString();
SearchModel searchModel = new SearchModel(make, model, stock);
searchList.add(searchModel);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), searchList);
mListView = (ListView) findViewById(R.id.lv_searches);
mListView.setAdapter(customAdapter);
}
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
Related Topics
Base 64 Encode and Decode Example Code
Will System.Currenttimemillis Always Return a Value ≫= Previous Calls
Servlet Returns "Http Status 404 the Requested Resource (/Servlet) Is Not Available"
How to Convert a String to an Int in Java
What's Wrong With Overridable Method Calls in Constructors
How to Check If a String Is Numeric in Java
Why Is 128==128 False But 127==127 Is True When Comparing Integer Wrappers in Java
How to Count the Number of Occurrences of a Char in a String
Calling Non-Static Method in Static Method in Java
Custom Listview Adapter Getview Method Being Called Multiple Times, and in No Coherent Order
How to Change the Decimal Separator of Decimalformat from Comma to Dot/Point
Technically What Is the Main Difference Between Oracle Jdk and Openjdk
How to Fix Java.Lang.Unsupportedclassversionerror: Unsupported Major.Minor Version
Java Generics Type Erasure: When and What Happens
Validating Input Using Java.Util.Scanner