且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么是firebase以及如何在Android中使用它?

更新时间:2022-06-10 05:03:05

更新:自从Google I / O 2016以来,Firebase已经有了一些重大更新。以下是与旧服务相关的信息。



此处是Firebase团队成员。

Update: Since Google I/O 2016 there have been some major updates to Firebase. Below is information related to the legacy service.

Firebase team member here.

Firebase是一个移动和网络应用平台。

Firebase is a platform for mobile and web apps.

Firebase有三项主要服务:

There's three main services to Firebase:


  • 实时数据库

  • 身份验证

  • 静态托管

要编写Android应用程序,您需要下载Android SDK。如果您使用的是Android Studio 1.4,则可以转到文件>设置Firebase。项目结构>云。然后点击Firebase复选框。

For writing an Android app you need to download the Android SDK. If you have Android Studio 1.4 you can setup Firebase by going to File > Project Structure > Cloud. Then click the Firebase checkbox.

每个Firebase应用都有一个名称,即用于在URL中访问您的数据库。数据以JSON格式存储在Firebase中。每个部分都有一个映射到其位置的URL。要获取或保存数据到该位置,请创建Firebase参考。

Every Firebase app has a name, and that is used to in a URL to access your database. Data is stored in Firebase in JSON. Each piece has a URL mapped to its location. To get or save data to that location you create a Firebase reference.

// Create a reference to the Firebase database
Firebase ref = new Firebase("https:<MY-FIREBASE-APP>.firebaseio.com/data");
// Save Data
ref.setValue("Hello"); 
// Sync data
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        System.out.println(snapshot.getValue());
    }
    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("The read failed: " + firebaseError.getMessage());
    }
});



FirebaseUI



Firebase SDK很好保存和检索数据,但它与Android SDK组件无关,如 ListAdapter s。为此,您可以使用 FirebaseUI库

FirebaseUI

The Firebase SDK is good at saving and retrieving data, but it is agnostic of Android SDK components like ListAdapters. For that you can use the FirebaseUI library.

FirebaseUI允许您快速将常用UI元素连接到Firebase数据库以进行数据存储。以下是使用FirebaseUI和 FirebaseListAdapter 的示例。

FirebaseUI allows you to quickly connect common UI elements to the Firebase database for data storage. Below is an example of using FirebaseUI with a FirebaseListAdapter.

mAdapter = new FirebaseListAdapter<ChatMessage>(this, ChatMessage.class, android.R.layout.two_line_list_item, ref) {
    @Override
    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());

    }
};
messagesView.setListAdapter(mAdapter);

这只是一切的要点。 Firebase 文档非常全面(如果我这样做,和人类可读)我自己)。

That's just the gist of everything. The documentation of Firebase is pretty comprehensive (and human readable if I do so myself).