<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vikram Kodag on Medium]]></title>
        <description><![CDATA[Stories by Vikram Kodag on Medium]]></description>
        <link>https://medium.com/@kodagvikram?source=rss-68de4bfefffc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Z4RN7qpQAdzVi1pyAQ7ERQ.jpeg</url>
            <title>Stories by Vikram Kodag on Medium</title>
            <link>https://medium.com/@kodagvikram?source=rss-68de4bfefffc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:36:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kodagvikram/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Firebase Cloud Firestore Database read-write best practices -Android]]></title>
            <link>https://medium.com/@kodagvikram/firebase-cloud-firestore-database-read-write-best-practices-android-49637ffe700f?source=rss-68de4bfefffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/49637ffe700f</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[firebase-firestore]]></category>
            <category><![CDATA[android-cloud-firestore]]></category>
            <category><![CDATA[cloud-firestore]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Vikram Kodag]]></dc:creator>
            <pubDate>Sun, 26 Jul 2020 12:49:08 GMT</pubDate>
            <atom:updated>2020-07-26T12:49:08.255Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bermci2O_jU2s7dVSbGcww.gif" /><figcaption>Firebase</figcaption></figure><p>The Firebase Cloud Firestore is a NoSQL database provided by Google Firebase. Like the Firebase realtime database, it provides real-time synced between cloud database and end client app (Android, IOS, Web). Unlike the Firebase realtime database is a single-rooted JSON format database, Firebase Cloud Firestore stores data in hierarchical data structures.</p><p>The Firebase Cloud Firestore store user data in the <strong>document </strong>organized into <strong>collections</strong>. The <strong>document</strong> contains the hierarchical data structure of complex JSON objects. The document also contains the subcollection and subcollection documents also follow the same hierarchical data structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ciqeW8Qd6ozsfuTaA4ugSA.jpeg" /><figcaption>Cloud Firestore database structure</figcaption></figure><p><strong>Now the question is, Why the Cloud Firestore?</strong></p><p>As we all know, the NoSQL database has increasing value in the market and the Cloud Firestore provides the best NoSQL database support with data sync listeners. The Firebase also has a NoSQL <strong>Realtime database</strong> but it has some limitations, like limited querying power, Prising, Security.</p><p><strong>The advantages of Cloud Firestore</strong></p><ol><li><strong>Better querying power </strong>than a Realtime database.</li><li><strong>Allows filters on multiple fields</strong> that will help to limit the data fetch size</li><li>The Realtime database has a higher charge rate on bandwidth and storage. But the Cloud Firestore charge only on operations performed on your database (read, write, delete).</li><li><strong>As for the developers’ point of view, in the Realtime database, we need to add database indexing manually, but Cloud Firestore recognizes the database query indexes and error alert with indexing URL.</strong></li></ol><p>Now we will check the event listeners available in Cloud Firestore for database read-write operations.</p><ol><li>Tasks success listener <strong>addOnSuccessListener</strong></li><li>Task Failure listener <strong>addOnFailureListener</strong></li><li>Task Complete listener <strong>addOnCompleteListener</strong></li><li>Realtime data sync snapshot listener on document or query <strong>addSnapshotListener</strong></li></ol><p>I n this blog, we are going to see the best practice of read-write Firebase Cloud Firestore listeners with a small example. I have a database structure as below and we are going add some data read event listeners to get data from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-eywSFMi8modgK2eJhheg.png" /><figcaption>Database structure</figcaption></figure><p>So let’s start coding. The first thing is that the Firebase Cloud Firestore listeners are asynchronous threads so we need to create some callback classes to handle event listener’s callbacks.</p><p>Create one abstract class named CallBack with two abstract functions to handle onSuccess() and onError().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc022d113c318f727ecf64e74ac6c5e/href">https://medium.com/media/7cc022d113c318f727ecf64e74ac6c5e/href</a></iframe><p>Create another abstract callback class and name it FirebaseChildCallBack with abstract functions to handle child event listeners.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c17a2a4a3df8236c81ff34426bb345d0/href">https://medium.com/media/c17a2a4a3df8236c81ff34426bb345d0/href</a></iframe><p>Now we are going to write all Firebase Cloud Firestore read-write listeners in one class so that it is easy to manage and flexible for future changes. Create a class FirebaseRepository.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0801e62c9aa13f9da260939d40c825e/href">https://medium.com/media/a0801e62c9aa13f9da260939d40c825e/href</a></iframe><p>As you can see, the FirebaseRepository.java the class contains Firebase Cloud Firestore read-write listeners with CallBacks and event listener&#39;s references.</p><p>The function readDocumentByListener() andreadQueryDocumentsByListener() returns ListenerRegistration . This listener is useful to remove EventListener manually. If we are adding addSnapshotListener to any document or query reference then it creates an event connection between our client app and database. The connection will continue until the app is closed or listeners are removed manually.</p><p><strong>So to better utilization of </strong>addSnapshotListener<strong> listeners, we need to remove the </strong>ListenerRegistration<strong>when its task will complete.</strong></p><p>In FirebaseRepository.java you can see all type of events like <strong>addOnSuccessListener ,</strong><strong>addOnFailureListener ,</strong><strong>addOnCompleteListener ,</strong><strong>addSnapshotListener </strong>in one class.</p><p>In the class, you can see one function named batchWrite() . The Firebase Cloud Firestore provides support for a batch write operation. We can give up to 500 tasks in one batch write. So the batch write is also one of the main feature of Cloud Firestore, we will discuss the batch write in another Blog.</p><pre><strong>protected final void </strong>batchWrite(WriteBatch batch, <strong>final </strong>CallBack callback) {<br>    batch.commit().addOnCompleteListener(<strong>new </strong>OnCompleteListener&lt;Void&gt;() {<br>        @Override<br>        <strong>public void </strong>onComplete(@NonNull Task&lt;Void&gt; task) {<br>            <strong>if </strong>(task.isSuccessful())<br>                callback.onSuccess(Constant.<strong><em>SUCCESS</em></strong>);<br>            <strong>else<br>                </strong>callback.onError(<strong><em>FAIL</em></strong>);<br>        }<br>    });<br>}</pre><p>Create a class named <strong>FirebaseDatabaseReference.java</strong> which holds the reference fo our database.</p><pre><strong>public class </strong>FirebaseDatabaseReference {<br>    <strong>private </strong>FirebaseDatabaseReference() {<br>    }</pre><pre>    <strong>public static final </strong>FirebaseFirestore <strong><em>DATABASE </em></strong>= FirebaseFirestore .<em>getInstance</em>();<br>}</pre><p>Create a class named <strong>FirebaseConstants.java </strong>which holds the constants required the database, like database collection names and field names.</p><pre><strong>public class </strong>FirebaseConstants {<br> <strong>public static </strong>String <em>EMPLOYEE_TABLE </em>= <strong>“employee”</strong>;<br> <strong>public static </strong>String <em>EMPLOYEE_NAME </em>= <strong>“empName”</strong>;<br> <strong>public static </strong>String <em>CREATED_DATE_TIME </em>= <strong>“createdDateTime”</strong>;<br>}</pre><p>Here we are done with setting up the structure of the Cloud Firestore read-write.</p><p>Now we are going to start our example of <strong>add update </strong>and <strong>read </strong>Employee details from the real-time database. We are using an MVVM design pattern to structure our code.</p><p>First, create POJO classes for Employee and BranchDetails.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0265fa8ed2997c8da18734bdbbca02a7/href">https://medium.com/media/0265fa8ed2997c8da18734bdbbca02a7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/811891956d4c5f76b1872b720db7f60a/href">https://medium.com/media/811891956d4c5f76b1872b720db7f60a/href</a></iframe><p>Then create an interface EmployeeRepository.java where we add all abstract functions which are required for the data manipulation of the employee collection. You can create separately Repository for every collection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f7a2f7d53519235c57d778ea9b8dae3/href">https://medium.com/media/4f7a2f7d53519235c57d778ea9b8dae3/href</a></iframe><p>We are going to write the implementation of EmployeeRepository in a separate class called EmployeeRepositoryImpl.java which extends FirebaseRepository and implements EmployeeRepository. In this class, we are going to implement all read-write operations and data manipulation logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20f00f4891073d7d3ad9367997af7744/href">https://medium.com/media/20f00f4891073d7d3ad9367997af7744/href</a></iframe><p>As you can see the EmployeeRepositoryImpl.java class contains the implementation of a data read-write. In this class only we are going to write insert, update, delete, simple and compound queries on employee collection.</p><p>That’s it now you are ready to use EmployeeRepository . just create an object reference in your class as,</p><pre><strong>private </strong>EmployeeRepository <strong>employeeRepository</strong>;<br><strong>employeeRepository</strong>= <strong>new </strong>EmployeeRepositoryImpl(addEmployeeActivity);</pre><p>To <strong>add </strong>and <strong>update Employee </strong>details you can call as,</p><pre><strong>private void </strong>saveData(Employee employee) {<br>    <strong>employeeRepository</strong>.createEmployee(employee, <strong>new </strong>CallBack() {<br>        @Override<br>        <strong>public void </strong>onSuccess(Object object) {<br>            <strong>addEmployeeActivity</strong>.finish();<br>        }<br><br>        @Override<br>        <strong>public void </strong>onError(Object object) {<br>            Utility.<em>showMessage</em>(<strong>addEmployeeActivity</strong>, <strong>addEmployeeActivity</strong>.getString(R.string.<strong><em>some_thing_went_wrong</em></strong>));<br>        }<br>    });<br>}<br><br><strong>private void </strong>updateData(Employee employee) {<br>    <strong>employeeRepository</strong>.updateEmployee(<strong>this</strong>.<strong>employee</strong>.getEmpKey(), employee.getMap(), <strong>new </strong>CallBack() {<br>        @Override<br>        <strong>public void </strong>onSuccess(Object object) {<br>            <strong>addEmployeeActivity</strong>.finish();<br>        }<br><br>        @Override<br>        <strong>public void </strong>onError(Object object) {<br>            Utility.<em>showMessage</em>(<strong>addEmployeeActivity</strong>, <strong>addEmployeeActivity</strong>.getString(R.string.<strong><em>some_thing_went_wrong</em></strong>));<br>        }<br>    });<br>}</pre><p>Now we are going to read the employee details with the addSnapshotListener and removing the listener on <strong>onDestroy() </strong>of the activity. In this example, we will use the child event listeners of Firebase Cloud Firestore. The child events listener added in FirebaseRepository.java class as readQueryDocumentsByChildEventListener() and we are going to that function.</p><p>Now we are going to write the adapter EmployeeDetailsAdapter.java to show the list of employees.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd846b7a1603bbc3f9c12624fad7cb67/href">https://medium.com/media/fd846b7a1603bbc3f9c12624fad7cb67/href</a></iframe><p>In adapter, you can see the functionreloadList() which can notify the adapter with index instead of notifyDataSetChanged(); and the operation specifies the event happen in the database which is triggered by the Firebase Cloud Firestore listener.</p><pre><strong>public void </strong>reloadList(<strong>int </strong>index, String operation) {<br>    <strong>switch </strong>(operation) {<br>        <strong>case <em>ADD</em></strong>:<br>            notifyItemInserted(getReversePosition(index));<br>            <strong>break</strong>;<br>        <strong>case <em>UPDATE</em></strong>:<br>            notifyItemChanged(getReversePosition(index));<br>            <strong>break</strong>;<br>        <strong>case <em>DELETE</em></strong>:<br>            notifyItemRemoved(getReversePosition(index));<br>            <strong>break</strong>;<br>        <strong>default</strong>:<br>            notifyDataSetChanged();<br>            <strong>break</strong>;<br>    }<br>}</pre><p>And in ViewModel, we call the child event listener as</p><pre><strong>private void </strong>getAllEmployees() {<br>    <strong>if </strong>(<strong>listenerRegistration </strong>!= <strong>null</strong>)<br>        <strong>listenerRegistration</strong>.remove();<br>    <strong>listenerRegistration </strong>= <strong>employeeRepository</strong>.readAllEmployeesByChildEvent(<strong>new </strong>FirebaseChildCallBack() {<br>        @Override<br>        <strong>public void </strong>onChildAdded(Object object) {<br>            <strong>if </strong>(object != <strong>null</strong>) {<br>                Employee employee = (Employee) object;<br>                <strong>if </strong>(<strong>employeeDetailsAdapter </strong>== <strong>null</strong>)<br>                    setAdapter(<strong>new </strong>IndexedLinkedHashMap&lt;String, Employee&gt;());<br>                <strong>employeeDetailsAdapter</strong>.getEmployeeList().add(employee.getEmpKey(), employee);<br>                <strong>employeeDetailsAdapter</strong>.reloadList(<strong>employeeDetailsAdapter</strong>.getEmployeeList().size() - 1, <strong><em>ADD</em></strong>);<br>            }<br>        }<br><br>        @Override<br>        <strong>public void </strong>onChildChanged(Object object) {<br>            <strong>if </strong>(object != <strong>null</strong>) {<br>                Employee employee = (Employee) object;<br>                <strong>employeeDetailsAdapter</strong>.getEmployeeList().update(employee.getEmpKey(), employee);<br>                <strong>employeeDetailsAdapter</strong>.reloadList(<strong>employeeDetailsAdapter</strong>.getEmployeeList().getIndexByKey(employee.getEmpKey()), <strong><em>UPDATE</em></strong>);<br>            }<br>        }<br><br>        @Override<br>        <strong>public void </strong>onChildRemoved(Object object) {<br>            <strong>if </strong>(object != <strong>null</strong>) {<br>                Employee employee = (Employee) object;<br>                <strong>employeeDetailsAdapter</strong>.getEmployeeList().update(employee.getEmpKey(), employee);<br>                <strong>employeeDetailsAdapter</strong>.reloadList(<strong>employeeDetailsAdapter</strong>.getEmployeeList().getIndexByKey(employee.getEmpKey()), <strong><em>DELETE</em></strong>);<br>            }<br>        }<br><br>        @Override<br>        <strong>public void </strong>onCancelled(Object object) {<br>            <strong>if </strong>(object != <strong>null</strong>)<br>                ExceptionUtil.<em>errorMessage</em>(<strong>TAG</strong>, <strong>&quot;getAllEmployees&quot;</strong>, <strong>new </strong>Exception(object.toString()));<br>        }<br>    });<br>}</pre><p>The getAllEmployees() complete all the tasks for us, to show the list of all employees and you can see we are using readAllEmployeesByChildEvent() to fetch data. That means it handles the data changes in the database. <strong>It creates an event listener</strong> <strong>between our database query reference and client app.</strong></p><p>Now here the manual task is come in the picture, to remove the listener<strong>listenerRegistration.remove(); </strong>listener when our functionality is over. you can remove the listener by calling the function on onDestroy() of your activity.</p><pre><strong>public void </strong>removeListener() {<br>    <strong>if </strong>(<strong>listenerRegistration </strong>!= <strong>null</strong>)<br>        <strong>listenerRegistration</strong>.remove();<br>    Glide.<em>get</em>(<strong>employeeListActivity</strong>).clearMemory();<em>//clear memory<br></em>}</pre><p>In an Activity</p><pre>@Override<br><strong>protected void </strong>onDestroy() {<br>    <strong>super</strong>.onDestroy();<br>    <strong>employeeListViewModel</strong>.removeListener();<br>}</pre><p>The EmployeeListViewModel looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcf2c756536c64cb76d7435e8a20cde5/href">https://medium.com/media/fcf2c756536c64cb76d7435e8a20cde5/href</a></iframe><p><strong>Conclusion :</strong></p><p>So this is how we are written all firebase operation listeners in a separate file and creating a repository for individual collection. Then we are using the repository to manipulate the data operations. And at last, if we are using addSnapshotListener to fetch data, we are then responsible to remove the data change listeners.</p><p>In this blog, we had discussed only the read-write best practices of Cloud Firestore listeners. But intentionally I ignored the discussion on Firebase Cloud Firestore querying. The Firestore provides strong querying power on data and we will discuss Firestore querying in the next blog.</p><p><a href="https://github.com/vikram-kodag/CloudFirestoreListeners.git">Download the Full source code</a></p><p>Note: In the above example the write operation is not permitted. So to check the write data operation you need to configure your own project from the firebase console.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49637ffe700f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Camera Preview Stretch Issue]]></title>
            <link>https://medium.com/@kodagvikram/android-camera-preview-stretch-issue-b43a0db6f7c2?source=rss-68de4bfefffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b43a0db6f7c2</guid>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[android-camera]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[camera-preview-stretch]]></category>
            <category><![CDATA[image-stretch]]></category>
            <dc:creator><![CDATA[Vikram Kodag]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 09:35:58 GMT</pubDate>
            <atom:updated>2020-07-02T09:35:58.806Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJywkAUWrTx1O_JvJKd9PQ.gif" /></figure><p>In the Mobile platform, the Camera is the most usable feature than the other features. Almost 80% of applications have embedded with camera features and use to capture images, video recording, or barcode scanning, etc. Nowadays the camera is using in a more advancing manner like Face recognition, Object recognition, Shape recognition, etc.</p><p>As a mobile application developer implementing the camera feature in the application is an easy thing. But most of the developers face the camera preview stretch issue, so we need to implement the camera feature in the most efficient way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*CfmYupPs8hkwlBMPoYIA7A.jpeg" /><figcaption>Back Camera Stretch Image</figcaption></figure><p>In one of our recent application, we are also facing the same issue, and after spending a lot of time on the internet and reading multiple blogs found one working solution. We combined different answers to working functionality.</p><p>In this blog, we are going to solve the <strong>Camera Preview Stretch Issue</strong>, <strong>Captured Image Stretch Issue</strong>, <strong>Resize Camera Preview With Aspect Ratio, Captured Image Rotation Issue.</strong></p><p>The most important bug in the <strong>Camera Preview Stretch Issue </strong>is the ratio given to display a camera preview. So if the preview ratio is not given in the right way then the camera preview will be going to stretch. Maybe it will work for some of the devices but defiantly it will break in many of the devices. So the preview ratio plays the most important role in camera preview.</p><p>First, we will discuss how to display <strong>Camera Preview In Full Screen?. </strong>So while displaying the camera preview in full screen we need to keep in mind that most of the android devices don&#39;t support the full-screen preview. You can see in the default camera application also has some space at the top and bottom, and they are using those spaces to display settings button and capture button.</p><p>We were also doing the same, we will find the optimal preview size to display camera preview and display in the middle of the screen. Let me share the code and we will discuss it in detail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f27a908b6639a089c0c7891d3a8e93ba/href">https://medium.com/media/f27a908b6639a089c0c7891d3a8e93ba/href</a></iframe><p>Created one class named CameraPreview.java extends SurfaceView implements SurfaceHolder.Callback. The first thing we are going to do is find out the supported preview sizes by</p><pre> List&lt;Camera.Size&gt; <strong>mSupportedPreviewSizes </strong>= <strong>mCamera</strong>.getParameters().getSupportedPreviewSizes();</pre><p>and supported picture sizes by</p><pre>List&lt;Camera.Size&gt; <strong>mSupportedPictureSizes </strong>= <strong>mCamera</strong>.getParameters().getSupportedPictureSizes();</pre><p>Now we are going to find out the Optimal preview size or the best fitting aspect ratio to display camera preview by</p><pre><strong>public </strong>Camera.Size getOptimalPreviewSize(List&lt;Camera.Size&gt; sizes, <strong>int </strong>w, <strong>int </strong>h) {<br>    <strong>final double </strong>ASPECT_TOLERANCE = 0.1;<br>    <strong>double </strong>targetRatio = (<strong>double</strong>) h / w;<br><br>    <strong>if </strong>(sizes == <strong>null</strong>)<br>        <strong>return null</strong>;<br><br>    Camera.Size optimalSize = <strong>null</strong>;<br>    <strong>double </strong>minDiff = Double.<strong><em>MAX_VALUE</em></strong>;<br><br>    <strong>int </strong>targetHeight = h;<br><br>    <strong>for </strong>(Camera.Size size : sizes) {<br>        <strong>double </strong>ratio = (<strong>double</strong>) size.<strong>height </strong>/ size.<strong>width</strong>;<br>        <strong>if </strong>(Math.<em>abs</em>(ratio - targetRatio) &gt; ASPECT_TOLERANCE)<br>            <strong>continue</strong>;<br><br>        <strong>if </strong>(Math.<em>abs</em>(size.<strong>height </strong>- targetHeight) &lt; minDiff) {<br>            optimalSize = size;<br>            minDiff = Math.<em>abs</em>(size.<strong>height </strong>- targetHeight);<br>        }<br>    }<br><br>    <strong>if </strong>(optimalSize == <strong>null</strong>) {<br>        minDiff = Double.<strong><em>MAX_VALUE</em></strong>;<br>        <strong>for </strong>(Camera.Size size : sizes) {<br>            <strong>if </strong>(Math.<em>abs</em>(size.<strong>height </strong>- targetHeight) &lt; minDiff) {<br>                optimalSize = size;<br>                minDiff = Math.<em>abs</em>(size.<strong>height </strong>- targetHeight);<br>            }<br>        }<br>    }<br><br>    <strong>return </strong>optimalSize;<br>}</pre><p>We are going to call the getOptimalPreviewSize() function in the overridden method named onMeasure() as</p><pre>Camera.Size <strong>mPreviewSize </strong>= getOptimalPreviewSize(<strong>mSupportedPreviewSizes</strong>, width, height);</pre><pre>Camera.Size <strong>mPictureSize </strong>= getOptimalPreviewSize(<strong>mSupportedPictureSizes</strong>, width, height);</pre><p>And will set the camera parameters as</p><pre>Camera.Parameters parameters = <strong>mCamera</strong>.getParameters();<br>parameters.setPreviewSize(<strong>mPreviewSize</strong>.<strong>width</strong>, <strong>mPreviewSize</strong>.<strong>height</strong>);<br>parameters.setPictureSize(<strong>mPictureSize</strong>.<strong>width</strong>, <strong>mPictureSize</strong>.<strong>height</strong>);<br><strong>mCamera</strong>.setParameters(parameters);</pre><p>Now we are done with our camera preview and picture stretch issue. So the question is how to use our CameraPreview class?. Here is the solution</p><pre>&lt;<strong>FrameLayout<br>    android:id=&quot;@+id/fl_camera_preview&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:layout_centerInParent=&quot;true&quot;<br>    android:background=&quot;@color/colorBlack&quot; </strong>&gt;<br>&lt;/<strong>FrameLayout</strong>&gt;</pre><pre>CameraPreview <strong>maPreview </strong>= <strong>new </strong>CameraPreview(<strong>context</strong>, <strong>mCamera</strong>, <strong>null</strong>);<br><strong>activityFullScreenPreviewBinding</strong>.<strong>flCameraPreview</strong>.addView(<strong>maPreview</strong>);<br>FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) <strong>maPreview</strong>.getLayoutParams();<br>params.<strong>gravity </strong>= Gravity.<strong><em>CENTER</em></strong>;</pre><p>Now we will discuss the <strong>Dynamic Resize Camera Preview. </strong>So to achieve dynamic resizing of the camera preview we don’t need to changes anything in our CameraPreview.java class. but her also the display preview ratio is very important.</p><p>We will provide the height and width in the percentage of the device pixels but that is not sufficient we need to find the best fitting ratio of given height-width and set it to display a camera preview. So to find the ratio of given height-width we are going to use one Utility function as</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c689fdfc68573aefc7c81fa7a8116c62/href">https://medium.com/media/c689fdfc68573aefc7c81fa7a8116c62/href</a></iframe><p>The<em> getOptimalDimensions() </em>has<em> </em>4 parameters. First 2 aremediaWidth and mediaHeight we will provide the device width pixels as mediaWidth and device height pixels as mediaHeight and for the next 2 parameters, we will provide the percentage pixels provided by the user as</p><pre>DisplayMetrics displayMetrics = <strong>new </strong>DisplayMetrics();<br>((Activity) <strong>context</strong>).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);<br><strong>int </strong>width = (<strong>int</strong>) (displayMetrics.<strong>widthPixels </strong>*((<strong>float</strong>)inputWidth/100));<br><strong>int </strong>height = (<strong>int</strong>) (displayMetrics.<strong>heightPixels </strong>* ((<strong>float</strong>)inputHeight/100));</pre><p>And we will set layout parameters as</p><pre><strong>int </strong>optimalSize[] = Utility.<em>getOptimalDimensions</em>(mScreenWidth<br>        , mScreenHeight<br>        , width<br>        , height);<br><strong>activityFullScreenPreviewBinding</strong>.<strong>flCameraPreview</strong>.getLayoutParams().<strong>width </strong>= optimalSize[0];<br><strong>activityFullScreenPreviewBinding</strong>.<strong>flCameraPreview</strong>.getLayoutParams().<strong>height </strong>= optimalSize[1];</pre><p>Here we are done with <strong>Camera Preview Stretch Issue</strong>, <strong>Captured Image Stretch Issue</strong>, <strong>Resize Camera Preview With Aspect Ratio. </strong>Take look for ViewModel code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/790aa2dac6edd2f002c8c56966131dfe/href">https://medium.com/media/790aa2dac6edd2f002c8c56966131dfe/href</a></iframe><p>For image rotation, we have a utility function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22dfadd780ab96d918b064af296ac709/href">https://medium.com/media/22dfadd780ab96d918b064af296ac709/href</a></iframe><p><strong>Conclusion :</strong></p><p>So this is how we solved the <strong>Camera Preview Stretch Issue</strong>, <strong>Captured Image Stretch Issue</strong>, <strong>Resize Camera Preview With Aspect Ratio, Captured Image Rotation Issue. </strong>The root of all issues is the height-width ratio to display the camera preview.</p><p><a href="https://github.com/vikram-kodag/Camera-Preview-Strech-Issue.git">Download the Full source code</a></p><p>Happy coding….!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b43a0db6f7c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase real-time data read-write best practices -Android]]></title>
            <link>https://medium.com/@kodagvikram/firebase-real-time-data-read-write-best-practices-android-67a06fa6420d?source=rss-68de4bfefffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/67a06fa6420d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[firebase-data-read-write]]></category>
            <category><![CDATA[realtime-database]]></category>
            <category><![CDATA[firebase-database]]></category>
            <category><![CDATA[firebaserealtimedatabase]]></category>
            <dc:creator><![CDATA[Vikram Kodag]]></dc:creator>
            <pubDate>Sat, 14 Dec 2019 13:21:15 GMT</pubDate>
            <atom:updated>2019-12-14T13:21:15.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bermci2O_jU2s7dVSbGcww.gif" /><figcaption>Firebase</figcaption></figure><p>The Firebase Realtime Database is a famous NoSQL single-rooted JSON format database and provides real-time synced between cloud database and end client app (Android, IOS, Web).</p><p><strong>Read Data :</strong></p><p>The Firebase provides the asynchronous data read event listeners to fetch data from a cloud database. The client app attaches data read listeners to get data. The listeners trigger when any changes in the database references, The some of them are as,</p><ul><li><strong>addListenerForSingleValueEvent</strong></li><li><strong>addValueEventListener</strong></li><li><strong>addChildEventListener</strong></li></ul><p>You can use listeners as you need. The addListenerForSingleValueEvent is for reading data ones, theaddValueEventListener and addChildEventListener to add a real-time data change trigger. <a href="https://firebase.google.com/docs/database/admin/retrieve-data">For more information</a>.</p><p><strong>Add, Update and Remove :</strong></p><p>The firebase provides .setValue() and .updateChildren() to add and update data in a firebase realtime database. .removeValue() for remove data from the database.</p><p>In this blog, we are going to see the best practice of write firebase listeners with a small example. I have a database structure of employee as below and we are going add some data read event listeners to get data from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*PtNiNEexls_aMFR8GqGRxw.png" /></figure><p>So let&#39;s start coding. The first thing is that the firebase listeners are asynchronous threads so we need to create some callback classes to handle event listener&#39;s callbacks.</p><p>Create one abstract class named CallBack with two abstract functions to handle onSuccess() and onError().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc022d113c318f727ecf64e74ac6c5e/href">https://medium.com/media/7cc022d113c318f727ecf64e74ac6c5e/href</a></iframe><p>Create another abstract callback class and name it FirebaseChildCallBack with abstract functions to handle child event listeners.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0233ed8f9ab86f21b27d16e450d127a6/href">https://medium.com/media/0233ed8f9ab86f21b27d16e450d127a6/href</a></iframe><p>Now we are going to write all firebase read-write listeners in one class so that it is easy to manage and flexible for future changes. Create a class FirebaseRepository.java</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4285e48e36dd6f9bfa5562ac755df506/href">https://medium.com/media/4285e48e36dd6f9bfa5562ac755df506/href</a></iframe><p>As you can see, the FirebaseRepository.java class contains firebase read-write listeners with CallBacks and event listener&#39;s references.</p><p>The function fireBaseDataChangeListene() returns ValueEventListener reference on database query which is useful to add and remove ValueEventListenermanually. If we are adding ValueEventListener to any database reference then it creates an event connection between our client app and database. The connection will continue until the app is closed or listeners are removed manually.</p><p><strong>So to better utilization of data change listeners, we need to remove the listeners when its task is completed.</strong></p><p>The same functionality is applied forChildEventListener. But you can see the fireBaseReadData() returns void because addListenerForSingleValueEvent reads data ones and removes the listeners itself.</p><p>Now create a POJO class named FirebaseRequestModel.java which contains the <strong>query</strong> on which the listener is applied and the <strong>listener type</strong> which listens to the data change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92b9c7cdcc2834e7a0da79858114ed01/href">https://medium.com/media/92b9c7cdcc2834e7a0da79858114ed01/href</a></iframe><p>Now create another class named FirebaseUtility.java which contains static functions to remove listeners applied to the query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e08bd20e78375bd843685060bc734141/href">https://medium.com/media/e08bd20e78375bd843685060bc734141/href</a></iframe><p>Create a class named <strong>FirebaseDatabaseReference.java</strong> which holds the reference fo our database.</p><pre><strong>public class </strong>FirebaseDatabaseReference {<br>    <strong>private </strong>FirebaseDatabaseReference() {<br>    }<br><br>    <strong>public static final </strong>FirebaseDatabase <strong><em>DATABASE </em></strong>= FirebaseDatabase.<em>getInstance</em>();<br>}</pre><p>Create a class named <strong>FirebaseConstants.java </strong>which holds the constants required the database, like database collection names and field names.</p><pre><strong>public class </strong>FirebaseConstants {<br>    <strong>public static </strong>String <em>EMPLOYEE_TABLE </em>= <strong>&quot;employee&quot;</strong>;<br>    <strong>public static </strong>String <em>EMPLOYEE_NAME </em>= <strong>&quot;empName&quot;</strong>;<br>    <strong>public static </strong>String <em>CREATED_DATE_TIME </em>= <strong>&quot;createdDateTime&quot;</strong>;<br>}</pre><p>Here we are done with setting up the structure of the firebase data read-write.</p><p>Now we are going to start our example of <strong>add update </strong>and <strong>read </strong>Employee details from the real-time database. We are using an MVVM design pattern to structure our code.</p><p>First, create POJO classes for Employee and BranchDetails.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0265fa8ed2997c8da18734bdbbca02a7/href">https://medium.com/media/0265fa8ed2997c8da18734bdbbca02a7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c34acd5b4f1cec4894f58b6009782e5/href">https://medium.com/media/4c34acd5b4f1cec4894f58b6009782e5/href</a></iframe><p>Then create an interface EmployeeRepository.java where we add all abstract functions which are required for the data manipulation of the employee collection. You can create separate Repository for every collection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/364a213a5bd98efeeea8ceb29f119f10/href">https://medium.com/media/364a213a5bd98efeeea8ceb29f119f10/href</a></iframe><p>We are going to write the implementation of EmployeeRepository . Create a class called EmployeeRepositoryImpl.java which extends FirebaseRepository and implements EmployeeRepository. In this class, we are going to implement all read-write operations and data manipulation logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8746e44b363f1e52eee04bfb920e7eb/href">https://medium.com/media/c8746e44b363f1e52eee04bfb920e7eb/href</a></iframe><p>As you can see the readAllEmployeesByDataChangeEvent() function returns FirebaseRequestModel because in this function we are applying ValueEventListener to the query. So that calling function can contain the reference to the FirebaseRequestModel to remove the listener manually.</p><p>Same applied for the readAllEmployeesByChildEvent() function which returns ChildEventListener .</p><p>That&#39;s it now you are ready to use EmployeeRepository . just create an object reference in your class as,</p><pre><strong>private </strong>EmployeeRepository <strong>employeeRepository</strong>;<br><strong>employeeRepository</strong>= <strong>new </strong>EmployeeRepositoryImpl(addEmployeeActivity);</pre><p>To <strong>add </strong>and <strong>update Employee </strong>details you can call as,</p><pre><strong>private void </strong>saveData(Employee employee) {<br>    <strong>employeeRepository</strong>.createEmployee(employee, <strong>new </strong>CallBack() {<br>        @Override<br>        <strong>public void </strong>onSuccess(Object object) {<br>            <strong>addEmployeeActivity</strong>.finish();<br>        }<br><br>        @Override<br>        <strong>public void </strong>onError(Object object) {<br>            Utility.<em>showMessage</em>(<strong>addEmployeeActivity</strong>, <strong>addEmployeeActivity</strong>.getString(R.string.<strong><em>some_thing_went_wrong</em></strong>));<br>        }<br>    });<br>}<br><br><strong>private void </strong>updateData(Employee employee) {<br>    <strong>employeeRepository</strong>.updateEmployee(<strong>this</strong>.<strong>employee</strong>.getEmpKey(), employee.getMap(), <strong>new </strong>CallBack() {<br>        @Override<br>        <strong>public void </strong>onSuccess(Object object) {<br>            <strong>addEmployeeActivity</strong>.finish();<br>        }<br><br>        @Override<br>        <strong>public void </strong>onError(Object object) {<br>            Utility.<em>showMessage</em>(<strong>addEmployeeActivity</strong>, <strong>addEmployeeActivity</strong>.getString(R.string.<strong><em>some_thing_went_wrong</em></strong>));<br>        }<br>    });<br>}</pre><p>The ViewModel looks like,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6b5e7ac6f4d241200d1716411e6a72c/href">https://medium.com/media/b6b5e7ac6f4d241200d1716411e6a72c/href</a></iframe><p>Now we are going to read the employee details with the ChildEventListener and removing the listener on <strong>onDestroy() </strong>of the activity.</p><p>To show the list employee we need the Adapter . But before writing the adapter, we are going to write a custom indexed hashmap named IndexedLinkedHashMap to optimize the performance of the adapter collaborating with the ChildEventListener .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/066bd174cce3a8e79ebdc6152d842631/href">https://medium.com/media/066bd174cce3a8e79ebdc6152d842631/href</a></iframe><p>Now we are going to write the adapter EmployeeDetailsAdapter.java to show the list of employees.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd846b7a1603bbc3f9c12624fad7cb67/href">https://medium.com/media/fd846b7a1603bbc3f9c12624fad7cb67/href</a></iframe><p>In adapter, you can see the functionreloadList() which can notify the adapter with index instead of notifyDataSetChanged(); and the operation specifies the event happen in the database which is triggered by the ChildEventListener .</p><pre><strong>public void </strong>reloadList(<strong>int </strong>index, String operation) {<br>    <strong>switch </strong>(operation) {<br>        <strong>case <em>ADD</em></strong>:<br>            notifyItemInserted(getReversePosition(index));<br>            <strong>break</strong>;<br>        <strong>case <em>UPDATE</em></strong>:<br>            notifyItemChanged(getReversePosition(index));<br>            <strong>break</strong>;<br>        <strong>case <em>DELETE</em></strong>:<br>            notifyItemRemoved(getReversePosition(index));<br>            <strong>break</strong>;<br>        <strong>default</strong>:<br>            notifyDataSetChanged();<br>            <strong>break</strong>;<br>    }<br>}</pre><p>Now it’s time to set the ChildEventListener on the employee database orderByChild(<em>CREATED_DATE_TIME</em>) and that returns the FirebaseRequestModel object reference.</p><pre>{<br>    <strong>if </strong>(<strong>firebaseRequestModel </strong>!= <strong>null</strong>)<br>        removeListener();<br>    <strong>firebaseRequestModel </strong>= <strong>employeeRepository</strong>.readAllEmployeesByChildEvent(<strong>new </strong>FirebaseChildCallBack() {<br>        @Override<br>        <strong>public void </strong>onChildAdded(Object object) {<br>            <strong>if </strong>(object != <strong>null</strong>) {<br>                Employee employee = (Employee) object;<br>                <strong>if </strong>(<strong>employeeDetailsAdapter </strong>== <strong>null</strong>)<br>                    setAdapter(<strong>new </strong>IndexedLinkedHashMap&lt;String, Employee&gt;());<br>                <strong>employeeDetailsAdapter</strong>.getEmployeeList().add(employee.getEmpKey(), employee);<br>                <strong>employeeDetailsAdapter</strong>.reloadList(<strong>employeeDetailsAdapter</strong>.getEmployeeList().size() - 1, <strong><em>ADD</em></strong>);<br>            }<br>        }<br><br>        @Override<br>        <strong>public void </strong>onChildChanged(Object object) {<br>            <strong>if </strong>(object != <strong>null</strong>) {<br>                Employee employee = (Employee) object;<br>                <strong>employeeDetailsAdapter</strong>.getEmployeeList().update(employee.getEmpKey(), employee);<br>                <strong>employeeDetailsAdapter</strong>.reloadList(<strong>employeeDetailsAdapter</strong>.getEmployeeList().getIndexByKey(employee.getEmpKey()), <strong><em>UPDATE</em></strong>);<br>            }<br>        }<br><br>        @Override<br>        <strong>public void </strong>onChildRemoved(Object object) {<br>            <strong>if </strong>(object != <strong>null</strong>) {<br>                Employee employee = (Employee) object;<br>                <strong>employeeDetailsAdapter</strong>.getEmployeeList().update(employee.getEmpKey(), employee);<br>                <strong>employeeDetailsAdapter</strong>.reloadList(<strong>employeeDetailsAdapter</strong>.getEmployeeList().getIndexByKey(employee.getEmpKey()), <strong><em>DELETE</em></strong>);<br>            }<br>        }<br><br>        @Override<br>        <strong>public void </strong>onChildMoved(Object object) {<br><br>        }<br><br>        @Override<br>        <strong>public void </strong>onCancelled(Object object) {<br>            Utility.<em>showMessage</em>(<strong>employeeListActivity</strong>, <strong>employeeListActivity</strong>.getString(R.string.<strong><em>some_thing_went_wrong</em></strong>));<br>        }<br>    });<br>}</pre><p>The getAllEmployees() complete all the tasks for us, to show the list of all employees and you can see we are using ChildEventListener to fetch data. That means it handles the data changes in the database. <strong>It creates an event listener</strong> <strong>between our database query reference and client app.</strong></p><p>Now here the manual task is come in the picture, to remove the ChildEventListener listener when our functionality is over. you can remove the listener by calling the function on onDestroy() of your activity.</p><pre><strong>public void </strong>removeListener() {<br>    FirebaseUtility.<em>removeFireBaseChildListener</em>(<strong>employeeListActivity</strong>, <strong>firebaseRequestModel</strong>);<br>}</pre><p>In an Activity</p><pre>@Override<br><strong>protected void </strong>onDestroy() {<br>    <strong>super</strong>.onDestroy();<br>    <strong>employeeListViewModel</strong>.removeListener();<br>}</pre><p>The ViewModel looks like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6b5e7ac6f4d241200d1716411e6a72c/href">https://medium.com/media/b6b5e7ac6f4d241200d1716411e6a72c/href</a></iframe><p><strong>Conclusion :</strong></p><p>So this is how we are written all firebase operation listeners in a separate file and creating a repository for individual collection. Then we are using the repository to manipulate the data operations. And at last, if we are using ValueEventListener or ChildEventListener to fetch data, we are then responsible to remove the data change listeners.</p><p>To increase the data fetch speed we need to add Indexing to query fields.</p><p><a href="https://medium.com/@kodagvikram/firebase-real-time-database-indexing-83f16e7adf9a?source=friends_link&amp;sk=dbc8a619b98b4a331a0f6caae9bdbdc2"><strong>How to add indexing to the firebase database?</strong></a></p><p><a href="https://github.com/vikram-kodag/FirebaseListner.git">Download the Full source code</a></p><p>Note: In the above example the write operation is not permitted. So to check the write data operation you need to configure your own project from the firebase console.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67a06fa6420d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Real-Time Database Indexing]]></title>
            <link>https://medium.com/@kodagvikram/firebase-real-time-database-indexing-83f16e7adf9a?source=rss-68de4bfefffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/83f16e7adf9a</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[ios-developer]]></category>
            <category><![CDATA[firebase-indexing]]></category>
            <category><![CDATA[application-developer]]></category>
            <category><![CDATA[android-developers]]></category>
            <dc:creator><![CDATA[Vikram Kodag]]></dc:creator>
            <pubDate>Thu, 19 Sep 2019 14:52:38 GMT</pubDate>
            <atom:updated>2019-11-05T19:59:59.278Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bermci2O_jU2s7dVSbGcww.gif" /><figcaption>Firebase image</figcaption></figure><h3>Firebase Real-Time Database Data Indexing</h3><p>Google Firebase is a Google-backed application development software that enables developers to develop Android, iOS and Web apps. Firebase provides features like analytics, reporting and fixing app crashes, creating marketing and product experiments, <strong>Realtime Database</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ojR0MbntzBMUi816f64Xpw.png" /><figcaption>Google Firebase Features</figcaption></figure><p><strong>Why go for Firebase Realtime database?</strong></p><p>The Firebase Realtime Database is a cloud-hosted and simple JSON formatted NoSQL database that enables data to be stored in single-rooted JSON format and synced between users in real-time.</p><p>To create HTTP requests and response service APIs, we need to do a lot of configuration and also we need knowledge of backend services. And also to synchronize our local database to the server is a difficult task for developers. Instead of typical HTTP requests, the Firebase Realtime Database provides event-based data synchronization. Every time data changes, all connected device receives that update within milliseconds. The data change events are invoked with all connected devices and provide updated data.</p><p>Maintain offline data is also very simple in firebase because firebase apps remain responsive even when offline because the Firebase Realtime Database SDK persists your data to disk. Once connectivity is reestablished, the client device receives any changes it missed, synchronizing it with the current server state.</p><p>The Firebase Realtime Database can be accessed directly from a mobile device or web browser. there’s no need for an application server. Security and data validation are available through the Firebase Realtime Database Security Rules, expression-based rules that are executed when data is read or written.</p><p>Firebase provides the best solutions for mobile app development. Firebase Real-Time database is one of the good features of that. But it has its own advantages and limitations also.</p><p>As we know, Firebase real-time data fetch listeners work fine with a small amount of data, but as data increases the performance of data read is also decreases.</p><p>In this blog, we are going to discuss the indexing of the firebase data fields and values to increase the performance of the firebase query. Indexing increases the performance of <strong>orderByChild()</strong> and <strong>orderByValue()</strong> queries.</p><p>A node’s key is indexed automatically, so there is no need to index it explicitly. Firebase supports indexing by <strong>field names</strong> and <strong>field values</strong>.</p><p>Explicit indexing is added in the section of the <strong>Rules</strong> tab of the Real-Time database.</p><p><strong>Indexing with </strong><a href="https://firebase.google.com/docs/database/security/indexing-data#section-indexing-order-by-value"><strong><em>orderByValue</em></strong></a><strong>:</strong></p><p>To demonstrate how<strong>.indexOn</strong> works with <strong>orderByValue()</strong>, Suppose we have a database structure of cricket players World Cup runs like,</p><pre>{<br> “scores”: {<br> “ViratKholi” : 557,<br> “MSDhoni” : 346,<br> “RohitSharma” : 746,<br> “ShikharDhawan” : 256,<br> “KLRahul” : 545,<br> “RPant” : 228<br> }<br>}</pre><p>We’re using orderByValue() to get players sorted by scores of World Cup OR top scorers by <strong>.orderByValue() </strong>followed by <strong>.limitToFirst() </strong>. We can optimize our queries by adding a <strong>.value</strong> rule on our <strong>/scores</strong> node:</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;scores&quot;: {<br>      &quot;.indexOn&quot;: &quot;.value&quot;<br>    }<br>  }<br>}</pre><p><strong>Indexing with </strong><a href="https://firebase.google.com/docs/database/security/indexing-data#section-indexing-order-by-child"><strong><em>orderByChild</em></strong></a><strong>:</strong></p><p>We will use the following Database structure to explain how <strong>.indexOn</strong> works with <strong>orderByChild()</strong>.</p><pre>{<br>  &quot;employee&quot;: {<br>    &lt;&quot;employee1Key&quot;&gt;: {<br>      &quot;empName&quot;: Rohit Sharma,<br>      &quot;Designation&quot;: SW Developer,<br>      &quot;empId&quot;: EMP776,<br>      &quot;branchDetails&quot;: {<br>        &quot;branch&quot;: Software,<br>        branchLocation: Pune,<br>        branchId: BR556<br>      }<br>    },<br>    &lt;&quot;employee2Key&gt;&quot;: {<br>      &quot;empName&quot;: Vira tKholi,<br>      &quot;Designation&quot;: Accountant,<br>      &quot;empId&quot;: EMP908,<br>      &quot;branchDetails&quot;: {<br>        &quot;branch&quot;: Finance,<br>        branchLocation: Dheli,<br>        branchId: BR557<br>      }<br>    },<br>    &lt;&quot;employee3Key&quot;&gt;: {<br>      &quot;empName&quot;: MS Dhoni,<br>      &quot;Designation&quot;: Sales Manager,<br>      &quot;empId&quot;: EMP909,<br>      &quot;branchDetails&quot;: {<br>        &quot;branch&quot;: Sales and Marketing,<br>        branchLocation: Pune,<br>        branchId: BR556<br>      }<br>    }<br>  }<br>}</pre><p>Now, if you want to order the data by <strong>empName, empId and designation</strong>, you need to update rules as follows,</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;employee&quot;: {<br>      &quot;.indexOn&quot;: [&quot;empName&quot;, &quot;empId&quot;, &quot;designation&quot;]<br>    }<br>  }<br>}</pre><p>Now, if you want to fetch data of employees whose branchId=BR556 <strong>OR</strong> <strong>branch=Pune </strong>then you need to add the second level indexing.</p><p>You can add indexing on any level of data as other rules. If you want to add indexing on <strong>empName, empId </strong>which is on the first level, and <strong>branch, branchLocation, </strong>and<strong> branchId</strong> which is on the second level of employee data structure, you need to update rules as follows,</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;employee&quot;: {<br>      &quot;.indexOn&quot;: [&quot;empName&quot;,&quot;empId&quot;,&quot;branchDetails/branch&quot;,<br>        &quot;branchDetails/branchLocation&quot;,&quot;branchDetails/branchId&quot;]<br>    }<br>  }<br>}</pre><p>There is another way to specify <strong>multilevel indexing</strong> as,</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;employee&quot;: {<br>      &quot;.indexOn&quot;: [&quot;empName&quot;,&quot;empId&quot;,&quot;designation&quot;],<br>      &quot;$key&quot;: {<br>        &quot;salary&quot;: {<br>          &quot;.indexOn&quot;: [&quot;branch&quot;,&quot;branchLocation&quot;,&quot;branchId&quot;<br>          ]<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>You can create indexing on any of your node with a comma separating as,</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;employee&quot;: {<br>      &quot;.indexOn&quot;: [&quot;empName&quot;,&quot;empId&quot;,&quot;branchDetails/branch&quot;,<br>        &quot;branchDetails/branchLocation&quot;,&quot;branchDetails/branchId&quot;]<br>    },<br>    &quot;scores&quot;: {<br>      &quot;.indexOn&quot;: &quot;.value&quot;<br>    }<br>  }<br>}</pre><p><strong>Conclusion:</strong></p><p>As all Firebase realtime database users experience that data fetch delay increases when they are having the bulk of data in the database. So to improve performance, indexing is very helpful. The performance of the realtime database is more dependent on what kind of data structure you have chosen.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83f16e7adf9a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>