We are using remote config in our application, and since yesterday our remote value are not reflecting on apps it was working before. Due to this some of over feature breaks and produce crash.
FirebaseRemoteConfig mFirebaseRemoteConfig;
FirebaseRemoteConfigSettings configSettings;
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
mFirebaseRemoteConfig.setDefaults(R.xml.firebase_remote_config_defaults);
mFirebaseRemoteConfig.fetch(getCacheExpiration(mFirebaseRemoteConfig))
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// If is successful, activated fetched
if (task.isSuccessful()) {
MyloLogger.e("FIREBASE_REMOTE_CONFIG", "CONFIG_FETCHED");
mFirebaseRemoteConfig.activateFetched();
setFirebaseConfigData(mFirebaseRemoteConfig, false);
} else {
MyloLogger.e("FIREBASE_REMOTE_CONFIG", "ERROR - KILLLLLL MMMMEEEE ");
}
}
});
setFirebaseConfigData(mFirebaseRemoteConfig, true);`
implementation 'com.google.firebase:firebase-config:16.1.3'
This code was working previously, and suddenly not responding.
This was solved, the problem with the A/B testing regex which is fail and not showing any error. I think Firebase should have some kind of process the errors over there.
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.
I'm trying to setup firebase remote config for release mode by setting developer mode to false. But with cache expiration time less then 3000(may be a bit less, determined it experimentally) seconds, it fails to fetch data. It throws FirebaseRemoteConfigFetchThrottledException
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(false)
.build();
And with .setDeveloperModeEnabled(true) it allows me to set any time even 0 and works well.
Here is whole hunk:
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(false)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
mFirebaseRemoteConfig.setDefaults(R.xml.remote_config_defaults);
mFirebaseRemoteConfig.fetch(CACHE_EXPIRATION)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.i("info32", "remote config succeeded");
mFirebaseRemoteConfig.activateFetched();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.i("info32", "remote config failed");
}
});
}
}, 0);
Could you please explain what the issue is?
Remote Config implements client-side throttling to prevent buggy or malicious clients from blasting the Firebase servers with high frequency fetch requests. One user has reported the limit is five requests per hour. I haven't found the limit documented anywhere, although I have confirmed that five rapid fetches will activate throttling.
The caching of configuration values is explained in the documentation. Because of the throttling limits, it is not possible for your released app to immediately see changes in Remote Config values. Cached values will be used until the next fetch is allowed. The default cache expiration is 12 hours.
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
I am building an android app which uses Firebase as the back-end and an model, view, presenter architecture. However, the fact that Firebase is a cloud service complicates the automated testing in my android app. So far I have built most of the authentication system, but am unable to see how to implement unit tests for the Firebase code in my app. In terms of end to end testing I am also stuck.
Since testing is fundamental to any android app and without it application developers can't be sure what they have implemented is functioning as expected, I can't really progress any further without automated tests.
In conclusion, my question is:
Generally, how do you implement Firebase automated testing in an android app?
EDIT:
As an example could someone unit test the following method?
public void addUser(final String name, final String birthday,
final String email, final String password) {
Firebase mUsersNode = Constants.mRef.child("users");
final Firebase mSingleUser = mUsersNode.child(name);
mSingleUser.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
mSingleUser.child("birthday").setValue(birthday);
mSingleUser.child("email").setValue(email);
mSingleUser.child("password").setValue(password);
return Transaction.success(mutableData);
}
#Override
public void onComplete(FirebaseError firebaseError, boolean b, DataSnapshot dataSnapshot) {
if(firebaseError != null) {
mSignUpPresenter.addUserFail(firebaseError);
} else {
mSignUpPresenter.addUserComplete();
}
}
});
}
UPDATE 2020:
"So far this year (2020), this problem seems to have been solved using a (beta, at the date of this comment) Firebase emulator: Build unit tests using Fb Emulators and Unit testing security rules with the Firebase Emulator Suite, at YouTube This is done locally in the developer's computer. – carloswm85"
I found this https://www.firebase.com/blog/2015-04-24-end-to-end-testing-firebase-server.html but the article is over a year old. I only scanned it, I'll give it a more thorough read in a bit.
Either way, we really need the equivalent of the local Google AppEngine Backend that you can run in Intellij (Android Studio). Testing cannot be an afterthought in 2016. Really hoping one of the awesome Firebase devs notices this thread and comments. Testing should be part of their official guides.
Here is my solution - hope this helps:
[Update]
I've removed my prev. sample in favor of this one. It's simpler and shows the main essence
public class TestFirebase extends AndroidTestCase {
private static Logger logger = LoggerFactory.getLogger(TestFirebase.class);
private CountDownLatch authSignal = null;
private FirebaseAuth auth;
#Override
public void setUp() throws InterruptedException {
authSignal = new CountDownLatch(1);
Firebase.setAndroidContext(mContext); //initializeFireBase(context);
auth = FirebaseAuth.getInstance();
if(auth.getCurrentUser() == null) {
auth.signInWithEmailAndPassword("urbi#orbi.it", "12345678").addOnCompleteListener(
new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull final Task<AuthResult> task) {
final AuthResult result = task.getResult();
final FirebaseUser user = result.getUser();
authSignal.countDown();
}
});
} else {
authSignal.countDown();
}
authSignal.await(10, TimeUnit.SECONDS);
}
#Override
public void tearDown() throws Exception {
super.tearDown();
if(auth != null) {
auth.signOut();
auth = null;
}
}
#Test
public void testWrite() throws InterruptedException {
final CountDownLatch writeSignal = new CountDownLatch(1);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message");
myRef.setValue("Do you have data? You'll love Firebase. - 3")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull final Task<Void> task) {
writeSignal.countDown();
}
});
writeSignal.await(10, TimeUnit.SECONDS);
}
}