From setting up Firebase's Realtime Database to simple data entry (Android app)

Overview

It is assumed that you have a Firebase account. </ font> The official explanation of Firebase Realtime Database is here. Briefly, it is a simple database specialized for real-time updates, and it seems that it is often used for miscellaneous things such as chat.

How to get started with Realtime Database

Select Tools → Firebase from the menu above Android Studio. Since Assistant is displayed, select Realtime Database. 1.png

You will see a link with instructions on how to set it up. Start Guide Even if you do not read this, the procedure is written with numbers, It used to be set up with the click of a button. (As a result, I had a hard time this time ...) 2.png

Realtime Database settings

①Connected your app to Firebase When you click [Connected to Firebase], the Google account selection screen will be displayed, and if you allow authentication, a project will be automatically created and linked to Firebase. Go to Firebase and you should see your project.

②Add the Realtime Database to your app Click [Add the Realtime Database to your app] and the following will be added automatically.

build.gradle(project-level)


// Add Firebase Gradle buildscript dependency
classpath 'com.google.gms:google-services:4.0.1'

app/build.gradle


// Add Firebase plugin for Gradle
apply plugin: 'com.google.gms.google-services'

// build.gradle will include these new dependencies:
compile 'com.google.firebase:firebase-database:16.0.1:15.0.0'

If you build in this state, it will not compile for some reason. implementation 'com.android.support:appcompat-v7:27.1.1' Looking at the error content of the red line of

---------------------------------- All com.android.support libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 27.1.1, 26.1.0. Examples include com.android.support:animated-vector-drawable:27.1.1 and com.android.support:support-media-compat:26.1.0 less... (Ctrl+F1) There are some combinations of libraries, or tools and libraries, that are incompatible, or can lead to bugs. One such incompatibility is compiling with a version of the Android support libraries that is not the latest version (or in particular, a version lower than your targetSdkVersion). Issue id: GradleCompatible ---------------------------------- implementation 'com.android.support:appcompat-v7:27.1.1' When implementation 'com.google.firebase:firebase-database:16.0.1:15.0.0' It is said that another version of the same library was found inside.

Since firebase-database contains older libraries, I searched for the latest and got the same result. (See) Firebase Android Release Notes Realtime Database com.google.firebase:firebase-database:16.0.3

There is no choice but to switch to app compat. implementation 'com.android.support:appcompat-v7:27.1.1' ↓ implementation 'com.android.support:appcompat-v7:26.1.0' Changed compileSdkVersion and targetSdkVersion to 26.

Then the following error ---------------------------------- Could not find firebase-database-15.0.0.jar (com.google.firebase:firebase-database:16.0.1). ---------------------------------- I heard that there is no such java archive, and while wondering what it means to add it automatically, Start Guide When you read

app/build.gradle


implementation 'com.google.firebase:firebase-database:16.0.3'

And the latest one.

Then

app/build.gradle


implementation 'com.google.firebase:firebase-core:16.0.4'

If you also include it, a Warning will appear, so follow it. It seems that Google's developer blog wrote that the problem of different internal library versions around here will be fixed soon.

③Configure Firebase Database Rules There is a link about authentication and a link for creating DB rules. Firebase Authentication Try using database rules

Authentication is required to make the user's personal information highly confidential. I don't think it's necessary to use it for simple chats or game rankings. (maybe)

Now, access the Firebase console with your browser and click Database on the left tab. Click Create Database. Created in test mode.

3.png Then the tab is Cloud Firestore [Beta], so Please use Realtime Database. 4.png

Anyway, the habit of creating DB rules is so great that it is difficult to create. It cannot be designed like a relational DB. See the links below for detailed rules.


