Where to put Firebase.setAndroidContext() function
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
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>
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