Posts

Showing posts with the label Firebase

Auto Generate Id For Document And Not Collection In Firestore

Answer : If you are using CollectionReference's add() method, it means that it: Adds a new document to this collection with the specified POJO as contents, assigning it a document ID automatically. If you want to get the document id that is generated and use it in your reference, then use DocumentReference's set() method: Overwrites the document referred to by this DocumentRefere Like in following lines of code: String id = db.collection("collection_name").document().getId(); db.collection("collection_name").document(id).set(object); Since you already know the id of the document, just call set() instead of add() . It will create the document if it doesn't already exist. This answer might be a little late but you can look at this code here which will generate a new document name: // Add a new document with a generated id. db.collection("cities").add({ name: "Tokyo", country: "Japan" }) .then...

Android Project, Change Firebase Account

Answer : Follow the below steps, to switch firebase account Go to your firebase console, and select the project you want to shift Select the icon besides the project name on top right. Select Permissions from the flyout. You've reached the IAM & Admin page of firebase. Click on +Add button on top. Enter the email ID of the account to transfer the project to. In the dropdown, Select a role > Project > Owner. Click add Check mail in the email added above. Accept the invite, and go to IAM & Admin page of the transferred project. Use remove button to delete the previous user Hope this helps. 1- Yes, it's possible and you can follow this tutorial to do so. 2- If you want to simply switch projects, generate a new JSON on the console and remove the old one. If you want to migrate your database, it's possible, just check this question. 3- Both answers are "yes" so, try them out.

'com.google.android.gms.common.api.GoogleApiClient' Is Deprecated

Answer : Yeah GoogleApiClient has been deprecated. As per the documentation: When you want to make a call to one of the Google APIs provided in the Google Play services library (such as Google Sign-in and Drive), you need to create an instance of one the API client objects, which are subclasses of GoogleApi Particularly for the authentication api, you now need to use GoogleSignInClient . // Configure sign-in to request the user's ID, email address, and basic // profile. ID and basic profile are included in DEFAULT_SIGN_IN. GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); // Build a GoogleSignInClient with the options specified by gso. mGoogleSignInClient = GoogleSignIn.getClient(this, gso); You may refer following documentations for more details: Integrating Google Sign-In into Your Android App Moving Past GoogleApiClient

Cloud Firestore: How Is Read Calculated?

Answer : Since you're reading 10 documents, so you'll be charged for 10 document reads. The number of read API calls you use is not relevant here. Also see: Firestore read/write pricing; does .limit(25) counts as 25 reads or one? Understanding Firestore Pricing Firestore Pricing - Does The Amount Of Documents In A Collection Matters? QuizApp - Firebase/ FireStore Reads I did a bunch of testing of this and can confirm that the Firebase Database tab uses an insane amount of reads. For me it incurred a 600+ read count every single time I opened it. If I clicked off that tab and back onto it, I would get another 600+ hit on read count. I monitored the usage of this using the GCP Usage for Firestore so I could avoid having that window open. This is an absurd cost, it has taken me into 100k+ reads by scrolling through it without realizing what was happening. You could even hit a million pretty easy if you were spending a lot of time in there doing something. In addi...

Can I Cleanly Delete Firebase CLI Project?

Answer : You should delete firebase.json and .firebaserc if it exists. Once those files are deleted you should be good to go. I am using the following command npm uninstall firebase and npm uninstall angularfire2 it works for me

Change/update Firebase Notification Token Or Instance Id Forcefully Via Code?

