I have created some test project for learning Firebase remote config. This is settings in firebase https://monosnap.com/file/0xgQCL7oo7lyOjBs8CG3kZO0szBXh6 . Bellow my code:
final FirebaseRemoteConfig config = FirebaseRemoteConfig.getInstance();
FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder()
.setDeveloperModeEnabled(BuildConfig.DEBUG)
.build();
config.setConfigSettings(configSettings);
String onlineVersion = FirebaseRemoteConfig.getInstance().getString("android_current_version");// empty string
I dont know why i cant get value from firebase
Maybe you need to fetch the remote config first:
config.fetch(cacheExpiration)
.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();
// After config data is successfully fetched, it must be activated before newly fetched
// values are returned.
mFirebaseRemoteConfig.activateFetched();
} else {
Toast.makeText(MainActivity.this, "Fetch Failed",
Toast.LENGTH_SHORT).show();
}
String onlineVersion = FirebaseRemoteConfig.getInstance().getString("android_current_version");// empty string
}
})
In the "onComplete" method, you can get the remote config info
check this: Remote Config
Related
i'm working on Login and register activity using Firebase that requires me to strore data in realtime database. I setup the firebase realtime database location in South East Asia, and this is the supposed URL: https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/
and this is my code on writing Users data on the DB, after succesfully creating user using .createUserWithEmailAndPassword(email, password) ==>>
myRef = FirebaseDatabase.getInstance().getReference("Users");
String currUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
User user = new User(username, "default");
myRef.setValue(user)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
} else{
}
}
});
After debugging, i found that the process fails at myRef.setValue(user) because the URL set up for database reference is https://chatapp-5e8ce-default-rtdb.firebaseio.com/Users instead of https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app/Users.
How do i set the URL so it match my firebase database location?
You can pass the URL to FirebaseDatabase.getInstance(), so:
myRef = FirebaseDatabase.getInstance("https://chatapp-5e8ce-default-rtdb.asia-southeast1.firebasedatabase.app").getReference("Users");
You can also download an updated google-services.json, which will contain the correct string and replace the existing (incompletely) file in your Android Studio project with that.
My code uses Remote Config to check for app updates as follows:
ForceUpdateChecker.with(this).onUpdateNeeded(this).check();
final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
// set in-app defaults
Map<String, Object> remoteConfigDefaults = new HashMap();
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_REQUIRED, false);
remoteConfigDefaults.put(ForceUpdateChecker.KEY_CURRENT_VERSION, "2.00.229");
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_URL,
"https://play.google.com/store/apps/details?id=com.chiaramail.pento");
firebaseRemoteConfig.setDefaultsAsync(remoteConfigDefaults);
firebaseRemoteConfig.fetchAndActivate() // fetch config from server and activate
.addOnCompleteListener(new OnCompleteListener<Boolean>() {
#Override
public void onComplete(#NonNull Task<Boolean> task) {
if (task.isSuccessful()) {
Log.d(TAG, "FirebaseRemoteConfig fetched");
} else {
Log.d(TAG, "FirebaseRemoteConfig error:" + task.getResult());
}
}
});
Since I've updated the release containing this code, several users have crashed with the result 'TOO_MANY_REGISTRATIONS'. I believe I've looked at all the SO posts that relate to this problem, but none of them are using fetchAndActivate(). Also, I only have about 1200 users at this point, so hopefully the number of fetches isn't the problem; besides, as I understand it, Remote Config was built to push changes out to one's entire user base, so 1200 users (perhaps up to 6000 devices, max) should not be a problem.
Ok I am a running into a weird problem with firestore
I have the following structure
collection1 -> document1- >collection2
I am adding a new document to collection2 with on complete listener( I tried the success listener as well). No errors are shown. The new document is not shown on the console. The listener is not being called. However, when I query, I get ALL the added documents including the new ones. What's going on here?
Map<String, Object> data = new HashMap<>();
data.put("completed", true;
data.put("date_completed", new Date());
data.put("location", "123 main st");
data.put("notes", "");
data.put("work", "");
db.collection("collection1").document(document1).collection("collection2")
.add(data)
.addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
DocumentReference documentReference = task.getResult();
Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
det.setDocId(documentReference.getId());
addr_arr.add(det);
} else {
Log.w(TAG, "Error adding document", task.getException());
Toast.makeText(EditListActivity.this, "Failed operation - " + task.getException().getMessage(),
Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}
});
Here is the query I do
CollectionReference collecRef = db.collection("collection1").document(document1).collection("collection2");
collecRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (DocumentSnapshot document : task.getResult()) {
// here I do document.get on all the fields, add them to object and add object to array
}
adapter.notifyDataSetChanged();
} else {
Log.d(TAG, "get failed with ", task.getException());
Toast.makeText(EditListActivity.this, "Failed operation - " + task.getException(),
Toast.LENGTH_SHORT).show();
hideProgressDialog();
}
}
});
Your app is acting like it's offline or somehow lacking a working internet connection.
When there is no network connection, the Firestore SDK won't fail on writes. It will store the write locally, and eventually sync that to the server. In the meantime, the local write becomes part of any queries, just like if the data was available on the server. So probably what you're seeing is the result of your local write.
(This is the same behavior you would see with Realtime Database.)
As far why the Firestore SDK doesn't have a connection, I don't know. You might have to troubleshoot that on your own.
I'm using Firebase's custom authentication.
I'm trying to set a user's username with:
UserProfileChangeRequest userProfileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName("Hello")
.build();
assert currentUser != null;
currentUser.updateProfile(userProfileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
#SuppressWarnings("ConstantConditions")
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
Toast.makeText(UsernameAndProfilePictureChooserActivity.this, "Success. Username: " + getUsername(), Toast.LENGTH_SHORT).show();
}
else {
throw new Error(task.getException().getMessage(),task.getException().getCause());
}
}
});
But it has no effect.
The Toast message (Toast.makeText(UsernameAndProfilePictureChooserActivity.this, "Success. Username: " + getUsername(), Toast.LENGTH_SHORT).show(); gets called, but getUsername(), which is FirebaseAuth.getInstance().getCurrentUser().getDisplayName() returns null.
Closing the app then re-opening it doesn't work.
Why is this happening?
Try to update the version of your firebase auth library.
I am using com.google.firebase:firebase-auth:10.2.0 and it works for me.
i have set up firebase storage for my app, and added the code for anonymous auth on the app and on the firebase console.
it worked at first, but i dont know why it stopped working, saying that the user does not have permission to access the object
Anonymous auth is correctly set up and i did see it working, code is almost like Google Firebase docs
logcat:
D/FirebaseAuth: signInAnonymously:onComplete:true
D/FirebaseAuth:
onAuthStateChanged:signed_in: (Random auth user id)
... When i request the item from firebase
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.FirebaseException: An internal error has occured. [Internal error encountered.]
I/DpmTcmClient: RegisterTcmMonitor
from: com.android.okhttp.TcmIdleTimerMonitor W/NetworkRequest: no auth
token for request E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403
Can Someone help?
Declaring Variables
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
on the OnCreate method
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d("FirebaseAuth", "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d("FirebaseAuth", "onAuthStateChanged:signed_out");
}
// ...
}
};
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("FirebaseAuth", "signInAnonymously:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w("FirebaseAuth", "signInAnonymously", task.getException());
Toast.makeText(SingleMemeEditor.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
and the method that gets from storage:
Bitmap bmp;
final Context lContext = context; //getting the MainActivity Context
final String lFileName = fileName; //filename to download
final String lCatPath = catPath; //internal categorization folder
FirebaseStorage storage = FirebaseStorage.getInstance();
// Create a storage reference from our app
StorageReference storageRef = storage.getReferenceFromUrl(context.getResources().getString(R.string.firebase_bucket));
// Create a reference with an initial file path and name
StorageReference filesRef = storageRef.child("files/" + fileName);
try
{
final File localFile = File.createTempFile("images", "jpg");
filesRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>()
{
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot)
{
// Local temp file has been created
File file = new File(getDirectory(lContext)
+ File.separator + lCatPath + File.separator + lFileName);
try
{
Boolean b = file.createNewFile();
if(b)
{
FileInputStream in = new FileInputStream(localFile);
FileOutputStream out = new FileOutputStream(file);
// Transfer bytes from in to out
byte[] buf = new byte[(int)localFile.length()];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
Drawable.createFromPath(file.getPath())).getBitmap());
}
catch (IOException ex)
{
// Handle any errors
Log.e("CopyingFromTemp", ex.getMessage());
}
}
}).addOnFailureListener(new OnFailureListener()
{
#Override
public void onFailure(#NonNull Exception ex)
{
// Handle any errors
Log.e("FirebaseDownloadError", ex.getMessage());
}
});
}
catch(Exception ex)
{
Log.e("FirebaseDownloadError", ex.getMessage());
}
also i'm using standard security rules:
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
as Benjamin Wulfe hinted, i deleted the App's data on the phone and it worked, which means that some kind of Token data was stored on the phone and Anonymous Auth was getting an old session data.
so i added a sign out code before signInAnonymously
mAuth.signOut();
and done!
Thanks to you all for the help!
EDIT: I found another method which is better than signing out and in again (which lead to hundreds of unused anonymous users on the firebase console, and that because the app is not in production yet, would have been millions).
this is what i did:
if (mAuth.getCurrentUser() != null)
{
mAuth.getCurrentUser().reload();
}
else
{
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
#Override
public void onComplete(#NonNull Task<AuthResult> task)
{
Log.d("FirebaseAuth", "signInAnonymously:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful())
{
Log.w("FirebaseAuth", "signInAnonymously", task.getException());
Toast.makeText(MainActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
}
this just reloads current authenticated (anonymous) user.
The message " W/NetworkRequest: no auth token for request " is key for debugging this issue.
This log message means that Firebase Storage did not see any login in the current context. This includes anonymous logins. It means that no authorization was passed to the backend and the only way this will be allowed is if you set your rules to be completely open (public access) which is not recommended (see below).
//this sets completely open access to your data
allow read, write;
I would review the code you have for logging in and ensure it successfully completes before any storage operation is done.
If you are sure your auth code is correct, try resetting data on the device so that no saved state might be there to mess up the application's authorization information.
You might have to check your RULES for storage in firebase console. By default it is set to only permit to authenticated user only
like this
allow read, write: if request.auth != null;
Sometime its disconnect from firebase database,So Connect your app with firebase authentication in android studio through firebase assistance tool.