I'm trying to have a remote config parameter using the new Remote Config feature of Firebase, and I'm having an issue.
Here's my Remote Config console:
I'm doing a fetch and update in my Application's onCreate():
final FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.getInstance();
remoteConfig.fetch().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
remoteConfig.activateFetched();
}
}
});
And here's how I'm reading it:
FirebaseRemoteConfig remoteConfig = FirebaseRemoteConfig.getInstance();
String value = remoteConfig.getString("active_subscriptions");
Value is returning null.
If I call remoteConfig.getInfo().getLastFetchStatus(), it returns LAST_FETCH_STATUS_SUCCESS, so it seems the fetch is going through successfully.
Any idea why my value is blank?
Workaround found! See below
I'm running into the "silent completion" thing - I call "fetch" but onComplete, onSuccess, or onFailure listeners never fire. I tried moving it to an activity onCreate, and still nothing happened, and therefore, the config items never get loaded from the server. I've got Developer Mode enabled, and am calling fetch with a cache value of 0.
I was able to (once) put a breakpoint on the line "public void onComplete(#NonNull Task task) {", which got hit, and then I was able to step through and the onComplete fired. I was then unable to reproduce this same result any other way, including doing the same thing (I think) a second time.
Seems like a timing or concurrency issue, but that makes little sense, given this is an asynchronous call.
Workaround
If you fetch from Activity#onResume (or, I presume, Activity#onStart), it works perfectly. Calling fetch from Activity#onCreate or Application#onCreate results in a call that seemingly never gets handled, and in fact, performance of the app degrades noticeably after the fetch begins, so I think there's a looper running or something.*
Workaround #2
If you really want this to run from Application#onCreate (which I do), this seems to work as well:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Run mFirebaseRemoteConfig.fetch(timeout) here, and it works
}
}, 0);
You're likely hitting the caching in Remote Config. The way it works is that Config will cache incoming items locally, and return them. So your last (cached) fetch status was probably before the value was defined, and we get a cached blank value.
You can control the cache expiry, but if you fetch too often you risk getting throttled.
Because this is a common development problem though, there is a developer mode that lets you request more rapidly (for small groups of users):
FirebaseRemoteConfigSettings configSettings =
new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
FirebaseRemoteConfig.getInstance().setConfigSettings(configSettings);
When you call fetch you can then pass a short cache expiration time
long cacheExpiration = 3600;
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
if (mFirebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
cacheExpiration = 0;
}
mFirebaseRemoteConfig.fetch(cacheExpiration)
.addOnCompleteListener(new OnCompleteListener<Void>() {
// ...
});
That's how its done in the quickstart sample if you want a full reference.
Found the problem.
After adding some logging, I found that the fetch job's onComplete() was never being called. I moved the fetch from my Application's onCreate to a fragment's, and now it works properly!
(Ian Barber, this might be something to look into or clarify, as the logs indicated that Firebase was initialized without an issue when it was in the Application, and the fetches were silent failures.)
I also encountered this problem. Turns out I hadn't seen the 'Publish' button in the the Firebase console. :facepalm:
I had the same problem and no workarounds were helpful in my case. The problem was in the testing device. I used emulator without installing Google Mobile Services, because of this the Complete event was not fired. I tried my phone with GMS and everything worked great. Good luck.
First thing in such case is check if you have the correct firebase config and you are connected to firebase .If you have android studio 2.2 got to Tools->Firebase->RemoteConfig - Connect to Firebase and see if you get a notification saying connected.Once Connected do the following in your code:
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
/** NOTE: At this point, your app can use in-app default parameter values.To use in-app
* default values,skip the next section. You can deploy your app without setting
* parameter values on the server,and then later set values on the server to
* override the default behavior and appearance of your app.
*/
mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(true)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
And then for fetching config do the following
long cacheExpiration = 2000; // Can increase this usually 12hrs is what is recommended
/** If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from
* the server.*/
if (mFirebaseRemoteConfig.getInfo().getConfigSettings().isDeveloperModeEnabled()) {
cacheExpiration = 0;
}
/** cacheExpirationSeconds is set to cacheExpiration here, indicating that any previously
* fetched and cached config would be considered expired because it would have been fetched
* more than cacheExpiration seconds ago. Thus the next fetch would go to the server unless
* throttling is in progress. The default expiration duration is 43200 (12 hours).
*/
mFirebaseRemoteConfig.fetch(cacheExpiration)//TODO Bring this from a config file
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(TAG, "Firebase Remote config Fetch Succeeded");
// Once the config is successfully fetched it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
} else {
Log.d(TAG, "Firebase Remote config Fetch failed");
}
showRemoteConfig();
}
});
Run your App and check in logs " Firebase Remote config Fetch Succeeded ". If you see the same your remote configs are loaded and activated.
I've used a similar code like #Ian Barber (copy):
FirebaseRemoteConfigSettings configSettings =
new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
FirebaseRemoteConfig.getInstance().setConfigSettings(configSettings);
My problem was the "BuildConfig.DEBUG", it returns false. So it takes the value 1h in cache until it was fetched again!
I had a problem that Firebase Remote Config didn't fire OnCompleteListener with fetch(0), but with fetch() did.
Looking at FirebaseRemoteConfig.fetch() does not trigger OnCompleteListener every time, I found that the first answer was working sometimes even with fetch(0). Then I again set 3600 seconds for interval, as errors continued to appear:
override fun onPostResume() {
super.onPostResume()
// Initialize FirebaseRemoteConfig here.
...
firebaseRemoteConfig.fetch(3600).addOnCompleteListener { task ->
if (task.isSuccessful) {
firebaseRemoteConfig.activateFetched()
//calling function to check if new version is available or not
checkForUpdate(currentVersionCode, firebaseRemoteConfig.getString(VERSION_CODE_KEY))
} else
Toast.makeText(this#MainActivity, "Someting went wrong please try again",
Toast.LENGTH_SHORT).show()
}
}
Well in my case, I am able to receive control in addOnCompleteListener for fetch method but I have fetched values firebaseRemoteConfig just after I called firebaseRemoteConfig.activate(), so when I have tried to get the values from firebaseRemoteConfig it returns me previously saved values because firebaseRemoteConfig.activate() runs asynchronously and new values didn't saved before I am getting them from firebaseRemoteConfig, so I have added complete listener for activate() method also, Here:
firebaseRemoteConfig.fetch()
.addOnCompleteListener(activity, OnCompleteListener {
if (it.isSuccessful)
{
Log.d("task","success")
firebaseRemoteConfig.activate().addOnCompleteListener { // here I have added a listener
val base_url=firebaseRemoteConfig.getString("base_url")
Log.d("base url",base_url)
Toast.makeText(activity, "Base url: $base_url",Toast.LENGTH_SHORT).show()
}
}
else
{
Log.d("task","failure")
}
})
Does Android Studio's Build Variant match your intended Firebase project?
I work on a big project and the problem was buried in an unexpected place.
Long story short: the firebase application id(normally set through google-services.json) was changed through code:
FirebaseOptions.Builder builder = new FirebaseOptions.Builder();
builder.setApplicationId(applicationId);
builder.setApiKey(apiKey);
FirebaseOptions options = builder.build();
FirebaseApp.initializeApp(context, options);
The solution was to remove that code and let firebase use the info from "google-services.json".
Use fetchAndActivate instead of fetch
I was facing the same problem. After fetching, no listener get call for first time only. I try fetchAndActivate in single line and it works for me. Use below code
mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
#Override
public void onComplete(#NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
boolean updated = task.getResult();
Log.d(TAG, "Config params updated: " + updated);
Toast.makeText(MainActivity.this, "Fetch and activate succeeded",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Fetch failed",
Toast.LENGTH_SHORT).show();
}
displayWelcomeMessage();
}
});
It will fetch and activate immediately. You can find this way in official documentation here
Related
I have the below defined:
I first launch the app with the device's language (from Settings) set to English and it loads the lang-EN json.
If I go in the Settings of the device, change the language to French and restart the app, .fetch() will still return the lang-EN value. If I clear cache the app and restart it, it then loads the lang-FR value.
Doesn't .fetch() get ALL the remote config params and locally decide which to show the user? From the functionality i'm getting it seems that .fetch() only gets the parameter values only pertaining to the device at the moment of the call. Either that or there's a bug in the firebase code ... OR ... and i'm hoping this is the case, i'm doing something wrong.
This is how i'm initializing the singleton. Perhaps i'm missing something?
public void initialize(Context applicationContext) {
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setMinimumFetchIntervalInSeconds(5 * 60 * 60)//5 hours
.build();
getConfig().setConfigSettingsAsync(configSettings);
}
And yes, i have the latest version of the remote config sdk in the dependencies 19.2.0
fetch() is not enough.
To fetch parameter values from the Remote Config backend, call the fetch() method. Any values that you set in the backend are fetched and stored in the Remote Config object.
To make fetched parameter values available to your app, call the activate() method.
For cases where you want to fetch and activate values in one call, you can use a fetchAndActivate() request to fetch values from the Remote Config backend and make them available to the app:
mFirebaseRemoteConfig.fetchAndActivate()
.addOnCompleteListener(this, new OnCompleteListener<Boolean>() {
#Override
public void onComplete(#NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
boolean updated = task.getResult();
Log.d(TAG, "Config params updated: " + updated);
Toast.makeText(MainActivity.this, "Fetch and activate succeeded",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Fetch failed",
Toast.LENGTH_SHORT).show();
}
displayWelcomeMessage();
}
});
Because these updated parameter values affect the behavior and appearance of your app, you should activate the fetched values at a time that ensures a smooth experience for your user, such as the next time that the user opens your app
I'm trying to use Amazon Cognito Sync to remotely store and retrieve information about my user, and for that information to be synced across all devices that that user is logged into.
I'm following the tutorial here which shows how to create Dataset objects and how to use its get(), put(), and synchronize() methods.
After getting that working, I tried following the tutorial here which shows how to register a device for push notifications and subsequently subscribe to a Dataset that you want to keep synced. However, when I call
cognitoSyncManager.subscribeAll()
I get the following exception:
com.amazonaws.mobileconnectors.cognito.exceptions.SubscribeFailedException: Failed to subscribe to dataset
at com.amazonaws.mobileconnectors.cognito.internal.storage.CognitoSyncStorage.subscribeToDataset(CognitoSyncStorage.java:360)
at com.amazonaws.mobileconnectors.cognito.DefaultDataset.subscribe(DefaultDataset.java:604)
at com.amazonaws.mobileconnectors.cognito.CognitoSyncManager.subscribe(CognitoSyncManager.java:332)
at com.amazonaws.mobileconnectors.cognito.CognitoSyncManager.subscribeAll(CognitoSyncManager.java:319)
Caused by: com.amazonaws.services.cognitosync.model.ResourceNotFoundException: Failed to subscribe to dataset USER_INFORMATION, endpointArns do not exist (Service: AmazonCognitoSync; Status Code: 404; Error Code: ResourceNotFoundException; Request ID: 7e681e01-a872-11e7-9e5f-01c7f0419773)
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:712)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:388)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:199)
at com.amazonaws.services.cognitosync.AmazonCognitoSyncClient.invoke(AmazonCognitoSyncClient.java:864)
at com.amazonaws.services.cognitosync.AmazonCognitoSyncClient.subscribeToDataset(AmazonCognitoSyncClient.java:663)
at com.amazonaws.mobileconnectors.cognito.internal.storage.CognitoSyncStorage.subscribeToDataset(CognitoSyncStorage.java:357)
at com.amazonaws.mobileconnectors.cognito.DefaultDataset.subscribe(DefaultDataset.java:604)
at com.amazonaws.mobileconnectors.cognito.CognitoSyncManager.subscribe(CognitoSyncManager.java:332)
at com.amazonaws.mobileconnectors.cognito.CognitoSyncManager.subscribeAll(CognitoSyncManager.java:319)
In my Android app, I'm authenticating the user using Google Sign-In, which gives me the token that I need when creating my Cognito Credentials Provider, and I'm using Firebase Cloud Messaging for getting the token needed by Cognito Sync Manager. Here's the snippet of my code which results in the exceptions:
new Thread(new Runnable()
{
#Override public void run()
{
CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(getContext(), Utilities.getString(R.string.aws_cognito_identity_pool_id), Regions.US_EAST_1);
Map<String, String> loginsMap = new HashMap<>();
loginsMap.put("accounts.google.com", GoogleLoginManager.getInstance().getToken());
credentialsProvider.setLogins(loginsMap);
credentialsProvider.refresh();
cognitoId = credentialsProvider.getIdentityId();
isLoggedIn = !cognitoId.equals("");
if(isLoggedIn)
{
CognitoSyncManager cognitoSyncManager = new CognitoSyncManager(getContext(), Regions.US_EAST_1, credentialsProvider);
try
{
cognitoSyncManager.registerDevice("GCM", FirebaseInstanceId.getInstance().getId());
}
catch(RegistrationFailedException exception)
{
Log.e(exception);
}
catch(AmazonClientException exception)
{
Log.e(exception);
}
if(cognitoSyncManager.isDeviceRegistered())
{
try
{
cognitoSyncManager.subscribeAll();
}
catch(SubscribeFailedException exception)
{
Log.e(exception);
}
catch(AmazonClientException exception)
{
Log.e(exception);
}
}
}
}
}).start();
Any idea what I'm doing wrong? Following the tutorials and navigating the developer console have been a bit of an enigma for me, and I feel like there must be some core concept that I'm just not getting.
I finally figured it out. When calling cognitoSyncManager.registerDevice() I was passing FirebaseInstanceId.getInstance().getId() as the token instead of FirebaseInstanceId.getInstance().getToken(). Bleh.
Also, before calling cognitoSyncManager.registerDevice("GCM", FirebaseInstanceId.getInstance().getId()); I now call cognitoSyncManager.unregisterDevice(). Apparently, if you call registerDevice() in a previous run of the app and the registration wasn't actually successful, the CognitoSyncManager class still stores in SharedPreferences that it's registered, and thus will block all future calls to registerDevice() until unregisterDevice() is called.
I'm trying to set up Firebase Remote Config for my project.
I added Firebase via the Assistant. I added values to the server values on Google Cloud Console:
I've created default values xml in res/xml
<defaultsMap>
<!-- Strings-->
<entry >
<key>textView_send_text</key>
<value >your phrase goes here.</value>
</entry>
</defaultsMap>
Thats my MainActivity:
final private FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
protected void onCreate(Bundle savedInstanceState) {
//..code..
//fetch from Firebase
fetchAll();
}
private void fetchAll(){
final FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
mFirebaseRemoteConfig.setDefaults(R.xml.defaults);
mFirebaseRemoteConfig.fetch()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Fetch Succeeded",
Toast.LENGTH_SHORT).show();
mFirebaseRemoteConfig.activateFetched();
}else{
Toast.makeText(MainActivity.this, "Fetch Failed",
Toast.LENGTH_SHORT).show();
}
displayWelcomeMessage();
}
});
}
private void displayWelcomeMessage(){
String welcomeMessage = mFirebaseRemoteConfig.getString("textView_send_text");
Toast.makeText(this, welcomeMessage,
Toast.LENGTH_SHORT).show();
}
Toast output:
So Toast gets the value from xml/defaults not from the Cloud.
It'd be much appreciated if somebody found where I made a mistake.
For development testing, specify a cache expiration time of zero to force an immediate fetch:
mFirebaseRemoteConfig.fetch(0) // <- add the zero
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
...
});
Some tips the helped to me:
Don't forget to click "publish changes" in Firebase console after each value update
Uninstall and install the App before checking (Firebase may not fetch immediately)
Use mFirebaseRemoteConfig.fetch(0)
For what it worth I found that our firebase remote configs weren't downloading no matter what we tried - we are usually debugging while connected to a proxy (like Charles Proxy) and that was interrupting the firebase cloud update.
Once we connected to a non-proxied wifi connection we got the update.
You can also set your config to developer mode if running a debug build which will refresh values more often - but the proxy was our root problem.
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
In Flutter, I just changed the value of minimumFetchInterval to const Duration(hours: 0). I manually added an message to firebase and here I just get it. Here is my code;
await Firebase.initializeApp();
RemoteConfig remoteConfig = RemoteConfig.instance;
await remoteConfig.setConfigSettings(RemoteConfigSettings(
fetchTimeout: const Duration(seconds: 10),
minimumFetchInterval: const Duration(hours: 0),
));
RemoteConfigValue(null, ValueSource.valueStatic);
bool updated = await remoteConfig.fetchAndActivate();
if (updated) {
print("it is updated");
} else {
print("it is not updated");
}
print('my_message ${remoteConfig.getString('my_message')}');
Make sure your mFirebaseRemoteConfig.fetch() called only once. It gets throttled if you call it multiple times.
There is a default minimum time duration Intervals for firebase remote config fetching. According to the Firebase documentation, it is now 12 hours. During that default time interval gap, if you change the keys from Firebase remote config and if you don't uninstall the app, you don't get updated data. you will get updated data after passing default time intervals. If you need more frequent data changes, you can override fetch intervals from client side.
In my app, I simply try to retrieve a reading passage from my Firebase database by adding a ListenerForSingleValueEvent in the following code:
myRef.child("passages").child(passageNum).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("ON DATA CHANGE");
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("DATABASE ERROR");
FirebaseErrorHandler.handleDatabaseError(databaseError.getCode(), ReadingActivity.this);
}
});
It works perfectly fine when there is internet connection. However, when I purposely turn off internet connection, neither onDataChange nor onCancelled are being called. This is very frustrating since two of the error codes in databaseError.getCode() have to do with network connectivity issues.
If I can't get this data due to no internet, I want to at least let the user know that instead of having this listener hanging with the screen constantly loading. Is there a way to solve this? Would I have to just resort to Firebase's REST API? At least with RESTful network requests, they let you know if the connection failed or not.
Firebase separates the flow of data events (such as onDataChange()) from other things that might happen. It will only call onCancelled when there is a server-side reason to do so (currently only when the client doesn't have permission to access the data). There is no reason to cancel a listener, just because there is no network connection.
What you seem to be looking for is a way to detect whether there is a network connection (which is not a Firebase-specific task) or whether the user is connected to the Firebase Database back-end. The latter you can do by attaching a listener to .info/connected, an implicit boolean value that is true when you're connected to the Firebase Database back-end and is false otherwise. See the section in the document on detecting connection state for full details.
Hope that my solution can help somebody else (I assume that you already did something else)
Besides to set the keepSynced to true in my database reference:
databaseRef.keepSynced(true)
And add to my Application class:
FirebaseDatabase.getInstance().setPersistenceEnabled(true)
I've added two listeners, one for offline mode and other one for online:
override fun create(data: BaseObject): Observable<String> {
return Observable.create { observer ->
val objectId = databaseRef.push().key
objectId?.let { it ->
data.id = it
val valueEvent = object : ValueEventListener {
override fun onCancelled(e: DatabaseError) {
observer.onError(e.toException())
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
observer.onComplete()
}
}
// This listener will be triggered if we try to push data without an internet connection
databaseRef.addListenerForSingleValueEvent(valueEvent)
// The following listeners will be triggered if we try to push data with an internet connection
databaseRef.child(it)
.setValue(data)
.addOnCompleteListener {
observer.onComplete()
// If we are at this point we don't need the previous listener
databaseRef.removeEventListener(valueEvent)
}
.addOnFailureListener { e ->
if (!observer.isDisposed) {
observer.onError(e)
}
databaseRef.removeEventListener(valueEvent)
}
} ?: observer.onError(FirebaseApiNotAvailableException("Cannot create new $reference Id"))
}
}
To be honest, I don't like the idea to attach two listeners very much, if somebody else has a better and elegant solution, please let me know, I have this code temporarily until I find something better.
I am developing a new Android app using Firebase (first time to use Firebase). and I opted to use the Persistence mode as it suits my app better.
My problem is that the app doesn't sync data to the server, hence, other devices, even if the device used to store data is online!!
Code is fine (as far as I can tell), if I disable the Persistence mode, everything works fine, but for sure I don't have the cached data on the device.
This happens in different devices and emulator as well, and the weird thing is that sometimes the devices sync, and then stop syncing again, for no reason!
I appreciate any recommendations here.
code:
My App class:
//....
Firebase.setAndroidContext(this);
Firebase.getDefaultConfig().setPersistenceEnabled(true);
Firebase.getDefaultConfig().setLogLevel(Logger.Level.DEBUG);
//...
Sending code in Message class:
//....
Firebase senderRef = new Firebase(MyApp.FirebaseURL).child("Messages").child(sender_Id);
senderRef.keepSynced(true);
senderRef.push().setValue(this, null);
//....
receive code:
//...
Firebase ref = new Firebase(MyApp.FirebaseURL).child("Messages").child(sender_Id);
Query query = ref.orderByKey();
query.limitToLast(MAX_CHAT_MESSAGES_TO_SHOW);
query.keepSynced(true);
query.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("Firebase", "Message Child Added");
Message message = dataSnapshot.getValue(Message.class);
mMessages.add(0, message);
mAdapter.notifyDataSetChanged();
}
//...
I have done in both ways:
If you want to sync with firebase server
FirebaseDatabase.getInstance().goOnline();
If you do not want to sync with firebase server
FirebaseDatabase.getInstance().goOffline();
Full code:
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
/**
* User anyone function from below as required,
* Read comment proper
*/
// If you want to sync with firebase server
FirebaseDatabase.getInstance().goOnline();
// If you do not want to sync with firebase server
FirebaseDatabase.getInstance().goOffline();
}
}
Hope this would help you.