Answer : Now i got my answer after facing many troubles for generating new or change token of firebase for push notification. 1) Delete old Firebase token let instance = FIRInstanceID.instanceID() _ = FIRInstanceID.delete(instance) FIRInstanceID.instanceID().delete { (err:Error?) in if err != nil{ print(err.debugDescription); } else { print("Token Deleted"); } } 2) Request new Firebase token if let token = FIRInstanceID.instanceID().token() { print("Token \(token) fetched"); } else { print("Unable to fetch token"); } FIRMessaging.messaging().connect { (error) in if (error != nil) { print("Error connecting to FCM. \(error.debugDescription)") } else { print("Connected to FCM.") } } UPDATE FOR SWIFT 4 & Firebase 4.8.2 (Follow simple two steps) 1) Delete old Token let instance = InstanceID.instanceID() instance.deleteID { (error) in print(error.debugD...

After Upload A File In Android Firebase Storage How Get The File Download Url? GetDownloadUrl() Not Working

Answer : I had Found 2 solution for my issue. Firebase Google Documentation : //add file on Firebase and got Download Link filePath.putFile(imageUri).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() { @Override public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception { if (!task.isSuccessful()){ throw task.getException(); } return filePath.getDownloadUrl(); } }).addOnCompleteListener(new OnCompleteListener<Uri>() { @Override public void onComplete(@NonNull Task<Uri> task) { if (task.isSuccessful()){ Uri downUri = task.getResult(); Log.d(TAG, "onComplete: Url: "+ downUri.toString()); } } }); Another solution! It's more easy and small than google Firebase documentation and I'll use it: filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.Task...

Can Firestore Update Multiple Documents Matching A Condition, Using One Query?

Answer : Updating a document in Cloud Firestore requires knowings its ID. Cloud Firestore does not support the equivalent of SQL's update queries. You will always have to do this in two steps: Run a query with your conditions to determine the document IDs Update the documents with individual updates, or with one or more batched writes. Note that you only need the document ID from step 1. So you could run a query that only returns the IDs. This is not possible in the client-side SDKs, but can be done through the REST API and Admin SDKs as shown here: How to get a list of document IDs in a collection Cloud Firestore? Frank's answer is actually a great one and does solve the issue. But for those in a hurry maybe this snippet might help you: const updateAllFromCollection = async (collectionName) => { const firebase = require('firebase-admin') const collection = firebase.firestore().collection(collectionName) const newDocumentBody = { ...

Add Field Separately To Firestore Document

Answer : Build a DocumentReference to the document you want to update, then use the update() method on the DocumentReference to indicate only the fields to be added or changed. Pass it an object with only properties that match the fields to add or change.

AngularFire2 - Cannot Find Module @firebase/database

Answer : I think it has to do with an issue with npm. When using yarn to install the modules, everything works flawlessly. yarn add angularfire2 firebase tldr: Node: 8.4.0/npm: 5.2.0 has issues, yarn works You could try with: $ rm -rf node_modules/ $ npm install $ npm install angularfire2@latest --save or to change AngularFireDatabaseModule by AngularFireDatabase . I had no luck trying to reproduce your issue. I would suggest if this is still an issue for you trying the following: Check for differences between my configuration below and yours View the notes for configuring ionic3 here Reinstalling npm (sounds crazy but occasionally I do this and issues disappear and I see mine is a little newer than yours) npm configuration $npm ls -g --depth=0 /Users/pbrack/.nvm/versions/node/v8.5.0/lib ├── cordova@7.1.0 ├── cordova-check-plugins@3.0.1 ├── ionic@3.13.2 ├── ios-deploy@1.9.2 └── npm@5.4.2 Configuration Steps $ ionic start angularfire2test blank $ npm instal...

Cloud Firestore Rules On Subcollection

Answer : Honestly, I think you're okay with your structure and get call as-is. Here's why: If you're fetching a bunch of documents in a subcollection, Cloud Firestore is usually smart enough to cache values as needed. For example, if you were to ask to fetch all 200 items in "conversions/chat_abc/messages", Cloud Firestore would only perform that get operation once and re-use it for the entire batch operation. So you'll end up with 201 reads, and not 400. As a general philosophy, I'm not a fan of optimizing for pricing in your security rules. Yes, you can end up with one or two extra reads per operation, but it's probably not going to cause you trouble the same way, say, a poorly written Cloud Function might. Those are the areas where you're better off optimizing.

Android Firebase Phone Auth Not Receiving SMS Second Time

Answer : In my case, I have my number on Phone numbers for testing (optional) Removing it from there, firebase started sending SMS Code to my number. Spark Plan offer 10k phone auth per month. So that you can test and deploy your app without paying a penny. In case someone is not getting the concept or reason of not sent sms again then please go through on my below details. I have been confused for very long time that why I didn't get sms for second time, third and so on.. First Read the original documentation: onVerificationCompleted(PhoneAuthCredential) This method is called in two situations: Instant verification: in some cases the phone number can be instantly verified without needing to send or enter a verification code. Auto-retrieval: on some devices, Google Play services can automatically detect the incoming verification SMS and perform verification without user action. (This capability might be unavailable with some carriers.) ...

Can You Get The Timestamp From A Firebase Realtime Database Key?

Answer : As I said in my comment, you should not rely on decoding the timestamp from the generated id. Instead of that, you should simply store it in a property in your Firebase. That said, it turns out to be fairly easy to get the timestamp back: // DO NOT USE THIS CODE IN PRODUCTION AS IT DEPENDS ON AN INTERNAL // IMPLEMENTATION DETAIL OF FIREBASE var PUSH_CHARS = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; function decode(id) { id = id.substring(0,8); var timestamp = 0; for (var i=0; i < id.length; i++) { var c = id.charAt(i); timestamp = timestamp * 64 + PUSH_CHARS.indexOf(c); } return timestamp; } var key = prompt("Enter Firebase push ID"); if (key) { var timestamp = decode(key); console.log(timestamp+"\n"+new Date(timestamp)); alert(timestamp+"\n"+new Date(timestamp)); } I'll repeat my comment, just in case somebody thinks it is a good idea to use this code for anything e...

Auto Increment A Value In Firebase With Javascript

Answer : Firebase has no auto-incrementing keys, since those don't work well in massively multi-user systems where clients can be offline for prolonged periods. Instead, Firebase has its own type of auto-generated keys called push IDs. These push IDs have the same important properties of sequences in many relational databases: they are ordered and sequential. But in addition, they can be calculated client-side, even when the client is not connected to the Firebase servers. See the Firebase documentation on saving data in lists, this legacy blog post on why arrays don't work well in Firebase and this post on how push ids work. Firebase recommends using distributed counters: https://firebase.google.com/docs/firestore/solutions/counters For the document that requires the counter, you'd initialize a subcollection of, say, 10 documents and run transaction increments on a random shard whenever you need a counter incremented. Then you'd query the collection of shar...

Android Studio - Get Firebase Token From GetIdToken

Answer : Your second approach is close, you just need to use <GetTokenResult> instead of <UploadTask.TaskSnapshot> as that is for uploading images using Firebase Storage. Try this: user.getIdToken(true).addOnSuccessListener(new OnSuccessListener<GetTokenResult>() { @Override public void onSuccess(GetTokenResult result) { String idToken = result.getToken(); //Do whatever Log.d(TAG, "GetTokenResult result = " + idToken); } });

Angular 6 - Getting Download URL For Firebase Storage File After Uploading

Answer : You should add a finalize() to the pipe, something like: this.task.snapshotChanges().pipe( finalize(() => { this.downloadURL = this.ref.getDownloadURL(); // <-- Here the downloadURL is available. }) ).subscribe(); In the finalize() step, the downloadURL is available, so u can grab him from the ref asynchronously. --UPDATE You said you are using Angular 6, so I assume you are using the last version of firebase. They change getDownloadURL() to Observable from Task, So to get the actual URL you just have to subscribe. this.task.snapshotChanges().pipe( finalize(() => { this.ref.getDownloadURL().subscribe(url => { console.log(url); // <-- do what ever you want with the url.. }); }) ).subscribe();

Cloud Function To Export Firestore Backup Data. Using Firebase-admin Or @google-cloud/firestore?

Answer : The way you're accessing the admin client is correct as far as I can tell. const client = new admin.firestore.v1.FirestoreAdminClient({}); However, you probably won't get any TypeScript/intellisense help beyond this point since the Firestore library does not actually define detailed typings for v1 RPCs. Notice how they are declared with any types: https://github.com/googleapis/nodejs-firestore/blob/425bf3d3f5ecab66fcecf5373e8dd03b73bb46ad/types/firestore.d.ts#L1354-L1364 Here is an implementation I'm using that allows you to do whatever operations you need to do, based on the template provided by firebase here https://firebase.google.com/docs/firestore/solutions/schedule-export In my case I'm filtering out collections from firestore I don't want the scheduler to automatically backup const { Firestore } = require('@google-cloud/firestore') const firestore = new Firestore() const client = new Firestore.v1.FirestoreAdminClient() const bu...

Auto-increment A Value In Firebase

Answer : Here's an example method that increments a single counter. The key idea is that you are either creating the entry (setting it equal to 1) or mutating the existing entry. Using a transaction here ensures that if multiple clients attempt to increment the counter at the same time, all requests will eventually succeed. From the Firebase documentation (emphasis mine): Use our transactions feature when working with complex data that could be corrupted by concurrent updates public void incrementCounter() { firebase.runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(final MutableData currentData) { if (currentData.getValue() == null) { currentData.setValue(1); } else { currentData.setValue((Long) currentData.getValue() + 1); } return Transaction.success(currentData); } @Override public void onComplete(Fi...

Android Studio ML Kit Cannot Load OCR Module

Answer : The solution was to update Google Play Services app. I did not consider this as an option at first as I would have expected an API 29 emulator to have an up-to-date Google Play Services installed. I signed into Google Play on the emulator, searched Google Play Services, uninstalled it (there was no "update" option), and installed it again. It still says that the installed version is 19.4.20 though the text recognition started working as expected. Here are some relevant logs: W/DynamiteModule: Local module descriptor class for com.google.android.gms.vision.dynamite.ocr not found. I/DynamiteModule: Considering local module com.google.android.gms.vision.dynamite.ocr:0 and remote module com.google.android.gms.vision.dynamite.ocr:0 D/TextNativeHandle: Cannot load feature, fall back to load dynamite module. I/DynamiteModule: Considering local module com.google.android.gms.vision.ocr:0 and remote module com.google.android.gms.vision.ocr:1 I/DynamiteModule: Selected re...

Cloud Functions For Firebase Killed Due To Memory Limit Exceeded

Answer : You can set this from within your Cloud Function file on Firebase. const runtimeOpts = { timeoutSeconds: 300, memory: '1GB' } exports.myStorageFunction = functions .runWith(runtimeOpts) .storage .object() .onFinalize((object) = > { // do some complicated things that take a lot of memory and time }); Take from the docs here: https://firebase.google.com/docs/functions/manage-functions#set_timeout_and_memory_allocation Don't forget to then run firebase deploy from your terminal. I was lost in the UI, couldn't find any option to change the memory, but finally found it: Go to the Google Cloud Platform Console (not the Firebase console) Select Cloud Functions in the menu Now you see your firebase function in here if it's correct. Otherwise check if you selected the right project. Ignore all checkboxes, buttons and menu items, just click on the name of the function . Click on edit (top menu) and only change the allocated me...