Not instant Remote Config value android? - android

implementation 'com.google.firebase:firebase-config:11.8.0'
FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
mFirebaseRemoteConfig.setConfigSettings(configSettings);
mFirebaseRemoteConfig.fetch(0).addOnCompleteListener(this, new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mFirebaseRemoteConfig.activateFetched();
String appDefaultColor = mFirebaseRemoteConfig.getString(FIREBASE_REMOTE_CONFIG_DEFAULT_COLOR);
if (appDefaultColor != null && appDefaultColor.length() > 0) {
System.out.println("==== appDefaultColor : " + appDefaultColor);
}
}
}
});
public static String FIREBASE_REMOTE_CONFIG_DEFAULT_COLOR = "project_default_theme_color";
here is my implementation of Firebase remote config.
As above my code explanation, project4_default_theme_color, i get the value from firebase, But the situation is that i change that value from Firebase remote config , but i did't get.
My firebase remote config Key project_default_theme_color and value is #f04030 and Publish Changes.is any wrong in this?

Follow below instruction to resolve this issue
Update your firebase library version
implementation 'com.google.firebase:firebase-config:19.1.0'
implementation 'com.google.firebase:firebase-core:17.2.1'
Initialize FirebaseRemoteConfig
FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
Set firebaseRemoteConfig parameter default value
firebaseRemoteConfig.setDefaultsAsync(R.xml.remote_config_defaults);
Add below code in remote_config_defaults.xml
<?xml version="1.0" encoding="utf-8"?>
<defaultsMap>
<entry>
<key>your_key</key>
<value>defaultValue</value>
</entry>
Add this code in your java file
firebaseRemoteConfig.fetch(cacheTimeDuration)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String errorString = "";
if (task.isSuccessful()) {
firebaseRemoteConfig.activate();
errorString = " task is successful ";
} else {
errorString = "task is canceled";
}
Log.i(TAG, "onComplete: error " + errorString);
Log.i(TAG, " Get firebase remote config value " + firebaseRemoteConfig.getString("your_key"));
}
});
Note :
If your Apk is debug then use this method .fetch(cacheTimeDuration)
If your Apk is Release then use this method .fetch()

Related

Read and write data to Cloud Firestore in Android

