如何从Firebase检索和显示数据到ListView?

时间:2017-03-12 22:39:53

标签: android firebase firebase-realtime-database

我已经漫游YouTube和Stack Overflow以寻找从以下数据库中检索 teacherName 值的方法:

Database

我还没有为我的问题找到解决方案,无论我使用的是Value还是ChildEventListener。这是我使用的代码:

public class ViewTeachersActivity extends AppCompatActivity {

// Define the Teacher Firebase DatabaseReference
private DatabaseReference databaseTeachers;

// Define a String ArrayList for the teachers
private ArrayList<String> teachersList = new ArrayList<>();

// Define a ListView to display the data
private ListView listViewTeachers;

// Define an ArrayAdapter for the list
private ArrayAdapter<String> arrayAdapter;

/**
 * onCreate method
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_teachers);

    // Associate the Teacher Firebase Database Reference with the database's teacher object
    databaseTeachers = FirebaseDatabase.getInstance().getReference();
    databaseTeachers = databaseTeachers.child("teachers");

    // Associate the teachers' list with the corresponding ListView
    listViewTeachers = (ListView) findViewById(R.id.list_teachers);

    // Set the ArrayAdapter to the ListView
    arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teachersList);
    listViewTeachers.setAdapter(arrayAdapter);

    // Attach a ChildEventListener to the teacher database, so we can retrieve the teacher entries
    databaseTeachers.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            // Get the value from the DataSnapshot and add it to the teachers' list
            String teacher = dataSnapshot.getValue(String.class);
            teachersList.add(teacher);

            // Notify the ArrayAdapter that there was a change
            arrayAdapter.notifyDataSetChanged();
        }

        @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) {

        }
    });
}

我也尝试在ChildEventListener中使用for循环,但这也没有用。有谁能指出我的解决方案?

2 个答案:

答案 0 :(得分:2)

String teacher = dataSnapshot.getValue(String.class);

你没有String。你有一个对象。

所以,你需要一个Java类

public class Teacher {
    String teacherID, teacherEmail; // etc. all fieldnames in the database

    public Teacher() {
    }

    // getters

    // setters

    @Override
    public String toString() {
        return this.teacherID + ": " + this.teacherEmail;
    }
}

然后,从Firebase,您可以将快照映射到该类并添加到适配器。

Teacher teacher = (Teacher) dataSnapshot.getValue(Teacher.class);
String teacherString = String.valueOf(teacher);
arrayAdapter.add(teacherString);

参考:Firebase-UI | Using Firebase to populate ListView

答案 1 :(得分:0)

由于您的问题不清楚是否要收听所有教师姓名或只是一个。

这是获取所有教师名称的简便方法。对于/ teachers下的每个条目(uuid键),并为此查询添加一个监听器:

FirebaseDatabase.getInstance()
    .getReference()
    .child("teachers")
    .orderByChild("teacherName")
    .addValueEventListener(listener); //listener example below


ValueEventListener listener = new new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            dataSnapshot.getChildren().forEach(

               // assuming you are using RetroLambda, if not, implement Consumer<? super T> action
                // update change ListView here
            );
        }


        @Override
        public void onCancelled(FirebaseError firebaseError)
        {
            //handle errors here
        }
    });

如果您正在寻找特定的教师姓名,请发表评论,然后我会对其进行更改。此外,我还没有在移动设备上测试语法,所以将其视为伪代码,但它应该让你朝着正确的方向前进

查看Firebase查询documentation,它非常简单,截至目前,只需几行代码即可完成强大功能。在搜索时要小心过时的教程,Firebase在过去的〜1年内添加了其所有功能