According to the docs, in order to enable persistence for the DEFAULT initialized app, I need to add the line FirebaseDatabase.getInstance().setPersistenceEnabled(true); to my MainActivity.java file which I did. But persistence is still not working. This is the code for my MainActivity.java file:
package com.myapp;
import com.facebook.react.ReactActivity;
import com.google.firebase.database.FirebaseDatabase;
import android.os.Bundle;
public class MainActivity extends ReactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "myapp";
}
}
Application Target Platform: Android
Development Operating System: Windows 10
Build Tools: Android Studio 2.2.3
React Native version: 0.49.3
RNFirebase Version: 3.0.4
Firebase Module: database
What do you mean by persistence isn't working? How do you know this is the case?
When I go offline, perform some write actions, close the app, restart it and then go online, none of those actions are getting pushed.
@Shank209 I'd suggest putting a break point on the line FirebaseDatabase.getInstance().setPersistenceEnabled(true); and check that it's being called?
@chrisbianca I set a break point and checked like you said. It is indeed getting called.
Also, if it matters, auth() and every other part of database() and working just fine. It's just the persistence which is the issue. I tested on both an emulator and physical devices.
@Shank209 can you try move the setPersistence call to your MainApplication rather than MainActivity, the docs have been updated to reflect. Thanks
Closing due to lack of response. Please re-open if you're still experiencing issues and let us know the answers to the above questions.
According to the docs it should be added in MainApplication.java under inside the onCreate method;
Like so:
@Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
SoLoader.init(this, /* native exopackage */ false);
}
This causes an exception as such;
/Volumes/nvme/Users/jason/projects/acmtrackmobile/android/app/src/main/java/com/acmtrack/a
pp/futurity/MainApplication.java:79: error: cannot find symbol
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
^
symbol: variable FirebaseDatabase
location: class MainApplication
1 error
:app:compileDebugJavaWithJavac FAILED
Update: For those struggling with the same issue, I had to add this line to the same file near the top:
import com.google.firebase.database.FirebaseDatabase;
@TitanKing Thanks for highlighting this, I've just added the additional details to the documentation.
@chrisbianca You guys are just amazing, truly.
Hi,
Is there an example for "createUserWithEmailAndPassword" and other auth features when user is offline?
For example I am setting:
var firebase2 = RNFirebase.initializeApp({ persistence: true });
and then:
firebase2.auth().createUserWithEmailAndPassword(this.state.signupEmail, this.state.signupPassword)
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
})
.then(function(User) {
console.log(User)
});
But I am not getting User...
After I turn on internet I am getting:
Error: A network error has occurred, please try again.
and User is undefined.
Is there something else I need to do?
@nikolal only database is going to work offline for such actions. If you're offline you need the server to validate that say the email address is not already in use (for example).
@Ehesp
OK thanks.
What about keeping users authenticated? Can I login user in offline mode? I need to access database based on logged in user.
@nikolal If the user was logged in before going offline, they will remain logged in when offline, but will obviously only be able to access anything that had previously been accessed on the device. If the user was not logged in when the device went offline, then they will not be able to login until the device is back online.
Also note that database security rules are server side, so can not be enforced when offline.
OK. So this means if I log in user once and keep him logged in for a longer time, next time he opens the app offline he will stay logged in and will be able to access database ( if rules are allowing it ).
Am I correct?
Yes, the user will be able to access anything that has been persisted / cached in the database.
OK, great. Thank you very much.
I have a new problem after I added FirebaseDatabase.getInstance().setPersistenceEnabled(true);
On running react-native run-android:
MainApplication.java:35: error: package com.google.firebase.database does not exist
import com.google.firebase.database.FirebaseDatabase;
^
MainApplication.java:88: error: cannot find symbol
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
^
symbol: variable FirebaseDatabase
location: class MainApplication
2 errors
:app:compileDebugJavaWithJavac FAILED
FAILURE: Build failed with an exception.
I'm new to native Android development. Any idea on how to solve com.google.firebase.database being missing? I've followed Android installation docs exactly, and tried all the combinations in configs I can think of.
My MainApplication.java for reference:
package <appID>;
import android.app.Application;
import com.facebook.react.ReactApplication;
import io.sentry.RNSentryPackage;
import com.RNRate.RNRatePackage;
import com.corbt.keepawake.KCKeepAwakePackage;
import com.oblador.vectoricons.VectorIconsPackage;
import com.github.yamill.orientation.OrientationPackage;
import com.microsoft.codepush.react.CodePush;
import com.github.alinz.reactnativewebviewbridge.WebViewBridgePackage;
import com.sha256lib.Sha256Package;
import net.no_mad.tts.TextToSpeechPackage;
import com.cmcewen.blurview.BlurViewPackage;
import com.BV.LinearGradient.LinearGradientPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
// NOTE: This is only file modified on Android side of Firebase integration
import io.invertase.firebase.RNFirebasePackage;
// Optional packages for Firebase
// import io.invertase.firebase.admob.RNFirebaseAdMobPackage; //Firebase AdMob
import io.invertase.firebase.analytics.RNFirebaseAnalyticsPackage; // Firebase Analytics
import io.invertase.firebase.auth.RNFirebaseAuthPackage; // Firebase Auth
import io.invertase.firebase.config.RNFirebaseRemoteConfigPackage; // Firebase Remote Config
// import io.invertase.firebase.crash.RNFirebaseCrashPackage; // Firebase Crash Reporting
import io.invertase.firebase.database.RNFirebaseDatabasePackage; // Firebase Realtime Database
// import io.invertase.firebase.firestore.RNFirebaseFirestorePackage; // Firebase Firestore
import io.invertase.firebase.messaging.RNFirebaseMessagingPackage; // Firebase Cloud Messaging
import io.invertase.firebase.perf.RNFirebasePerformancePackage; // Firebase Performance
import io.invertase.firebase.storage.RNFirebaseStoragePackage; // Firebase Storage
import com.google.firebase.database.FirebaseDatabase;
import java.util.Arrays;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNSentryPackage(MainApplication.this),
new RNRatePackage(),
new VectorIconsPackage(),
new OrientationPackage(),
new RNFirebasePackage(),
new CodePush(getResources().getString(R.string.reactNativeCodePush_androidDeploymentKey), getApplicationContext(), BuildConfig.DEBUG),
new WebViewBridgePackage(),
new Sha256Package(),
new TextToSpeechPackage(),
new BlurViewPackage(),
new LinearGradientPackage(),
new KCKeepAwakePackage(),
);
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
@fungilation sounds like you haven't added the firebase-database dependency to your app/build.gradle
@chrisbianca thanks so much! I feel dumb now, pods spoiled me on iOS side and I forgot pods is iOS only when I set that up.
Now I'm running into this: https://github.com/invertase/react-native-firebase/issues/17#issuecomment-386009595 (unrelated)
Most helpful comment
Update: For those struggling with the same issue, I had to add this line to the same file near the top: