Skip to content

Firebase

kiryeonpark edited this page Jun 23, 2020 · 3 revisions

Firebase

Firebase Realtime Database is a cloud hosting database. Data is stored in JSON and synchronized in real time to all connected clients. Developing cross-platform apps with iOS, Android, and JavaScript SDKs ensures that all clients share one real-time database instance and receive the latest data with automatic updates. Firebase Realtime Database Security Rules, a flexible expression-based rules language provided by Realtime Database, allows you to define the structure of your data and the conditions under which it can be read from or written to. Developers can integrate with Firebase Authentication to define users' access to and access to data. The real-time database is a NoSQL database, and is designed around the execution speed of the job, so you can build an excellent real-time environment that can be used comfortably and smoothly by millions of users in real time.

Add Firebase to your Android project

  1. Connect to firebase console homepage https://console.firebase.google.com/

  2. Select 'Add Project'

image

  1. After entering the project name, click the Next button to create the project

  2. Click'Get started by adding an app' - select Android

image

  1. Enter the package name, app nickname, and SHA-1 of the app to be registered.

image

  1. Download google-services.json file, and put the file in the path (Project - App) described on the screen.

image

  1. Set build.gradle(Project)
buildscript {
    
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'
        classpath 'com.google.gms:google-services:4.3.3'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
  1. Set build.gradle(App), then Sync
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
    
dependencies {
   ...
        
    implementation 'com.google.firebase:firebase-database:19.2.0'
    implementation 'com.google.firebase:firebase-auth:19.1.0'
    implementation 'com.google.firebase:firebase-core:17.2.1'
}
  1. Select 'Tools - Firebase', then click 'Realtime Database - Save and retrieve data'

  2. Check if both 1 and 2 are connected.

image

Using firebase data for maps

reference : https://firebase.google.com/docs/android/setup?hl=ko

image

<FirebasePost.java>

  1. Declare items to be imported from the database as variables, and initialize null.
public String addr1 = null, cat3 = null, contentid = null, contenttypeid = null,
    	    firstimage = null, firstimage2 = null, mapx = null, mapy = null,
    	    mlevel = null, tel = null, placeTitle = null;
  1. Define the constructor.
public FirebasePost() { }

public FirebasePost(String addr1, String cat3, ..., String placeTitle) {
        this.addr1 = addr1;
        this.cat3 = cat3;
        ...
        this.placeTitle = placeTitle;
}
  1. Define mapping method using hash map.
public Map<String, Object> toMap() {
        HashMap<String, Object> result = new HashMap<>();

        result.put("addr1", addr1);
        result.put("cat3", cat3);
        ...
        result.put("placeTitle", placeTitle);

        return result;
}

<MyCallback.java>

  1. Define MyCallback interface.
public interface MyCallback {
    void onCallback(String value);
}

<FirebaseRead.java>

  1. Create arraylist to store index and data
static ArrayList<String> arrayIndex =  new ArrayList<String>();
static ArrayList<String> arrayData = new ArrayList<String>();
  1. Define ReadDB method. This method references a database and stores the data as a String. Then split this and store it in the arraylist defined in #1. At this time, the parameter is a callback interface. (Asynchronous call)
public void ReadDB(final MyCallback myCallback) { ... }

2-1. Declare DatabaseReference variables.

DatabaseReference database = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = database.child("place_list"); // Database title

2-2. Create addValueEventListner for store the data. After getting data from the database, return it using callback.

ref.addValueEventListener(new ValueEventListener() {
           @Override
           public void onDataChange(DataSnapshot dataSnapshot) {
                   for(DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                           String key = postSnapshot.getKey();
                           FirebasePost get = postSnapshot.getValue(FirebasePost.class);
                           String[] info = {get.mapy, get.mapx, get.placeTitle, get.addr1, get.firstimage};
                           String result = info[0] + "," + info[1] + "," + info[2] + "," + info[3] + "," + info[4] + "," + key;
                           arrayData.add(result);
                           arrayIndex.add(key);
                   
                           myCallback.onCallback(result);
                  }
           }

           @Override
           public void onCancelled(DatabaseError databaseError) {
               System.out.println("The read failed: " + databaseError.getCode());
           }
});

<MapFragment.java>

  1. To display the data on the map, we create an asynctask.
private class task extends AsyncTask<Void, String, Void> {...}
  1. In the task class, define Override methods.
@Override protected void onPreExecute() { }
@Override protected Void doInBackground(Void... params) { }
@Override protected void onProgressUpdate(String... values) { }
@Override protected void onPostExecute(Void aVoid) { }

2-1. doInBackground Create a firebaseRead object, and store the data from the database through the oncallback method in a string value.

FirebaseRead firebaseRead = new FirebaseRead();
firebaseRead.ReadDB(new MyCallback() {
        @Override
        public void onCallback(String value) {
                publishProgress(value);
        }
});
return null;

2-2. onProgressUpdate Split the string value, and store the desired information in a variable.

String[] mapValue = values[0].split(",");
Double latitude = Double.valueOf(mapValue[0]);
Double longitude = Double.valueOf(mapValue[1]);
String msg = mapValue[2];

Then, in your map, process it using the imported data.