📌  相关文章
📜  如何在Android ListView中从Firebase实时数据库检索数据?

📅  最后修改于: 2021-05-10 14:20:55             🧑  作者: Mango

Firebase实时数据库为我们提供了一项功能,可在几毫秒内对应用程序内的数据进行实时更新。借助Firebase,您可以向用户提供实时更新。在本文中,我们将研究Android中ListView的Firebase实时数据库的实现。在此ListView中,我们将能够实时添加和删除列表项。因此,让我们着手在ListView中实现Firebase实时数据库。

我们将在本文中构建什么?

我们将创建一个简单的应用程序,在其中创建一个ListView,并在该ListView中,从Firebase Realtime数据库中获取数据。在Firebase中,我们可以根据需要更新或删除列表项,并且数据将实时更新。注意,我们将使用Java语言实现该项目

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

第2步:将您的应用连接到Firebase

创建新项目后。导航到顶部栏上的“工具”选项。在里面单击Firebase。单击Firebase后,您可以在屏幕快照中看到下面提到的右列。

在该列内,导航到Firebase实时数据库。单击该选项,您将在“将应用程序连接到Firebase”和“将Firebase实时数据库添加到您的应用程序”中看到两个选项。单击立即连接,您的应用程序将连接到Firebase。之后,单击第二个选项,现在您的应用已连接到Firebase。

完成此过程后,您将看到以下屏幕。

现在,验证您的应用是否已连接到Firebase。转到您的build.gradle文件。导航至应用程序> Gradle脚本> build.gradle文件,并确保在依赖项部分中添加了以下依赖项。

如果上述依赖项未添加到“依赖项”部分中。添加此依赖性并同步您的项目。现在,我们将转向应用程序的XML部分。

步骤3:使用activity_main.xml文件

转到activity_main.xml文件,并参考以下代码。以下是activity_main.xml文件的代码。

XML


  
    
    
  


XML


Java
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our list view.
    private ListView coursesLV;
      
    // creating a new array list.
    ArrayList coursesArrayList;
      
    // creating a variable for database reference.
    DatabaseReference reference;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing variables for listviews.
        coursesLV = findViewById(R.id.idLVCourses);
          
        // initializing our array list
        coursesArrayList = new ArrayList();
          
        // calling a method to get data from
        // Firebase and set data to list view
        initializeListView();
    }
  
    private void initializeListView() {
        // creating a new array adapter for our list view.
        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, coursesArrayList);
  
        // below line is used for getting reference
        // of our Firebase Database.
        reference = FirebaseDatabase.getInstance().getReference();
         
        // in below line we are calling method for add child event 
        // listener to get the child of our database.
        reference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when new child is added to 
                // our data base and after adding new child
                // we are adding that item inside our array list and
                // notifying our adapter that the data in adapter is changed.
                coursesArrayList.add(snapshot.getValue(String.class));
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when the new child is added.
                // when the new child is added to our list we will be 
                // notifying our adapter that data has changed.
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {
                // below method is called when we remove a child from our database.
                // inside this method we are removing the child from our array list 
                // by comparing with it's value.
                // after removing the data we are notifying our adapter that the 
                // data has been changed.
                coursesArrayList.remove(snapshot.getValue(String.class));
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when we move our 
                // child in our database.
                // in our code we are note moving any child.
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // this method is called when we get any 
                // error from Firebase with error.
            }
        });
        // below line is used for setting 
        // an adapter to our list view.
        coursesLV.setAdapter(adapter);
    }
}


步骤4:在您的AndroidManifest.xml文件中添加互联网权限

在AndroidManifest.xml文件中添加Internet权限。

XML格式



步骤5:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
  
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
  
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
  
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our list view.
    private ListView coursesLV;
      
    // creating a new array list.
    ArrayList coursesArrayList;
      
    // creating a variable for database reference.
    DatabaseReference reference;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing variables for listviews.
        coursesLV = findViewById(R.id.idLVCourses);
          
        // initializing our array list
        coursesArrayList = new ArrayList();
          
        // calling a method to get data from
        // Firebase and set data to list view
        initializeListView();
    }
  
    private void initializeListView() {
        // creating a new array adapter for our list view.
        final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, coursesArrayList);
  
        // below line is used for getting reference
        // of our Firebase Database.
        reference = FirebaseDatabase.getInstance().getReference();
         
        // in below line we are calling method for add child event 
        // listener to get the child of our database.
        reference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when new child is added to 
                // our data base and after adding new child
                // we are adding that item inside our array list and
                // notifying our adapter that the data in adapter is changed.
                coursesArrayList.add(snapshot.getValue(String.class));
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when the new child is added.
                // when the new child is added to our list we will be 
                // notifying our adapter that data has changed.
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildRemoved(@NonNull DataSnapshot snapshot) {
                // below method is called when we remove a child from our database.
                // inside this method we are removing the child from our array list 
                // by comparing with it's value.
                // after removing the data we are notifying our adapter that the 
                // data has been changed.
                coursesArrayList.remove(snapshot.getValue(String.class));
                adapter.notifyDataSetChanged();
            }
  
            @Override
            public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName) {
                // this method is called when we move our 
                // child in our database.
                // in our code we are note moving any child.
            }
  
            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                // this method is called when we get any 
                // error from Firebase with error.
            }
        });
        // below line is used for setting 
        // an adapter to our list view.
        coursesLV.setAdapter(adapter);
    }
}

将此代码添加到您的应用程序之后。现在转到Firebase,然后单击右上角的“转到控制台”选项。

单击此屏幕后,您将看到下面的屏幕,其中包含您选择的项目的所有项目。

在该屏幕内,单击左侧窗口中的n实时数据库。

单击此选项后,您将看到右侧的屏幕。在此页面上,单击顶部栏中的“规则”选项。您将看到以下屏幕。

在此项目中,我们添加了适用于读取和写入的规则,因为我们没有使用任何身份验证来验证用户。因此,我们目前将其设置为true以测试我们的应用程序。更改规则后。单击右上角的“发布”按钮,您的规则将保存在此处。现在再次回到“数据”选项卡。现在,我们将从Firebase本身将数据手动添加到Firebase。

第6步:在Firebase控制台中添加数据

在Firebase数据库内部,我们将看到的父节点是父节点。在此父项中,我们必须添加子项。该子项将显示在我们的ListView中。我们将在数据库中添加新的子项。为我们的列表视图添加数据。我们只需要单击右侧的“ +”选项来添加项目,然后将其添加到我们的数据库中即可。以类似的方式将多个项目添加到数据库中。这些项目将显示在我们的ListView中。

上面提到的是您将了解如何在列表视图中添加单个项目的图像。同样,在数据库中添加多个项目,您将看到以下屏幕。

添加此数据后,运行您的应用程序,然后查看该应用程序的输出。运行您的应用程序后,更新Firebase中的数据。您可以添加,删除任何子项或更新任何子项,您将在ListView中看到“实时更新”。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!