Hi I want to read and write data using Firebase Firestore.
1- I `added Firebase to my project (using this instruction)
2- I added Firestore to my project (using this instruction)
I can write and then read data, but the read and write operation are locally and my Firestore database not changing.
I have added google-services.json to my app directory
I declared internet and network-state permission in manifest
My device is connected to internet
My Firestore database is in test mode (allow read, write)
This is my build.gradle dependency:
implementation platform('com.google.firebase:firebase-bom:29.1.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-firestore'
This is my code to add data to Firestore database:
private void writeData()
{
FirebaseFirestore db = FirebaseFirestore.getInstance();
Map<String, Object> user = new HashMap<>();
user.put("first", "Ada");
user.put("last", "Lovelace");
user.put("born", 1815);
db.collection("purchased")
.add(user)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(MainActivity.this,"done",Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,"failed",Toast.LENGTH_SHORT).show();
}
});
}
And this is my code to read data:
private void readData()
{
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("purchased")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Toast.makeText(MainActivity.this,document.getId() + " => " + document.getData(),Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MainActivity.this,"Error getting documents: "+ task.getException().getMessage().toString(),Toast.LENGTH_LONG).show();
}
}
});
}
While writing data, even callbacks are not calling (neither onSuccess nor onFailue) and no toast is displaying, but when I read data the toast display my data correctly, but everything is offline and no changes made to my Firestore database, what's the problem?

Firebase instance id: deprecation of getId() in 21.0.0

With the recent release of FirebaseInstanceId and FirebaseCloudMessaging (21.0.0) Firebase has deprecated iid package and both getToken() and getId() methods are now deprecated.
According to the Firebase release note the method getToken() is moved to FirebaseMessaging
Before:
FirebaseInstanceId.getInstance().getToken()
After:
FirebaseMessaging.getInstance().getToken()
Which gives use the fcmToken, but to retrieve instance id, there's no method available in FirebaseMessaging nor FirebaseInstanceId.
So, Is instance_id considered a useless id and should no longer be used? or is there a replacement for this?
FirebaseInstanceId class is deprecated, to get token use FirebaseMessagingClass. The token can be generated using the following code:
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (!task.isSuccessful()) {
Log.w(TAG, "Fetching FCM registration token failed", task.getException());
return;
}
// Get new FCM registration token
String token = task.getResult();
// Log and toast
String msg = getString(R.string.msg_token_fmt, token);
Log.d(TAG, msg);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
Regarding the Firebase InstanceId, this is what the official document says:
public Task getInstanceId () ->
This method is deprecated.
For an instance identifier, use FirebaseInstallations.getId() instead. For an FCM registration token, use FirebaseMessaging.getToken() instead.
Fcm Token
Before deprecation
val fcmToken = FirebaseInstanceId.getInstance().getToken()
Replacement
val fcmToken = FirebaseMessaging.getInstance().getToken()
FirebaseInstanceId#getId
Before deprecation
val istanceId = FirebaseInstanceId.getInstance().getId()
Replacement
Checking out the code of FirebaseInstanceId#getId() I saw the suggestion that you should use FirebaseInstallations#getId instead.
This method is deprecated
Use FirebaseInstallations.getId() instead.
val instanceId = FirebaseInstallation.getInstance().getId()
FCM Token:
Use firebase_messaging package
String? token = await FirebaseMessaging.instance.getToken();
Installation ID:
Use flutterfire_installations package
String id = await FirebaseInstallations.instance.getId();
Installation auth token:
String token = await FirebaseInstallations.instance.getToken();
try this one
public String getToken() {
String token;
FirebaseMessaging.getInstance().getToken()
.addOnCompleteListener(new OnCompleteListener<String>() {
#Override
public void onComplete(#NonNull Task<String> task) {
if (task.isSuccessful()) {
token = task.getResult();
}
}
});
return token;
}

Security rules "get()" not working on app

Performing the get() function in security rules is not working.
It returns permission denied on the client, but passes in simulation.
The config/permissions layout is an array structure:
config/permissions-->
---------------------------> CollectionName1 :
----------------------------------------------------> 0 : UID1
----------------------------------------------------> 1 : UID2
---------------------------> CollectionName2 :
----------------------------------------------------> 0 : UID3
----------------------------------------------------> 1 : UID4
I also tried to use single key/value fields in the config/permissions as so
config/permissions-->
---------------------------> CollectionName1 : UID1
---------------------------> CollectionName2 : UID3
with the rule
allow read: if request.auth.uid == get(/config/permissions).data[c] and this passed simulation and failed on the app. If I hardcode the UID instead of request.auth.uid it gives the same result.
UID is definitely correct on the app. This was tested by using the following rule, where it passed in simulation AND the app.
allow read: if request.auth.uid == 'USER_ID_HERE'
and by comparing the logcat output of the UID to the one above.
Please help. This is the Nth day of trying to find a suitable way to structure and query Firestore. I'm certain this is an issue with either the get() call or the way I am writing the call.
Android Code:
FirebaseFirestore db = FirebaseFirestore.getInstance();
FirebaseFirestoreSettings settings = new FirebaseFirestoreSettings.Builder()
.setTimestampsInSnapshotsEnabled(true)
.build();
db.setFirestoreSettings(settings);
Log.d("UID", FirebaseAuth.getInstance().getCurrentUser().getUid());
DocumentReference docRef = db.collection(collection).document("X153#111");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d("FIREBASE", "DocumentSnapshot data: " + document.getData());
} else {
Log.d("FIREBASE", "No such document");
}
} else {
Log.d("FIREBASE", "get failed with ", task.getException());
}
}
});

Simulation Rules - access allowed; Android - access denied

I have a rule which executes correctly in Firestore Rules simulation as seen below.
The /config/permissions document is many arrays named X153, X154, X155, etc., which contain UIDs:
When I attempt this access in Android, I get a PERMISSION_DENIED response.
Code:
DocumentReference docRef = db.collection("arcs").document("X153");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Log.d("FIREBASE", "DocumentSnapshot data: " + document.getData());
} else {
Log.d("FIREBASE", "No such document");
}
} else {
Log.d("FIREBASE", "get failed with ", task.getException());
}
}
});
The UID used in simulation is the same as in Android:
If I set the rule to authenticate access of the UID directly
Android permission accepted, returns document.
If I flatten out the config/permissions structure to just key/values, like X153 : '9iXQBaG3Ycaey4cFUj8tZjhKMaB3', and change the rule to
match /arcs/{x} {
allow read: if request.auth.uid == get(/config/permissions).data[x];
}
Android returns PERMISSION DENIED.
Why am I receiving this PERMISSION DENIED response using the rule pictured?

Querying Firestore for uid document after authentification => IllegalStateException

I am using both Firebase Authentification and Firestore for my Android app. What I am trying to do is the following:
the user signs in
if it's the first time the user signs in a document named by his uid is created
if the user has already signed in before (hence document named by uid already exists) then I load some further data.
Here's my logic to solve this:
get the FirebaseUser from FirebaseAuth instance
from the FirebaseUser I get the uid
build a DocumentReference with this uid
use get() query on the DocumentReference
if DocumentSnapshot is != null then user already exists in firestore
if DocumentSnapshot == null the user doesn't exist and I create it in firestore
I was testing the code below:
FirebaseUser user = mAuth.getCurrentUser();
if(user != null) {
// get uid from user
String uid = user.getUid();
// make a query to firestore db for uid
DocumentReference userDoc = db.collection("users").document(uid);
userDoc.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document != null) {
Log.d(LOG_TAG, "DocumentSnapshot data: " + task.getResult().getData());
} else {
Log.d(LOG_TAG, "No such document");
}
} else {
Log.d(LOG_TAG, "get failed with ", task.getException());
}
}
});
}
When uid exists in firestore I get the log message with appropriate data but when it doesn't I get the following exception and I can't find a way to get to use DocumentSnapshot.exists():
java.lang.IllegalStateException: This document doesn't exist. Use DocumentSnapshot.exists() to check whether the document exists before accessing its fields.
Can anyone help me understand what I am doing wrong ?
Thanks a million ! :)
The object returned by get() is a DocumentSnapshot not the document itself. The DocumentSnapshot is never null. Use the exists() method to determine if the snapshot contains a document. If exists() is true, you can
safely use one of the getXXX() methods (in your case, getData() for a map) to obtain the value of the document.
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot snapshot = task.getResult();
if (snapshot.exists()) {
Log.d(LOG_TAG, "DocumentSnapshot data: " + snapshot.getData());
} else {
Log.d(LOG_TAG, "No such document");
}
} else {
Log.d(LOG_TAG, "get failed with ", task.getException());
}
}

Categories

Resources