I'm trying to play a bit with Firebase and Android.
I have one RegisterActivity
, and one MainActivity
.
My current flow is - start with MainActivity
- check if user is registered, if not, call RegisterActivity
- after registeration call MainActivity
.
I'm having trouble with where to put the Firebase.setAndroidContext()
call.
I have 2 questions:
Application
or once in each Activty
?Thank you all, Giora.
To quote (step 4 of) the Firebase quickstart documentation:
The Firebase library must be initialized once with an Android
Context
. This must happen before any Firebase reference is created or used.
Create MyApplication.java
:
public class MyApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
//Previous versions of Firebase
Firebase.setAndroidContext(this);
//Newer version of Firebase
if(!FirebaseApp.getApps(this).isEmpty()) {
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
}
And update name parameter value in your AndroidManifest.xml
:
<application
android:label="@string/app_name"
android:name=".MyApplication">
...
</application>
As seen in the sample applications of Firebase you should place it inside your Application
.
package com.firebase.androidchat;
import com.firebase.client.Firebase;
/**
* @author Jenny Tong (mimming)
* @since 12/5/14
*
* Initialize Firebase with the application context. This must happen before the client is used.
*/
public class ChatApplication extends android.app.Application {
@Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this);
}
}
Source
Firebase.getAndroidContext()
After setting the Application context once you can use it where ever you need it. You can retrieve it as often as you like, everywhere.
I would also recommend to use the Firebase.getAndroidContext()
instead of storing it into variables to prevent MemoryLeaks
I do not know FireBase but i know Android.. A Context
is a global information about an application environment. Your Activity
is a Context
so i am pretty sure Firebase.getAndroidContext()
retrieves your Application Context
which is getApplicationContext()
, Since that seems sensible.
Should I only call this function once in Application or once in each Activty?
call it whenever you need a Context
with respects to FireBase codes- but i think will suit best if you call it in your Application
class
If the answer for question 1 is only once, then where should I put it ?
what if its not once? where do you call it? i guess you will call it anywhere you need Context
right? so do that irrespective of question 1's answer, but you can fall on Class.this
, getBaseContext()
or View.getContext()
anytime
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With