我尝试使用其他人的代码从 firebase 接收数据,但应用程序将被强制停止。我不明白他们的代码,因为我在 Android 开发方面还是新手。这里我的代码只显示 logcat 中的数据,但我会将其显示到 ListView 中,请帮助我,谢谢。
这是 xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:textAlignment="center"
android:textSize="25sp"
android:text="Time Table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tvUserInfo"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listview"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="11dp" />
</LinearLayout>
这是java类:
DatabaseReference dref;
ListView listview;
ArrayList<String> list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Time");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds.child("email").getValue(String.class);
String time = ds.child("time").getValue(String.class);
Log.d("TAG", email + " / " + time); // logcat check value
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
}
This picture is the firebase value that i want to display in list view (email and time)
我想要做的事情是在 ListView 中显示来自 firebase 的数据
最佳答案
您可以使用FirebaseListAdapter用于在列表中显示数据。
喜欢:
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);
关于java - 如何在 ListView 中显示firebase数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51888371/