〇 About Android ·guide Start Guide Database Structure (https://firebase.google.com/docs/database/android/structure-data) Reading and writing data on Android Working with lists of data on Android Enable offline features on Android (https://firebase.google.com/docs/database/android/offline-capabilities)

·reference Package Summary

〇About security and rules ·guide About Firebase Realtime Database Rules Try using database rules Data Security (https://firebase.google.com/docs/database/security/securing-data) User-based security (https://firebase.google.com/docs/database/security/user-security) Resolve insecurity Index your data (https://firebase.google.com/docs/database/security/indexing-data) Manage Firebase Realtime Database rules with REST (https://firebase.google.com/docs/database/rest/app-management)

·reference Firebase Database Security Rules API Firebase Security Rules Regular Expressions Firebase Security Rules for Cloud Storage Reference


Create a simple rule for the time being

rule


{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    "info":{
      "user": {
        ".read": true,
        ".write": true,
        "name": {
          ".validate": "newData.isString()"
        },
        "age": {
          ".validate": "newData.isNumber()"
        }
      }
    }
  }
}

It is a rule that just created user under info and name (String type) and age (Number type) under it. The reason for deepening the hierarchy is to make the rules for specifying paths easier to understand.

④Write to your database I will write the data immediately. Reading and writing data on Android Is easy to understand. It is possible to register the data individually, but it is quite troublesome, so it is easier to register and acquire by class.

** 〇 Create class ** `(Note) The condition is that the class that defines the object has a default constructor that takes no arguments and a public getter for the property to be assigned. ``

User


public static class User {
    public String name;
    public Integer age;

    //Empty constructor declaration required
    public User() {
    }

    public User(String _name, Integer _age) {
        name = _name;
        age = _age;
    }
    public String getName(){
        return name;
    }
    public Integer getAge(){
        return age;
    }
}

** 〇 Data registration **

register


User user = new User( "Yamada Taro",30 );
//Get an instance
FirebaseDatabase database = FirebaseDatabase.getInstance();

//Get reference by specifying file path
DatabaseReference refName = database.getReference("info/user");
//Register data
refName.setValue(user);

Looking at the Firebase data 5.png

You are well registered.

⑤Read from your database Read the data. Reading and writing data on Android than Guide → Administration → Get data May be easier to understand. The example sentences in the document are cluttered and difficult to understand ...

To write it simply, by setting an event listener, you can get all or update. For the time being, only all acquisitions are listed.

** 〇 Data acquisition **

reader


//Get an instance
FirebaseDatabase database = FirebaseDatabase.getInstance();
//Get reference by specifying file path
final DatabaseReference refUser = database.getReference("info");
refUser.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot dataSnapshot, String prevChildKey) {

        User user = dataSnapshot.getValue(User.class);
        Log.w( "DEBUG_DATA", "user.name = " + user.name);
        Log.w( "DEBUG_DATA", "user.age = " + user.age);
    }

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

⑥Optional: Configure ProGuard Be careful when setting a pro guard. I'm not using it, so I'll omit it ...

When using Firebase Realtime Database in your app along with ProGuard you need to consider how your model objects will be serialized and deserialized after obfuscation. If you use DataSnapshot.getValue(Class) or DatabaseReference.setValue(Object) to read and write data you will need to add rules to the proguard-rules.pro file:

----- # Add this global rule -keepattributes Signature

# This rule will properly ProGuard all the model classes in # the package com.yourcompany.models. Modify to fit the structure # of your app. -keepclassmembers class com.yourcompany.models.** { *; } -----

⑦Preapre for Launch Check it in Checklist. No big deal.

⑧Next Steps The content is that you can use multiple databases. Scale with multiple databases I've heard that Mercari has combined a significant number of databases to create a huge amount of chat. It's a really serverless era.

Only the basic version has become long. As it is, it is just inputting and acquiring simple data, and it seems that it is useless. The advanced version will be described later.

Recommended Posts

From setting up Firebase's Realtime Database to simple data entry (Android app)
Create a clear time ranking in Firebase's Realtime Database (Android app)
Java to fly data from Android to ROS of Jetson Nano
Android app to select and display images from the gallery
I tried to create a simple map app in Android Studio