<?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 Prakhar Srivastava on Medium]]></title>
        <description><![CDATA[Stories by Prakhar Srivastava on Medium]]></description>
        <link>https://medium.com/@prakharsrivastava_219?source=rss-be79a07df57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*1NxjMNX3TWG-_Ww6hCGyaA.jpeg</url>
            <title>Stories by Prakhar Srivastava on Medium</title>
            <link>https://medium.com/@prakharsrivastava_219?source=rss-be79a07df57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 23:55:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prakharsrivastava_219/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[Direction of marker for cabs application]]></title>
            <link>https://medium.com/@prakharsrivastava_219/direction-of-marker-for-cabs-application-5daa142ba06f?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/5daa142ba06f</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[cab-booking]]></category>
            <category><![CDATA[google-directions-api]]></category>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[android-google-map]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 10:01:32 GMT</pubDate>
            <atom:updated>2019-11-26T10:01:32.584Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OamXODHqgIq3uQSPqMaT7A.jpeg" /></figure><p>All of us have seen that in the cab booking applications, the cabs can be seen moving in a certain direction.<br>Today we will doing it for a sample application. Today we will be building this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*Kapg0hFn74Sxyf5RGvFv3Q.jpeg" /></figure><p>The full source code can be found <a href="https://github.com/shree-vastava/CabDirection"><strong>here</strong></a><strong><br></strong><a href="https://github.com/shree-vastava/CabDirection">https://github.com/shree-vastava/CabDirection</a></p><p>We had already built the google maps application and we know how to plot a marker on any latitude-longitude. Now we will plot the marker along with the direction.</p><p>Assuming that we know how to integrate google maps in an application, we will now see how to use the direction.<br>The google map integration can be found here:<br><a href="https://medium.com/@prakharsrivastava_219/place-search-for-cab-booking-apps-62fdb2820b55">https://medium.com/@prakharsrivastava_219/place-search-for-cab-booking-apps-62fdb2820b55</a></p><p>For this application, we are going to use this json for the data:</p><pre>[<br>  {<br>    &quot;id&quot;: 717089,<br>    &quot;coordinate&quot;: {<br>      &quot;latitude&quot;: 13.000328929247145,<br>      &quot;longitude&quot;: 77.66136940063981<br>    },<br>    &quot;heading&quot;: 79.76481247942495<br>  },<br>  {<br>    &quot;id&quot;: 138923,<br>    &quot;coordinate&quot;: {<br>      &quot;latitude&quot;: 13.004034501539103,<br>      &quot;longitude&quot;: 77.66658092598375<br>    },<br>    &quot;heading&quot;: 86.68768525531794<br>  },<br>  {<br>    &quot;id&quot;: 845561,<br>    &quot;coordinate&quot;: {<br>      &quot;latitude&quot;: 13.008143569008332,<br>      &quot;longitude&quot;: 77.66554754164146<br>    },<br>    &quot;heading&quot;: 55.94253168584245<br>  },<br>  {<br>    &quot;id&quot;: 552739,<br>    &quot;coordinate&quot;: {<br>      &quot;latitude&quot;: 12.998529266659475,<br>      &quot;longitude&quot;: 77.65874105811088<br>    },<br>    &quot;heading&quot;: 158.58042356238863<br>  }<br>]</pre><p>Here the <strong>‘heading’ </strong>parameter tells us about the direction of a cab. The value for heading is passed into a parameter called <strong>‘rotation’</strong> while plotting on the google map.</p><pre>mMap!!.addMarker(<br>    MarkerOptions()<br>        .position(LatLng(latitude, longitude))      .icon(BitmapDescriptorFactory.fromResource(R.drawable.<em>ic_marker</em>))<br>        .anchor(0.5f, 0.5f)<br>       <strong> .rotation(heading.<em>toFloat</em>())</strong><br>        .flat(true)<br>)</pre><p>Here, we have passed the value of heading to rotation.</p><p>If you have to calculate this value on runtime (without a json), we can calculate it using the latitude and longitudes.<br>By using the <strong>FusedLocationServices</strong>, the application can get the location updates.<br>Store the latitude longitude at a certain time and once the user moves, the application will get the updated lat-long.</p><p>This is how we calculate the direction, once we get the source/destination latitude and longitude.</p><pre>fun calculateBearing(lat1: Double, lng1: Double, lat2: Double, lng2: Double): Float {<br>        val sourceLatLng = LatLng(lat1, lng1)<br>        val destinationLatLng = LatLng(lat2, lng2)<br>        return SphericalUtil.computeHeading(sourceLatLng,    destinationLatLng).toFloat()<br>}</pre><p>This function calculates the heading direction. And we can call this using the latitude and longitude of the source and destination.</p><pre>Val bearing  = calculateBearing(lat1, lng1, lat2, lng2)<br>marker.rotation(bearing)</pre><p>This will calculate the direction when we move from a source to a destination.</p><p>Please try this and let me know in comments what challenges you faced or if you found a better way to achieve this.<br>Happy coding!!</p><p>The full source code can be found <a href="https://github.com/shree-vastava/CabDirection"><strong>here</strong></a><br><a href="https://github.com/shree-vastava/CabDirection">https://github.com/shree-vastava/CabDirection</a></p><blockquote>May the source be with you</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5daa142ba06f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Shared Element Transition]]></title>
            <link>https://medium.com/@prakharsrivastava_219/android-shared-element-transition-deea6fa7e34b?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/deea6fa7e34b</guid>
            <category><![CDATA[shared-element-transition]]></category>
            <category><![CDATA[android-animations]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-design-patterns]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Wed, 24 Jul 2019 11:31:15 GMT</pubDate>
            <atom:updated>2019-07-24T11:41:24.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*selyys8HHCWw4EX7DuHNOw.jpeg" /></figure><p>We are going to do a simple android shared element transition today. The shared element transition is one of the designs that any user loves to engage with.<br>For those who are new to the concept of shared element transition, we are going to do this today:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*LKIzUCiX4xJtiMg7eTOLyg.gif" /></figure><blockquote>Before we start, here is the full source code:<br><a href="https://github.com/shree-vastava/SharedElementTransition">https://github.com/shree-vastava/SharedElementTransition</a></blockquote><p>To achieve this animation, we need only 3 simple steps:</p><ol><li>Define same transition name for each element in both the xml.</li><li>Define transition in the intent to next activity</li></ol><h3>Transition Name in XML</h3><p>In this step, we will define the transition name to the elements we want to animate in the xml, in our case the circular image, name and occupation.</p><p>Note that the image, name and occupation are present in both activities. The transition name for one element should be same in both the activities.<br>For example, if we are giving the transition name “imageTrans” to the image in activity 1, we shall give the same name to the image in activity 2.</p><p>So here is the code of image, name and occupation from the activity_main.xml (activity1):</p><pre>&lt;de.hdodenhof.circleimageview.CircleImageView<br>        android:id=&quot;@+id/personImage&quot;<br>        android:layout_width=&quot;50dp&quot;<br>        android:layout_height=&quot;50dp&quot;<br>        android:scaleType=&quot;centerCrop&quot;<br>        android:transitionName=&quot;picture&quot;</pre><pre>&lt;TextView<br>        android:id=&quot;@+id/personName&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Stephen Amell&quot;<br>        android:textColor=&quot;#000&quot;<br>        android:transitionName=&quot;name&quot;<br>        android:fontFamily=&quot;@font/roboto_regular&quot;<br>        android:textSize=&quot;14sp&quot;/&gt;<br><br>&lt;TextView<br>        android:id=&quot;@+id/personOccupation&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Actor&quot;<br>        android:transitionName=&quot;occupation&quot;<br>        android:fontFamily=&quot;@font/roboto_regular&quot;<br>        android:textSize=&quot;12sp&quot;/&gt;</pre><p>Here the transition names for the elements are following<br>personImage: picture<br>personName: name<br>personOccupation: occupation</p><p>Now the elements from the activity_details.xml (activity2)</p><pre>&lt;de.hdodenhof.circleimageview.CircleImageView<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;120dp&quot;<br>        android:scaleType=&quot;centerCrop&quot;<br>        android:layout_marginTop=&quot;20dp&quot;<br>        android:transitionName=&quot;picture&quot;<br>        android:src=&quot;@drawable/stephen&quot;/&gt;<br><br>&lt;TextView<br>        android:id=&quot;@+id/personName&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:textSize=&quot;20sp&quot;<br>        android:layout_marginTop=&quot;10dp&quot;<br>        android:transitionName=&quot;name&quot;<br>        android:textColor=&quot;#B84D30&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:fontFamily=&quot;@font/roboto_regular&quot;<br>        android:text=&quot;Stephen Amell&quot;/&gt;<br><br>&lt;TextView<br>        android:id=&quot;@+id/personOccupation&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:textSize=&quot;20sp&quot;<br>        android:textColor=&quot;#5565AF&quot;<br>        android:transitionName=&quot;occupation&quot;<br>        android:layout_gravity=&quot;center&quot;<br>        android:fontFamily=&quot;@font/roboto_light&quot;<br>        android:text=&quot;Actor&quot;/&gt;</pre><p>Note that the transition names are same for the respective elements.</p><h3>Implement transition in Kotlin</h3><p>Let’s see what is required in the kotlin/java class to make it work.<br>Here we won’t use the intent with only one argument.<br>So, we will use:</p><pre>startActivity(intent, bundle)</pre><p>this function is by android only.<br>In the bundle part, we will pass our transition configuration.<br>We use ‘Pair’ for this. In the pair, we pass the element and its transition name to the bundle.</p><pre>android.util.Pair(personImage,personImage.<em>transitionName</em>)</pre><p>So the complete code comes out to be:</p><pre>profile_layout.setOnClickListener <strong>{<br>    </strong>var intent = Intent(this,DetailsActivity::class.<em>java</em>)<br>    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this,<br>        android.util.Pair(personImage,personImage.<em>transitionName</em>),<br>        android.util.Pair(personName,personName.<em>transitionName</em>),<br>        android.util.Pair(personOccupation,personOccupation.<em>transitionName</em>)).toBundle())<br><br><strong>}</strong></pre><blockquote>There is no code required in the details activity.<br>Cheers!!<br>Here is the full source code:<br><a href="https://github.com/shree-vastava/SharedElementTransition">https://github.com/shree-vastava/SharedElementTransition</a></blockquote><h3>May the source be with you</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=deea6fa7e34b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Android Augmented Images]]></title>
            <link>https://medium.com/@prakharsrivastava_219/simplifying-android-augmented-images-7659efd6b827?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/7659efd6b827</guid>
            <category><![CDATA[arcore]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Wed, 24 Jul 2019 08:02:24 GMT</pubDate>
            <atom:updated>2019-07-24T08:12:29.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*usnoNuOVBGTLG4G1EWMRgw.jpeg" /></figure><p>Android has come a long way over the past years. <br>With the augmented reality coming into android, the whole android ecosystem has got a whole new dimension to play around. Though the AR sdk has limited features, it is fascinating.</p><p>In this tutorial, we will see how to detect and augmented image and show information using a ViewRenderable or show a 3-D model.</p><h3>The Requirement</h3><p>We had a requirement to show the pressure flowing through a pipe using the mobile application. The AR implementation was:<br>A person should be able to see the pressure levels at certain points in a pipe.</p><p>We implemented the ARCore with a ViewRenderable to show the information on a card. And it looks pretty cool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ktC9X31E_NiGVRro74Kf4g.gif" /><figcaption>ARCore in action</figcaption></figure><p>The full source code can be found on my github:</p><p><a href="https://github.com/shree-vastava/ARAugmentedImage"><strong>https://github.com/shree-vastava/ARAugmentedImage</strong></a></p><p>There are three steps to achieve this.</p><ol><li>Create an augmented image</li><li>Match the image in camera frame with the augmented image</li><li>If matched, place an AR Object.</li></ol><p>I our scenario, we had to identify the pressure sensor. Unfortunately the android ARCore SDK does not support the 3-D objects recognition. So we were not able to identify the sensor. Instead, we added an image on top of the sensors with the ‘Sensor Id’. This is what we used as an augmented image as well.<br>Let’s go through the steps in detail:</p><h3>Create augmented Image</h3><p>We copy the image (which we want to detect) to the ‘assets’ directory.</p><pre>private fun setupAugmentedImageDb(config: Config): Boolean {<br>    val augmentedImageDatabase: AugmentedImageDatabase<br><br>    val augmentedImageBitmap = loadAugmentedImage() ?: return false<br><br>    augmentedImageDatabase = AugmentedImageDatabase(session)<br>    augmentedImageDatabase.addImage(&quot;snsr_image&quot;, augmentedImageBitmap)<br><br>    config.<em>augmentedImageDatabase </em>= augmentedImageDatabase<br>    return true<br>}</pre><p>Here we have created an Augmented Image Database.<br>The `addImage` method here takes one String and one Bitmap as the arguments. So we have added our name as ‘snsr_name’ and the bitmap of our image using the following function</p><pre>private fun loadAugmentedImage(): Bitmap? {<br>    try {<br>        <em>assets</em>.open(&quot;snsr_image.jpg&quot;).<em>use </em><strong>{ </strong>`is` <strong>-&gt; </strong>return BitmapFactory.decodeStream(`is`) <strong>}<br>    </strong>} catch (e: IOException) {<br>        Log.e(TAG, &quot;IO exception loading augmented image bitmap.&quot;, e)<br>    }<br><br>    return null<br>}</pre><p>Now we are ready to use this AugmentedImage with the real world camera image.</p><h3>Compare the camera Image with Augmented Image</h3><p>When we initialize our ARSceneView, we set an update callback which notifies us of all the frame updates on the camera</p><pre>arSceneView.<em>scene</em>.setOnUpdateListener(this::onUpdateFrame)</pre><p>An when the frame is updated, we compare the image in the frame with the augmented image in the DB.</p><pre>private fun onUpdateFrame(frameTime: FrameTime) {<br>    frameTime.toString()<br>    val frame = arSceneView.<em>arFrame<br>    </em>val updatedAugmentedImages = frame.getUpdatedTrackables(AugmentedImage::class.<em>java</em>)<br><br>    for (augmentedImage in updatedAugmentedImages) {<br>        if (augmentedImage.<em>trackingState </em>== TrackingState.TRACKING) {<br>            // Check camera image matches our reference image<br><br>            if (augmentedImage.<em>name </em>== &quot;snsr_image&quot;) {<br>               //the image has matched, do work here<br>            }<br><br>        }<br>    }<br>}</pre><p>Here, we get all the updated tractable on frame update as the Augmented Images and we compare them each with the DB. And when the name matches, we have just hit our image.<br>Now once the images are matched, we need to place an info card.</p><h3>Placing an Info Card</h3><p>When we get the correct match from our augmented images, we pass the correct one in a method.</p><pre>for (augmentedImage in updatedAugmentedImages) {<br>        if (augmentedImage.<em>trackingState </em>== TrackingState.TRACKING) {<br>            // Check camera image matches our reference image<br><br>            if (augmentedImage.<em>name </em>== &quot;snsr_image&quot;) {<br>               createRenderable(augmentedImage,&quot;snsr_002&quot;)<br>            }<br><br>        }<br>    }</pre><p>Here in the example I have passed the hardcoded value.<br>In the sample on GitHub, I have the original functionality implemented.<br>Once the image is matched, we scan the QRCode in the image, which is a sensor id and pass that value in the function below:</p><pre>private fun createRenderable(augmentedImage: AugmentedImage, name : String) {<br>    var renderable : ViewRenderable?=null<br>    try {<br>        renderable = dataView.get()<br>    } catch (e: InterruptedException) {<br>        e.printStackTrace()<br>    } catch (e: ExecutionException) {<br>        e.printStackTrace()<br>    }<br>    val node = Node()<br>    try {<br><br>        val anchorNode = AnchorNode(arSceneView.<em>session</em>.createAnchor(augmentedImage.<em>centerPose</em>))<br>        arSceneView.<em>scene</em>.removeChild(anchorNode)<br>        val pose = Pose.makeTranslation(0.0f, 0.0f, 0.12f)<br>        node.<em>localPosition </em>= Vector3(pose.tx(), pose.ty(), pose.tz())<br><br>        node.<em>renderable </em>= renderable<br>        node.setParent(anchorNode)<br>        node.<em>localRotation </em>= Quaternion(pose.qx(), 90f, -90f, pose.qw())<br><br>        arSceneView.<em>scene</em>.addChild(anchorNode)<br>        setNodeData(renderable!!,name)<br>        sensorsMap[name] = renderable!!<br>        makeInfoView()<br><br>    } catch (e: Exception) {<br>        e.toString()<br>    }<br>}</pre><p>Here we are using ViewRenderable.<br>We get the view to be inflated in the view renderable</p><pre>renderable = dataView.get()</pre><p>Where dataView is an XML from the layout folder</p><pre>dataView = ViewRenderable.builder().setView(this, R.layout.<em>layout_bg</em>).build()</pre><p>Once we have the view renderable, we setup the anchor where we will place this renderable. The anchor is placed in the center of the augmented image.</p><pre>AnchorNode(arSceneView.<em>session</em>.createAnchor(augmentedImage.<em>centerPose</em>))</pre><p>And when we have our anchor ready, we create a node, set the renderable and set our anchor node as the parent of the node.<br>And DONE. We have successfully placed our ARObject in front of the augmented image</p><p>The last step is to set the data.</p><p>You can get the full source code on my GitHub here:</p><p><a href="https://github.com/shree-vastava/ARAugmentedImage"><strong>https://github.com/shree-vastava/ARAugmentedImage</strong></a></p><p>Let me know in comments if this helped you. :)<br>Thanks</p><h3>May the source with you</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7659efd6b827" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Full Screen Activity (no system UI)]]></title>
            <link>https://medium.com/@prakharsrivastava_219/android-full-screen-activity-no-system-ui-c5f5a94667ec?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5f5a94667ec</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Thu, 05 Apr 2018 07:39:53 GMT</pubDate>
            <atom:updated>2018-04-05T07:39:53.063Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, has any of us ever wanted to create an android application with full screen? like real full screen, which doesn’t even show the top bar where network, battery, notifications appear and the OS’ back and home button.</p><p>Well I wanted to create one and was able to do so. It is easy at first but then as components like <strong>EditTexts</strong> get involved, it gets a bit tricky.</p><p>So let’s look at what we will be building today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NM4bOeNWOhMD_g8v2CSBSA.jpeg" /><figcaption>As we can see, on left, the default apps, and on right, our app without top and bottom System UI bars.</figcaption></figure><p>Now let’s add some code to achieve this. <br>It’s fairly simple to do so. We just need to add the following piece of code in our activity.</p><pre>public void hideSystemUI(){<br>    getWindow().getDecorView().setSystemUiVisibility(<br>            View.<em>SYSTEM_UI_FLAG_LAYOUT_STABLE<br>                    </em>| View.<em>SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION<br>                    </em>| View.<em>SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN<br>                    </em>| View.<em>SYSTEM_UI_FLAG_HIDE_NAVIGATION<br>                    </em>| View.<em>SYSTEM_UI_FLAG_FULLSCREEN<br>                    </em>| View.<em>SYSTEM_UI_FLAG_IMMERSIVE_STICKY</em>);<br>}</pre><p>After adding this our app will become full screen.</p><p><strong>BUT, </strong>one problem still exists. As soon as the EditText comes into focus and we write the text, the system UI comes back to never leave again. Worst part, our app doesn’t adjust its UI according to the system UI. So it’s view gets cut from top and bottom.</p><p>Let’s see how it looks in both the cases, without and with keyboard visible on screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vc9w6AubXWezxaGQl6D2Rg.jpeg" /><figcaption>On Left, without text and on right, with text in EditText</figcaption></figure><p>As we can see that on left the app is full screen and on left the system UI is visible hence affecting our application UI.</p><p>To fix this, we need to know when the keyboard is visible and once we know, we can hide the system UI if it’s visible.<br>Let’s add some code for this:</p><pre>final View activityRootView = findViewById(R.id.<em>activityRoot</em>);<br>activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {<br>    @Override<br>    public void onGlobalLayout() {<br>        Rect r = new Rect();<br>        //r will be populated with the coordinates of your view that area still visible.<br>        activityRootView.getWindowVisibleDisplayFrame(r);<br><br>        int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);<br>        if (heightDiff &gt; 100) { // if more than 100 pixels, its probably a keyboard...<br>            hideSystemUI();<br>        }<br>    }<br>});</pre><p>here activityRoot is the id of the root layout in the xml of the activity.<br>Now we shall not face any problem..</p><p>CHEERS.</p><h3><strong>May the source be with you!!</strong></h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5f5a94667ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install different versions of same app on same device- Android]]></title>
            <link>https://medium.com/@prakharsrivastava_219/install-different-versions-of-same-app-on-same-device-android-e34e030aa745?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/e34e030aa745</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-sdk]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[androiddev]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Thu, 21 Dec 2017 09:57:06 GMT</pubDate>
            <atom:updated>2017-12-21T09:57:06.315Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello folks,<br>Ever wanted to install QA and Prod builds of your application on same device!<br>Whenever we try to install the different version of app, it replaces the previous one.</p><p>We can achieve this by using the <a href="https://developer.android.com/studio/build/build-variants.html"><strong>build variant</strong></a> in android and its product flavors.</p><p>It’s very simple, only 2-step process.</p><h4>Step 1: Define the flavors:</h4><p>Defining the flavors is a very easy task, that we do in app level <strong>build.gradle.</strong></p><pre>android {<br>    compileSdkVersion 26<br>    buildToolsVersion &#39;26.0.0&#39;<br>    <br>    defaultConfig {---}<br>    buildTypes {---}<br><br>    productFlavors {<br>        qa {<br>            applicationIdSuffix &quot;.qa&quot;<br>            versionCode 1<br>            versionName &quot;1.0&quot;<br>        }<br><br>        demo {<br>            applicationIdSuffix &quot;.demo&quot;<br>            versionCode 1<br>            versionName &quot;1.0&quot;<br>        }<br><br>        dev {<br>            applicationIdSuffix &quot;.dev&quot;<br>            versionCode 1<br>            versionName &quot;1.0&quot;<br>        }<br><br>        uat {<br>            applicationIdSuffix &quot;.uat&quot;<br>            versionCode 1<br>            versionName &quot;1.0&quot;<br>        }<br>    }<br>}</pre><p>Build your projects after this.</p><h4>Step 2: Generating a specific build</h4><p>After building the project, you can select a build variant from all the option that we added as flavors in the build.gradle and when you run/generate an apk, tha apk is generated for that particular flavor.</p><p>The build variant can be selected at the bottom left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*UA1JeMdepxQweLUWqaCXiA.jpeg" /></figure><p>Once you click on <strong>build-variants</strong>, you will get another window with a drop-down to select a variant:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*_WXbN0tqCb0KRj24CJ_ufA.jpeg" /></figure><p>Now select a variant and generate a build.</p><p>So suppose now I want a build on QA environment. I make the changes in app APIs definition, select the QA option from build variant and install a build.<br>Again, I will change the API definitions to PROD, select the Prod option from build variants and install a build.</p><p>And done! Now you have two builds of your app installed on your device. One pointing to QA and other pointing to UAT.</p><blockquote>Please write to srivastava.prakhar91@gmail in case of any clarification</blockquote><h3>May the source be with you.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e34e030aa745" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Schedule your task for internet and relax.]]></title>
            <link>https://medium.com/@prakharsrivastava_219/schedule-your-task-for-internet-and-relax-b98e5fdb77fa?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/b98e5fdb77fa</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[android-jobs]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Thu, 27 Jul 2017 11:01:50 GMT</pubDate>
            <atom:updated>2017-07-27T11:01:50.972Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey android developers, I bet every one faces a problem handling network connection while making server transaction calls. <strong>Firstly</strong> you check if the internet is connected or not. <strong>Secondly</strong> you check if the internet is working or not and <strong>Thirdly</strong> handle your task that requires internet.</p><p>The commonly used approach for it is, you save your Request somewhere and the next time user opens the app, you check if there is any non-executed request there and internet is there, you execute it.</p><p>But heyyyyy, why bro why… why that much of pain when android keeps improving day by day with new features. The feature we are going to discuss about today is <strong>Android Job Scheduler</strong>.</p><h3>Android Job Scheduler</h3><p>Must have seen some apps, which allows you to proceed only when you are connected to wifi, or when the charger is plugged in. These actions can be performed easily using JobScheduler. In this lesson we will be doing the internet handling. You can more details on the <a href="https://developer.android.com/reference/android/app/job/JobScheduler.html">official android documentation.</a></p><p>When I mean handling the internet connection, I refer to the ability of Jobscheduler to keep the data persistence. So even if your app is in backgound or removed from background too or even if the phone is rebooted, your task is executed for sure.</p><h4>The code:</h4><p>Create a <strong>JobService </strong>which contains a onStart() method which is executed. So your service looks like this</p><pre>public class MyJobService extends JobService {<br><br>    public MyJobService() {<br>    }<br><br>    @Override<br>    public boolean onStartJob(JobParameters params) {<br><br>       Toast.makeText(this,&quot;Executed&quot;,Toast.LENGTH_LONG).show();<br>  /*<br>   * True - if your service needs to process<br>   * the work (on a separate thread).<br>   * False - if there&#39;s no more work to be done for this job.<br>   */<br>        return false;<br>    }<br><br>    @Override<br>    public boolean onStopJob(JobParameters params) {<br>      <br>        return false;<br>    }<br><br>}</pre><p>So whenever the internet comes, this toast will be fired.</p><h4>How to start the JobService:</h4><pre>jobScheduler = (JobScheduler)getSystemService(<em>JOB_SCHEDULER_SERVICE</em>);<br>ComponentName jobService = new ComponentName(getPackageName(), MyJobService.class.getName());<br>JobInfo jobInfo = new JobInfo.Builder(<em>MYJOBID</em>,jobService).setRequiredNetworkType(JobInfo.<em>NETWORK_TYPE_ANY</em>). build();<br>jobScheduler.schedule(jobInfo);</pre><p>here jobscheduler is an instance of JobScheduler and MYJOBID issome integer.</p><pre>JobScheduler jobScheduler;<br>int <em>MYJOBID </em>= 1;</pre><p>You can send the data with the into the JobScheduler using a PersistableBundle .</p><pre>PersistableBundle bundle = new PersistableBundle();<br>bundle.putString(&quot;name&quot;,&quot;Bruce Wayne&quot;);<br>bundle.putInt(&quot;age&quot;,43);<br>bundle.putBoolean(isSuperhero,true);</pre><p>and then we can add this bundle in JobInfo builder</p><pre>JobInfo jobInfo = new JobInfo.Builder(<em>MYJOBID</em>,jobService).setRequiredNetworkType(JobInfo.<em>NETWORK_TYPE_ANY</em>).setExtras(bundle). build();</pre><p>And lastly, register the JobService in the manifest.</p><pre>&lt;service<br>    android:name=&quot;.MyJobService&quot;<br>    android:exported=&quot;true&quot;<br>    android:permission=&quot;android.permission.BIND_JOB_SERVICE&quot; /&gt;</pre><p>Done. Now do whatever you want and the toast will be fired whenever internet connection is available.</p><blockquote>Write to srivastava.prakhar91@gmail.com for any clarifiations.</blockquote><h3>May the source be with you.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b98e5fdb77fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android development -Working with a designer.]]></title>
            <link>https://medium.com/@prakharsrivastava_219/android-development-working-with-a-designer-bb9c4aafc5b5?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb9c4aafc5b5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[android-design]]></category>
            <category><![CDATA[android-design-patterns]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Tue, 11 Jul 2017 09:42:17 GMT</pubDate>
            <atom:updated>2017-07-11T09:52:27.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CxPUhTZ5437ALZKJN3_BCQ.gif" /><figcaption>image source : <a href="https://dribbble.com/shots/3437005-Designer-vs-Developer-Rebound-challenge">https://dribbble.com/shots/3437005-Designer-vs-Developer-Rebound-challenge</a></figcaption></figure><p>Working with designer? Damn it’s so difficult, isn’t it? <strong>No it’s not,</strong> if you have a taste for designs.<br>I crave for good designs. I find it very interesting that how can there be infinite ways to represent something, each one better than the other. But again, designs are considered good depending on who’s taste it matches. Some people like glossy designs, some like it mat.</p><p>I have worked with developers who were struck for the release just because they didn’t have an icon, email icon. Can you believe it, an email icon in 4 sizes, that’s all was needed for the project to release a build.</p><p>So in this lesson, we’ll see how to reduce the work of designers and hence playing nice to them (winks!).</p><h3>1. Ask for icons in only one size and any color.</h3><p>Always ask for the icons in only size. The perfect size would be <strong>128 X 128.<br></strong>But we have to keep the icons in 4 sizes in four different drawable directories.<br>This is where you get to see the cooler side of android studio. You can create sharp different sized drawables in any color using the <strong>image-asset</strong> tool.</p><ul><li>Right click on drawable folder and new image asset.<br><strong>drawable(right click) &gt; new &gt; Image Asset</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*G3HzrlkoOxK1mEQJg1Yiew.png" /></figure><ul><li>In the next window, choose the type of icon you want. For all the <strong>tabs</strong> and <strong>drawable_left/right </strong>icons, the <strong>ActionBar &amp; Tab Icons</strong> works perfectly.<br>Choose asset type <strong>image</strong> and color as <strong>custom</strong>. The designer will give you the color code and you can generate the icon in that color.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*cL1FwGsz2xprSxagvbURyQ.png" /></figure><p>Same thing for launcher and notification icons.</p><p>You got it working. See easy.. only one size and the color code.. remember.</p><h3>2. Avoid asking for color codes</h3><p>Don’t ask for color codes.<br>If you have the screen designs, you can extract every color out of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7FmtMD-ajED1HmWPqRAYg.png" /></figure><p>Download the software <a href="http://www.wincatalog.com/getcolor.html"><strong>getcolor</strong> </a>for free and use the eye dropper tool anywhere on screen (not only on mages but absolutely anywhere).</p><p><a href="http://www.wincatalog.com/getcolor.html"><strong>Download it here</strong></a></p><h3>3. <strong>Fonts and spacing</strong></h3><p>Stop asking for the .ttf or .otf files for font, if the font is free.<br>We can find it on our own. Just type the name of the font and append <strong>ttf/font download.</strong> The designer does the same thing and finds the font.</p><p>Also, the fonts can be identified from an image on the websites like<br><a href="https://www.whatfontis.com/"><strong>what font is</strong></a><strong>, </strong>but they are not very reliable. So the font name should be mentioned by the designers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*vlnIlAgLJkMBkZQ3IcrW-g.jpeg" /><figcaption>image source : <a href="https://helpx.adobe.com/indesign/how-to/adjust-letter-spacing.html">https://helpx.adobe.com/indesign/how-to/adjust-letter-spacing.html</a></figcaption></figure><p>In the above image, we can see how the spacing impacts the design and how significant it is.</p><p>A lot of developers do everything right but miss the letter-spacing. The colors are perfect, font type and size are perfect, icons are perfect.. But when the psd and the xml design are matched, they don’t look same. The reason is letter-spacing, that the designer knew is important and we developers chose to ignore. The letter spacing can be added in android with a line in xml</p><pre>android:letterSpacing=&quot;YOUR_VALUE sp&quot;</pre><p>Also, one should take care of the shadows. The elevations and shadows adds a lot in the beautification of the design. In android, the shadows and elevation can be defined by adding one line in the xml</p><pre>android:elevation=&quot;YOUR_VALUE dp&quot;</pre><p>This is how designer and developers together can deliver a great product. Share the responsibilities.</p><blockquote>These are a few of the time saving hacks for designers as well as developers for android. There are a lot more tricks, that I will cover in upcoming blogs.<br>But these are the easiest and most needed, so make sure you get them right</blockquote><h3>May the source be with you.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb9c4aafc5b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Places search and Cab Booking Apps]]></title>
            <link>https://medium.com/@prakharsrivastava_219/place-search-for-cab-booking-apps-62fdb2820b55?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/62fdb2820b55</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[google-maps]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Mon, 10 Jul 2017 10:12:54 GMT</pubDate>
            <atom:updated>2017-07-11T09:52:51.821Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://github.com/shree-vastava/CabDemo"><strong>Full Source Code</strong></a></h4><h4><a href="https://drive.google.com/open?id=0By7L2nmxrhMZYzJyS21CNlBIX3M">Download apk</a></h4><p>All of us have used apps like Uber and Ola and find it really fascinating. The smooth process of booking a cab using the apps is a very happy experience. And the biggest facility these apps provide is places search and marking on the map. So you don’t have to write the full address as it auto completes it and also you can be sure if the address picked up by it is correct or not by looking at the map.</p><p>Today we’ll be building the same functionality where one can search the places and select it, marking it on map and getting every detail of the place available on google.<br>Let’s look at what are we building today :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*3FywZR1wYX44iN8vDtaakg.jpeg" /></figure><p>It looks excellent and yet it is very easy..<br>Let’s divide our solution in three parts :</p><ul><li>Non coding part (Using Google Api Console).</li><li>Loading Map on screen (surprisingly it takes only a minute.. yes! that simple, thanks to android studio)</li><li>Places search functionality.</li></ul><p>So let’s start building.</p><h3>Using Google Api Console</h3><p>For using google maps in our application, we have to create an API key on the <a href="https://console.developers.google.com/">google developer’s console</a>. This API key is later placed in our app and users can see maps in our app. So let’s create the key.</p><ul><li>Create a new Project on Developer’s console</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jlJ3oMhkdhM8U9sf_a-4w.png" /></figure><p>Click on the add icon on top and when it prompts, provide a <strong>project name</strong> and continue.<br>Once the project is created, it will take you directly to the dashboard.</p><ul><li>Now on the top, we can see the button for <strong>Enable APIs</strong>. Click on that button.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5EqrCss-_hQQsVr0x9_tg.png" /></figure><p>Now after clicking on that Button, we can see a lot of APIs listed. We have to select the Maps and Places API for android under <strong>Google Maps API </strong>section and click on enable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3H-t8jrhufbg3ZkmCC9WSg.png" /></figure><ul><li>Once the APIs are enabled, from the dashboard or library screen, we migrate to <strong>credentials</strong> screens.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1pgcfVp_uMBY24EPtaMrA.png" /></figure><ul><li>After clicking the Credentials, on the next screen, We’ll click <br><strong>Create Credentials &gt; API key</strong><br>And copy the API key somewhere, may be on a text file (we’ll be needing this key shortly).</li></ul><p>That’s all. Now we have created the project, enabled the APIs and generated an API key to use.</p><p>Now let’s move to the coding part and create a project in android studio.</p><h3>Create and load map on screen.</h3><p>Everytime we create a new project in Android Studio, we create an activity, remember? So this time while creating the project, we’ll select the <strong>GoogleMapsActivity </strong>option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B8Osjxb3ejn7JISoqUEUJw.png" /></figure><p>Now sit back, relax, eat some cheetos, grab some coffee may be and let the gradle build.<br>When the gradle build is completed, the file <strong>google_maps_api.xml</strong> should be visible on screen. If it is not, open it from the location <strong>Res &gt; Values &gt; google_maps_api.xml.</strong></p><p>When the xml is opened. Put the API key that we created a minute back in place of <strong>API_KEY_HERE. </strong>And it should look like</p><pre>&lt;string name=”google_maps_key” templateMergeStrategy=”preserve” translatable=”false”&gt;<br>AIz*********************Ug<br>&lt;/string&gt;</pre><p>ignore the asterisks above and put your full key in place of it.</p><p>DONE! run your app on device and you should see the map and a marker in Sydney. The Marker in Sydney is shown because it is hard coded in the <strong>MapsActivity.java</strong> by default.</p><pre>@Override<br>public void onMapReady(GoogleMap googleMap) {<br>    mMap = googleMap;<br><br>    Add a marker in Sydney and move the camera<br>    LatLng sydney = new LatLng(-34, 151);<br>    mMap.addMarker(new MarkerOptions().position(sydney).title(&quot;Marker in Sydney&quot;));<br>    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));<br>}</pre><p>onMapReady() is the function that is called when the map is loaded and ready for any operations. So Android Studio by default puts a marker on Sydney when Map is ready.</p><h3>Places Search Functionality</h3><p>First things first.. add the following library from google in <strong>build.gradle</strong>.<br> It is used for searching the places that we type.</p><pre>compile &#39;com.google.android.gms:play-services-places:10.2.4&#39;</pre><p>Now the UI.<br>When we created the project, the <strong>activity_maps.xml</strong> included only a fragment over which the map is loaded. So that fragment takes full screen.</p><p>So now we’ll put the fragment in a relative layout along with an <strong>EditText.</strong> So the fragment still takes the full screen but now we have an EditText over it (Since both are in a single RelativeLayout). So our layout looks like this :</p><pre>&lt;RelativeLayout<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:map=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;&gt;<br>&lt;fragment<br>    android:id=&quot;@+id/map&quot;<br>    android:name=&quot;com.google.android.gms.maps.SupportMapFragment&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;demo.shree.cabsplaces.MapsActivity&quot; /&gt;<br><br>    &lt;EditText<br>        android:id=&quot;@+id/where&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:hint=&quot;Where to?&quot;<br>        android:focusableInTouchMode=&quot;false&quot;<br>        android:layout_margin=&quot;30dp&quot;<br>        android:padding=&quot;10dp&quot;<br>        android:textSize=&quot;15sp&quot;<br>        android:elevation=&quot;10dp&quot;<br>        android:background=&quot;@drawable/rectangle&quot;/&gt;<br>&lt;/RelativeLayout&gt;</pre><p>We have EditText to search for the places. But it doesn’t search for anything written in the EditText (trust me!).<br>Actually, on click of the EditText, a fragment is loaded where we search. This fragment is loaded by google only, we don’t need to make this fragment in our design.</p><p>So the only thing we need to do is fire the intent on EditText click.</p><pre>whereEdtTxt.setOnClickListener(new View.OnClickListener() {<br>    @Override<br>    public void onClick(View v) {<br>        try {<br>            Intent intent =<br>                    new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.<em>MODE_OVERLAY</em>)<br>                            .build(MapsActivity.this);<br>            startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);<br>        } catch (GooglePlayServicesRepairableException e) {<br>            // <em>TODO: Handle the error.<br>        </em>} catch (GooglePlayServicesNotAvailableException e) {<br>            // <em>TODO: Handle the error.<br>        </em>}<br>    }<br>});</pre><p>Now we can search and select any place that is on google.<br>But after the selection we need the details of the page back. How do we do that?<br>Simple, we override the onActivityResult and get the place details. Once we have details, we mark it on the map using the marker.</p><pre>@Override<br>protected void onActivityResult(int requestCode, int resultCode, Intent data) {<br>    if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {<br>        if (resultCode == <em>RESULT_OK</em>) {<br>            Place place = PlaceAutocomplete.<em>getPlace</em>(this, data);<br>            whereEdtTxt.setText(place.getName().toString());<br>            mMap.addMarker(new MarkerOptions().position(place.getLatLng()).title(place.getName().toString()));<br>            mMap.animateCamera(CameraUpdateFactory.<em>newLatLngZoom</em>(place.getLatLng(), 12.0f));<br><br>        } else if (resultCode == PlaceAutocomplete.<em>RESULT_ERROR</em>) {<br>            Status status = PlaceAutocomplete.<em>getStatus</em>(this, data);<br>            // <em>TODO: Handle the error.<br>            </em>Log.<em>i</em>(&quot;Map&quot;, status.getStatusMessage());<br><br>        } else if (resultCode == <em>RESULT_CANCELED</em>) {<br>            // The user canceled the operation.<br>        }<br>    }<br>}</pre><h4>That’s all. Now run the app and it should work perfectly.</h4><p>Some important functions that the places API provide are:</p><pre>Place Name: place.getName()<br>Latitude: place.getLatLng().latitude<br>Longitude: place.getLatLng().longitude<br>Address: place.getAddress()<br>Phone Number: place.getPhoneNumber()<br>Rating: place.getRating()<br>Website: place.getWebsiteUri()</pre><p>Try putting these in onActivityResult and look what you get.</p><blockquote>I have included the Sample Project that is really easy. Just replace my key with yours and you can get it working. You can also see the app in action before trying, just to see how it looks, by downloading the apk for which I have provided the link.</blockquote><h4><a href="https://github.com/shree-vastava/CabDemo">Full Source Code</a></h4><h4><a href="https://drive.google.com/open?id=0By7L2nmxrhMZYzJyS21CNlBIX3M">Download apk</a></h4><h3>May the source be with you.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62fdb2820b55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep the user logged in android app.]]></title>
            <link>https://medium.com/@prakharsrivastava_219/keep-the-user-logged-in-android-app-5fb6ce29ed65?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fb6ce29ed65</guid>
            <category><![CDATA[android-hacks]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-studio]]></category>
            <category><![CDATA[android-apps]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 08:12:59 GMT</pubDate>
            <atom:updated>2017-07-11T09:53:14.077Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, in this lesson, we will see how to keep the user logged in android apps.<br>We have seen in almost every app that the user logs in for the first time and the next time he opens the app, he goes straight inside the app without authentication.<br>Let’s try doing it in a simple way. We will build an app for that. The app will contain two screens</p><ul><li><strong>Login screen : </strong>This will have a button. Once we click the button we will go to MainActivity.</li><li><strong>MainActivity : </strong>The screen that user will come on after login.</li></ul><p>So we will be trying to write the code so that the user clicks on the button and goes to the MainActivity for the first time, and from the next time onwards, he directly goes to MainActivity when he opens the app.</p><p>Let’s write the code for LoginActivity. The button and the intent on the click event of button. Simple.</p><p><strong>activity_login.xml</strong></p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>android.support.constraint.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;demo.shree.login.LoginActivity&quot;</strong>&gt;<br><br>    &lt;<strong>Button<br>        android:id=&quot;@+id/loginBtn&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;Login&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintLeft_toLeftOf=&quot;parent&quot;<br>        app:layout_constraintRight_toRightOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; </strong>/&gt;<br><br>&lt;/<strong>android.support.constraint.ConstraintLayout</strong>&gt;</pre><p>In the java file, lets take reference and click event on the button.</p><p><strong>LoginActivity.java</strong></p><pre><strong>login </strong>= (Button) findViewById(R.id.<strong><em>loginBtn</em></strong>);</pre><p>now let’s write a method to move to the MainActivity. This function will contain only the Intent, nothing complex.</p><pre><strong>public void </strong>goToMainActivity(){<br>    Intent i = <strong>new </strong>Intent(<strong>this</strong>,MainActivity.<strong>class</strong>);<br>    startActivity(i);<br>}</pre><p>Now let’s call this function on the button click</p><pre><strong>login</strong>.setOnClickListener(<strong>new </strong>View.OnClickListener() {<br>    @Override<br>    <strong>public void </strong>onClick(View v) {<br>        goToMainActivity();<br>        <strong>sp</strong>.edit().putBoolean(<strong>&quot;logged&quot;</strong>,<strong>true</strong>).apply();<br>    }<br>});</pre><p>So the LoginActivity.java looks like this</p><pre><strong>public class </strong>LoginActivity <strong>extends </strong>AppCompatActivity {<br><br>    Button <strong>login</strong>;<br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.<strong><em>activity_login</em></strong>);<br><br>        <strong>login </strong>= (Button) findViewById(R.id.<strong><em>loginBtn</em></strong>);</pre><pre>        <strong>login</strong>.setOnClickListener(<strong>new </strong>View.OnClickListener() {<br>            @Override<br>            <strong>public void </strong>onClick(View v) {<br>                goToMainActivity();<br>                <strong>sp</strong>.edit().putBoolean(<strong>&quot;logged&quot;</strong>,<strong>true</strong>).apply();<br>            }<br>        });<br>    }<br><br>    <strong>public void </strong>goToMainActivity(){<br>        Intent i = <strong>new </strong>Intent(<strong>this</strong>,MainActivity.<strong>class</strong>);<br>        startActivity(i);<br>    }<br>}</pre><p>Now we will be applying the logic to remain logged in, So the summary of the steps up to now</p><ul><li>A button and it’s initialization</li><li>A function <strong>goToMainActivity() </strong>having the intent.</li><li>Calling the function on button click. So when the user clicks the button, intent is called and he goes to MainActivity.</li></ul><h3>SharedPreferences Overview</h3><p>SharedPreferences in android store values in key-value fashion.<br>We initialize the SharedPreferenes with a particular name, which will be constant for the whole app. It is done as following.</p><pre>SharedPreferences sp = getSharedPreferences(NAME_IN_STRING, MODE)</pre><p>so we will be initializing in our app with name “login” and mode “private”. it looks like</p><pre><strong>sp </strong>= getSharedPreferences(<strong>&quot;login&quot;</strong>,<strong><em>MODE_PRIVATE</em></strong>);</pre><p>For storing values in SharedPreferences, we use <strong>edit() </strong>and then put the keys and values of corresponding data type.</p><pre>sp.edit().putDATA_TYPE(KEY,VALUE).apply();</pre><p>For example:</p><pre>sp.edit().putString(&quot;name&quot;,&quot;Bruce Wayne&quot;).apply();<br>sp.edit().putInt(&quot;age&quot;,30).apply();<br>sp.edit().putBoolean(&quot;isSuperhero&quot;,true).apply();</pre><p>So here in first one, we are saving a String value. We have our own key name and we are putting the value Bruce Wayne.</p><p>In second one, we are saving an Integer value. Our key is age and the value is 30.</p><p>In third, we are saving a Boolean value. Our key is isSuperHero and the value is true.</p><p>As we can see that we are defining our keys ourselves. So we know which key stores which value. So while retrieving the values, we use this key and the default value.</p><pre>sp.getDATA_TYPE(KEY, DEFAULT_VALUE) </pre><p>this will give the value for that particular key. <br>Let’s try getting the three values back which we saved above.</p><pre>sp.getString(&quot;name&quot;,&quot;&quot;) //this will give us <strong>Bruce Wayne</strong>. Notice that <strong>&quot;&quot;</strong> is the default value for String</pre><pre>sp.getInt(&quot;age&quot;,0) // this will give us <strong>30</strong>. Notice that <strong>0</strong> is the default value for integer.</pre><pre>sp.getBoolean(&quot;isSuperHero&quot;, false) //this will give us <strong>true. </strong>Notice that <strong>false</strong> is the default value for Boolean</pre><p>Now that we know how to use SharedPrefernces, let’s try using it in our application.</p><h3><strong>Applying SharedPreferences logic in our app</strong></h3><p>Editing the LoginActivity, let’s add and initialize the SharedPreferences.</p><pre>SharedPreferences <strong>sp</strong>;<br><strong>sp </strong>= getSharedPreferences(<strong>&quot;login&quot;</strong>,<strong><em>MODE_PRIVATE</em></strong>);</pre><p>now <strong>sp</strong> is ready to store values. <br>To check if the user is logged in once into the app, let’s save a boolean value <strong>isLogged</strong> into sp after login is completed.</p><pre><strong>sp</strong>.edit().putBoolean(<strong>&quot;logged&quot;</strong>,<strong>true</strong>).apply();</pre><p>and every time the activity starts, check for the value. If we get <strong>true, </strong>it means login is completed, because only after login, we are making it true. If we get <strong>false,</strong> it means login is not done, because the default value of Boolean is false.<br>So if we know that user has logged in already, we will send him to MainActivity directly and login screen will skip.</p><p>in <strong>onCreate()</strong></p><pre><strong>if</strong>(<strong>sp</strong>.getBoolean(<strong>&quot;logged&quot;</strong>,<strong>false</strong>)){<br>    goToMainActivity();<br>}</pre><p>So the whole code of <strong>LoginActivity.java </strong>looks like:</p><pre><strong>public class </strong>LoginActivity <strong>extends </strong>AppCompatActivity {<br><br>    Button <strong>login</strong>;<br>    SharedPreferences <strong>sp</strong>;<br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        setContentView(R.layout.<strong><em>activity_login</em></strong>);<br><br>        <strong>login </strong>= (Button) findViewById(R.id.<strong><em>loginBtn</em></strong>);<br>       <strong> <br>        sp = getSharedPreferences(&quot;login&quot;,<em>MODE_PRIVATE</em>);</strong><br><br>        <strong>if</strong>(<strong>sp</strong>.getBoolean(<strong>&quot;logged&quot;</strong>,<strong>false</strong>)){<br>            goToMainActivity();<br>        }<br><br>        <strong>login</strong>.setOnClickListener(<strong>new </strong>View.OnClickListener() {<br>            @Override<br>            <strong>public void </strong>onClick(View v) {<br>                goToMainActivity();<br>                <strong>sp</strong>.edit().putBoolean(<strong>&quot;logged&quot;</strong>,<strong>true</strong>).apply();<br>            }<br>        });<br>    }<br><br>    <strong>public void </strong>goToMainActivity(){<br>        Intent i = <strong>new </strong>Intent(<strong>this</strong>,MainActivity.<strong>class</strong>);<br>        startActivity(i);<br>    }<br>}</pre><h3>Summary</h3><ul><li>When LoginActivity is launched, we check for isLogged value in SharedPreferences. Since we haven’t saved any value for it, it will return <strong>false </strong>and our if condition will fail and normal LoginActivity code will be executed.</li><li>When the user completes login process, we will save a value true for isLogged in the Sharedpreferences. So isLogged which was <strong>false </strong>before is <strong>true </strong>now.</li><li>Next time the user launches LoginActivity, again the if condition will be checked but this time the value of <strong>isLogged</strong> is <strong>true</strong> as we made it true in previous step. So instead of the normal code, the code inside if block will be executed and the user will be sent to MainActivity directly.</li></ul><p>Hope this helps</p><blockquote>in case of any queries, write to me at<br>srivastava.prakhar91@gmail.com</blockquote><h3>May the source be with you.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fb6ce29ed65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating custom menu in android (Part-3/3 : Menu Implementation)]]></title>
            <link>https://medium.com/@prakharsrivastava_219/creating-custom-menu-in-android-part-3-3-menu-implementation-e28c96c7c029?source=rss-be79a07df57------2</link>
            <guid isPermaLink="false">https://medium.com/p/e28c96c7c029</guid>
            <category><![CDATA[android-design]]></category>
            <category><![CDATA[menu-design]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android-design-patterns]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Prakhar Srivastava]]></dc:creator>
            <pubDate>Tue, 04 Jul 2017 11:49:11 GMT</pubDate>
            <atom:updated>2017-07-11T09:53:38.180Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@prakharsrivastava_219/creating-custom-menu-in-android-part-1-3-menu-design-b51a13a7d018"><strong>Part 1 here</strong></a></p><p><a href="https://medium.com/@prakharsrivastava_219/creating-custom-menu-in-android-part-2-3-the-action-bar-2fe55d421e1c"><strong>Part 2 here</strong></a></p><p><a href="https://drive.google.com/open?id=0By7L2nmxrhMZZzYyYzZTVDN3MlU"><strong>Download the apk here</strong></a></p><p><a href="https://github.com/shree-vastava/CustomMenu"><strong>Full Source Code</strong></a></p><p>Up to now we have our menu design ready as well as the tool bar designed and integrated. Now let’s continue to integrating menu in the application.<br>We will use a Fragment for the menu. So whenever we click on the hamburger icon, the Fragment is loaded with animation over the Activity.</p><p>So let’s create the fragment with our custom menu as xml.</p><p><strong>MenuFragment.java</strong></p><pre><strong>public class </strong>MenuFragment <strong>extends </strong>Fragment{<br><br>    GestureDetector <strong>gestureDetector</strong>;<br>    @Override<br>    <strong>public </strong>View onCreateView(LayoutInflater inflater, ViewGroup container,<br>                             Bundle savedInstanceState) {<br>        View rootView = inflater.inflate(R.layout.<strong><em>slide_menu</em></strong>, container, <strong>false</strong>);<br>       <em><br>        </em><strong>return </strong>rootView;<br>    }<br>}</pre><p>That’s it! Our fragment is ready.<br>Now we have a screen i.e java+xml design ready to be shown on screen on any click event. And we will do it with animation. We will slide the menu in from top when to show and slide it up again when to hide.</p><p>So put these animation files in anim folder in res.</p><p><strong>slide_up.xml</strong></p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>set xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</strong>&gt;<br>    &lt;<strong>translate android:fromYDelta=&quot;0%&quot; android:toYDelta=&quot;-100%&quot; android:duration=&quot;500&quot;</strong>/&gt;<br>&lt;/<strong>set</strong>&gt;</pre><p><strong>slide_down.xml</strong></p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>set xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</strong>&gt;<br>    &lt;<strong>translate android:fromYDelta=&quot;-100%&quot; android:toYDelta=&quot;0%&quot; android:fillAfter = &quot;true&quot; android:duration=&quot;500&quot;</strong>/&gt;<br>&lt;/<strong>set</strong>&gt;</pre><p>Now we will edit our MainActivity.java and load the fragment on menu click and hide it again when the menu icon is clicked again. But where do we load the fragment?<br>In a FrameLayout that acts as a container. this FrameLayout is created in activity_main.xml</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;</strong>&gt;<br><br>    &lt;<strong>FrameLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:id=&quot;@+id/container&quot;</strong>&gt;<br><br>        &lt;<strong>TextView<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;match_parent&quot;<br>            android:layout_margin=&quot;20dp&quot;<br>            android:text=&quot;sample&quot;</strong>/&gt;<br>    &lt;/<strong>FrameLayout</strong>&gt;<br>&lt;/<strong>LinearLayout</strong>&gt;</pre><p>Now, loading the fragment in container. So the full code of MainActivity is changed to :</p><pre><strong>public class </strong>MainActivity <strong>extends </strong>BaseActivity {<br><br>    <strong>boolean isFragmentLoaded</strong>;<br>    Fragment <strong>menuFragment</strong>;<br>    TextView <strong>title</strong>;<br>    ImageView <strong>menuButton</strong>;<br><br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br>        initAddlayout(R.layout.<strong><em>activity_main</em></strong>);<br><br>        <strong>title </strong>= (TextView) findViewById(R.id.<strong><em>title_top</em></strong>);<br>        <strong>menuButton </strong>= (ImageView) findViewById(R.id.<strong><em>menu_icon</em></strong>);<br>        <strong>title</strong>.setText(<strong>&quot;Menu Activity&quot;</strong>);<br>        <strong>menuButton</strong>.setOnClickListener(<strong>new </strong>View.OnClickListener() {<br>            @Override<br>            <strong>public void </strong>onClick(View v) {<br>                <strong>if</strong>(!<strong>isFragmentLoaded</strong>) {<br>                    loadFragment();<br>                    <strong>title</strong>.setText(<strong>&quot;Profile&quot;</strong>);<br>                }<br>                <strong>else </strong>{<br>                    <strong>if </strong>(<strong>menuFragment </strong>!= <strong>null</strong>) {<br>                        <strong>if </strong>(<strong>menuFragment</strong>.isAdded()) {<br>                            hideFragment();<br>                        }<br>                    }<br>                }<br>            }<br>        });<br>    }<br><br>    <strong>public void </strong>hideFragment(){<br>        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();<br>        fragmentTransaction.setCustomAnimations(R.anim.<strong><em>slide_down</em></strong>, R.anim.<strong><em>slide_up</em></strong>);<br>        fragmentTransaction.remove(<strong>menuFragment</strong>);<br>        fragmentTransaction.commit();<br>        <strong>menuButton</strong>.setImageResource(R.drawable.<strong><em>ic_menu</em></strong>);<br>        <strong>isFragmentLoaded </strong>= <strong>false</strong>;<br>        <strong>title</strong>.setText(<strong>&quot;Main Activity&quot;</strong>);<br>    }<br>    <strong>public void </strong>loadFragment(){<br>        FragmentManager fm = getSupportFragmentManager();<br>        <strong>menuFragment </strong>= fm.findFragmentById(R.id.<strong><em>container</em></strong>);<br>        <strong>menuButton</strong>.setImageResource(R.drawable.<strong><em>ic_up_arrow</em></strong>);<br>        <strong>if</strong>(<strong>menuFragment </strong>== <strong>null</strong>){<br>            <strong>menuFragment </strong>= <strong>new </strong>MenuFragment();<br>            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();<br>            fragmentTransaction.setCustomAnimations(R.anim.<strong><em>slide_down</em></strong>, R.anim.<strong><em>slide_up</em></strong>);<br>            fragmentTransaction.add(R.id.<strong><em>container</em></strong>,<strong>menuFragment</strong>);<br>            fragmentTransaction.commit();<br>        }<br><br>        <strong>isFragmentLoaded </strong>= <strong>true</strong>;<br>    }<br>}</pre><p>Now let’s break it down.</p><ul><li>We have created a function <strong>loadFragment().</strong> In this function we create a new Fragment of our MenuFragment class that we created earlier.</li><li>We load this fragment in the FrameLayout that we created in the activity_main.xml with the slide down animation.</li><li>When we load the Fragment, we change the hamburger icon to an arrow icon.</li><li>We have another function <strong>hideFragment().</strong> In this function, we remove the previously loaded Fragment with slide up animation and change the icon back to hamburger.</li></ul><p>DONE! we have successfully created custom menu in an application. Create any design for your menu and load it as fragment .Now build and run the app.</p><blockquote><em>Do write to me in case of any doubt or clarification.<br>srivastava.prakhar91@gmail.com</em></blockquote><h3>May the source be with you.</h3><p><a href="https://medium.com/@prakharsrivastava_219/creating-custom-menu-in-android-part-1-3-menu-design-b51a13a7d018"><strong>Part 1 here</strong></a></p><p><a href="https://medium.com/@prakharsrivastava_219/creating-custom-menu-in-android-part-2-3-the-action-bar-2fe55d421e1c"><strong>Part 2 here</strong></a></p><p><a href="https://drive.google.com/open?id=0By7L2nmxrhMZZzYyYzZTVDN3MlU"><strong>Download the apk here</strong></a></p><p><a href="https://github.com/shree-vastava/CustomMenu"><strong>Full Source Code</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e28c96c7c029" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>