<?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 Monika Joshi on Medium]]></title>
        <description><![CDATA[Stories by Monika Joshi on Medium]]></description>
        <link>https://medium.com/@monikajoshimj1?source=rss-ba350809cae3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*GcYkQ-7Tyu_GUtdu</url>
            <title>Stories by Monika Joshi on Medium</title>
            <link>https://medium.com/@monikajoshimj1?source=rss-ba350809cae3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:07:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@monikajoshimj1/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[Obstacle game using HTML, CSS and Vanilla JS]]></title>
            <link>https://monikajoshimj1.medium.com/obstacle-game-using-html-css-and-vanilla-js-e8a979790bc9?source=rss-ba350809cae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8a979790bc9</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[vanillajs]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Monika Joshi]]></dc:creator>
            <pubDate>Thu, 02 Sep 2021 11:45:54 GMT</pubDate>
            <atom:updated>2021-09-02T11:45:54.486Z</atom:updated>
            <content:encoded><![CDATA[<p>“GO BEAN” is the obstacle game that I made using HTML , CSS and Vanilla Java Script. The main idea for the working of the game is quite simple , I am taking 2 characters in the game Mr. Bean and Mrs. Wicket ; Mrs. Wicket is actually acting as the obstacle and Mr. Bean has to jump over her every time she come near him. Summarizing the basic idea : I am gonna make my obstacle animate infinite times (till the game ends) and Mr. bean’s animation will be triggered by the arrow key. Player will save Mr. bean from continuously animating Mrs. Wicket by making him jump over her.</p><p>Here’s the preview:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b_HUyQ1z6d45wv2nmEITvw.png" /><figcaption>Mrs. Wicket approaching to Mr. bean</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CMszXbR3rGPJi8BYg4YpOQ.png" /><figcaption>Jumping Mr. Bean</figcaption></figure><p>These pictures can not totally elaborate what is going on exactly in the game , so you can check this out on GitHub :</p><p><a href="https://github.com/Monikajoshi2001/Go-Bean">GitHub - Monikajoshi2001/Go-Bean: An obstacle game with Mr. Bean and Mrs. Wicket</a></p><p>Let’s talk about the structure of the page , its quite simple :</p><p>we are using a background element and we have 4 elements over the background 1) Mr. Bean 2) Mrs. Wicket 3) Score Box 4) Game Over box . So this makes our html file really simple with 4 div nested within 1 div element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*bGHVma8Iu1RSDUeguwgs5Q.png" /></figure><p>Now talking about the styling of our container class (Gamecontainer ); we are gonna have a background image here, in the styling code below make sure that background occupy the full viewport.</p><blockquote>.Gamecontainer{</blockquote><blockquote>width: 100%;</blockquote><blockquote>height: 100vh;</blockquote><blockquote>background-image: url(https://medium.com/background.jpg);</blockquote><blockquote>background-repeat: no-repeat;</blockquote><blockquote>background-size: 100vw 100vh;</blockquote><blockquote>}</blockquote><p>Putting Mr. Bean and Mrs. Wicket in their places and adding animation to Mrs. Wicket. So here I want Mrs. Wicket to do the continuous animation (till the game is over (Bean and Wicket collide) . We’ll see the logic for collision later , for now I have to keep Mrs. Wicket moving ; so I am gonna have linear animation on Mrs. Wicket for infinite times .</p><blockquote>.bean{</blockquote><blockquote>background-image: url(https://medium.com/Mrbean.png);</blockquote><blockquote>background-repeat: no-repeat;</blockquote><blockquote>width: 150px;</blockquote><blockquote>height: 270px;</blockquote><blockquote>background-size: cover;</blockquote><blockquote>position: absolute;</blockquote><blockquote>bottom: 0;</blockquote><blockquote>}</blockquote><blockquote>.obstacle{</blockquote><blockquote>background-image: url(https://medium.com/mrsWicket.png);</blockquote><blockquote>background-repeat: no-repeat;</blockquote><blockquote>width: 150px;</blockquote><blockquote>height: 270px;</blockquote><blockquote>background-size: cover;</blockquote><blockquote>position: absolute;</blockquote><blockquote>bottom: 0;</blockquote><blockquote>right: 0;</blockquote><blockquote>}</blockquote><p>The Animation Class:</p><blockquote>.obstacleAnimation{</blockquote><blockquote>animation: obst_Ani 2.0s linear infinite;</blockquote><blockquote>}</blockquote><blockquote>@keyframes obst_Ani{</blockquote><blockquote>0%{</blockquote><blockquote>left: 100vw;</blockquote><blockquote>}</blockquote><blockquote>100%{</blockquote><blockquote>left: -10vw;</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><p>Now , I want movement of Mr. Bean as follows :</p><ol><li>On the press of up arrow key , he should jump.</li><li>On the press of left and right arrow key , he should be able to shift to some position left and right respectively. For this shifting , I will get the original ‘left property value’ of the bean first and then shift him to left and right by adding and substracting some value(112px here) to/from his original ‘left property value’.</li></ol><p>So, basically our bean will move “OnKeyDown” :</p><blockquote>document.onkeydown=function(e)</blockquote><blockquote>{</blockquote><blockquote>console.log(“key code is : “,e.keyCode);</blockquote><blockquote>if(e.keyCode==38)//up key</blockquote><blockquote>{</blockquote><blockquote>bean=document.querySelector(“.bean”);</blockquote><blockquote>bean.classList.add(“beanAnimation”);</blockquote><blockquote>setTimeout(()=&gt;{</blockquote><blockquote>bean.classList.remove(“beanAnimation”);</blockquote><blockquote>},700);</blockquote><blockquote>}</blockquote><blockquote>if(e.keyCode==39)//left key</blockquote><blockquote>{</blockquote><blockquote>bean=document.querySelector(“.bean”);</blockquote><blockquote>bean_x=parseInt(window.getComputedStyle(bean,null).getPropertyValue(‘left’));</blockquote><blockquote>bean.style.left=bean_x+112+”px”;</blockquote><blockquote>}</blockquote><blockquote>if(e.keyCode==37)//right key</blockquote><blockquote>{</blockquote><blockquote>bean=document.querySelector(“.bean”);</blockquote><blockquote>bean_x=parseInt(window.getComputedStyle(bean,null).getPropertyValue(‘left’));</blockquote><blockquote>bean.style.left=bean_x-112+”px”;</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><p>Explaination of the code :</p><p>When the Up arrow key(key code 38) is pressed ; I want to add an animation to the bean for 700 ms (after 700 ms animation will be removed from Bean he will come back to his actual position). The animation which I want to add on Bean is a jump animation. Basically I want to increase the distance of the Bean from the bottom of the frame. So my animation class for bean is going to be like :</p><blockquote>.beanAnimation{</blockquote><blockquote>animation: Bean_Ani 0.6s linear;</blockquote><blockquote>}</blockquote><blockquote>@keyframes Bean_Ani{</blockquote><blockquote>0%{</blockquote><blockquote>bottom: 0;</blockquote><blockquote>}</blockquote><blockquote>50%{</blockquote><blockquote>bottom: 300px;</blockquote><blockquote>}</blockquote><blockquote>100%{</blockquote><blockquote>bottom: 0;</blockquote><blockquote>}</blockquote><blockquote>}</blockquote><p>Now all we are left to do is : (a)detecting the collision ; if collision is found : Stop obstacle’s animation and display game over. If there is no collision : add 1 to the existing score.</p><p>Now let’s see , how can we find the collision :</p><p>If Mr. Bean and Mrs. Wicket are in proximity then there will be collision. So, firstly we have to find the position of Mr. Bean and Mrs. wicket and I can do that by ‘getPropertyvalue’.</p><blockquote>//finding current left and top position of bean</blockquote><blockquote>bean_x=parseInt(window.getComputedStyle(bean,null).getPropertyValue(‘left’));</blockquote><blockquote>bean_y=parseInt(window.getComputedStyle(bean,null).getPropertyValue(‘top’));</blockquote><blockquote>//finding current and top position of obstacle : Mrs. Wicket</blockquote><blockquote>obstacle_x=parseInt(window.getComputedStyle(obstacle,null).getPropertyValue(‘left’));</blockquote><blockquote>obstacle_y=parseInt(window.getComputedStyle(obstacle,null).getPropertyValue(‘top’));</blockquote><p>So, we got the top and left value of both Bean and wicket ; now check if they are in a porximity ;</p><p>if yes : display game over and stop Wicket’s animation.</p><p>if no : keep on adding in the score ; for score , we are taking a boolean variable ‘cross’ with initial value as true and we are going to update the score only when the value of ‘cross’ is true and we are gonna change the value of ‘cross’ back to false again after updating the score and will again set it to true after 1000ms(by this time Mrs. Wicket has already crossed the screen)</p><blockquote>//checking if there is a collision</blockquote><blockquote>offset_x=Math.abs(bean_x-obstacle_x);</blockquote><blockquote>offset_y=Math.abs(bean_y-obstacle_y);</blockquote><blockquote>if(offset_x&lt;92 &amp;&amp; offset_y&lt;52)</blockquote><blockquote>{</blockquote><blockquote>console.log(offset_x,offset_y);</blockquote><blockquote>gameover.style.visibility=”visible”;</blockquote><blockquote>obstacle.classList.remove(“obstacleAnimation”);</blockquote><blockquote>}</blockquote><blockquote>else if(offset_x&lt;145 &amp;&amp; cross){</blockquote><blockquote>score+=1;</blockquote><blockquote>updateScore(score);</blockquote><blockquote>cross=false;</blockquote><blockquote>setTimeout(() =&gt; {</blockquote><blockquote>cross=true;</blockquote><blockquote>}, 1000);</blockquote><blockquote>}</blockquote><p>This is all about this blog, complete code is in GitHub.</p><p>Thank You!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8a979790bc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array related problem in C++]]></title>
            <link>https://monikajoshimj1.medium.com/array-related-problem-in-c-b8423f875aca?source=rss-ba350809cae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8423f875aca</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[important]]></category>
            <category><![CDATA[arrays]]></category>
            <dc:creator><![CDATA[Monika Joshi]]></dc:creator>
            <pubDate>Wed, 19 May 2021 03:57:17 GMT</pubDate>
            <atom:updated>2021-05-19T03:57:17.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem :</p><p>Isayna is given number of visitors in her local park on N consecutive days. The number of visitors on the i-th day is Vi. A day is record breaking if it satisfies both the conditions :</p><ol><li>The number of visitor on the day is strictly larger than number of visitors on each of the previous days.</li><li>Either it is the last day, or or the number of visitors on the day is strictly larger than the number of visitors on the following day.</li></ol><p>Note that the very first day could be a record breaking day!</p><p>Please help Isayna to find out the number of record breaking days.</p><p>Solution :</p><p>//Finding number of record breaking Days.</p><p>#include&lt;iostream&gt;</p><p>using namespace std;</p><p>void Record_Breaking(int arr[], int n)</p><p>{</p><p>int record_breaking_days=0;</p><p>int max_of_prevDays=0;</p><p>for(int i=0;i&lt;n;i++)</p><p>{</p><p>if(max_of_prevDays&lt;arr[i]&amp;&amp; arr[i]&gt;arr[i+1])</p><p>{</p><p>record_breaking_days++;</p><p>}</p><p>max_of_prevDays=max(max_of_prevDays,arr[i]);</p><p>}</p><p>cout&lt;&lt;”No.of record Breaking Days are : “&lt;&lt;record_breaking_days&lt;&lt;endl;</p><p>}</p><p>int main()</p><p>{</p><p>int N;</p><p>cout&lt;&lt;”Enter the number of days Isyana worked in the park : “;</p><p>cin&gt;&gt;N;</p><p>int V[N];</p><p>cout&lt;&lt;”\nEnter the number of visitors she had each day : \n”;</p><p>for(int i=0;i&lt;N;i++)</p><p>{</p><p>cin&gt;&gt;V[i];</p><p>}</p><p>Record_Breaking(V,N);</p><p>return 0;</p><p>}</p><p>Thank you.!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8423f875aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Music App in Android Studio]]></title>
            <link>https://monikajoshimj1.medium.com/music-app-in-android-studio-a166ff0ecb7c?source=rss-ba350809cae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a166ff0ecb7c</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[music-apps]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[media-player]]></category>
            <dc:creator><![CDATA[Monika Joshi]]></dc:creator>
            <pubDate>Mon, 10 May 2021 14:22:48 GMT</pubDate>
            <atom:updated>2021-05-10T14:22:48.233Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s what the app gonna do:</p><p>It will show all the songs (.mp3 or .wav files) in a listView, when user will tap in any of the item in the list. Media player will start playing that song. It will also give user options to FastForward, Revind, Go to Next song, Go to Previous song, Play and Pause the song, go to aparticular part of song using progress bar.</p><p>I learnt :</p><ol><li>A lot about UI designs.</li><li>ListView</li><li>MediaPlayer</li></ol><p>Let’s start :</p><p><strong>res&gt;layout&gt;activity_main.xml</strong></p><p>Our main Activity will be a simple listView within a Relative Layout :</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;RelativeLayout 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;.MainActivity&quot;<br>    android:background=&quot;@color/black&quot;&gt;<br>    &lt;ListView<br>        android:id=&quot;@+id/Listsongs&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:divider=&quot;@android:color/transparent&quot;<br>        android:dividerHeight=&quot;10.0sp&quot;<br>        android:padding=&quot;8dp&quot;/&gt;<br>&lt;/RelativeLayout&gt;</pre><p>This listView was preety simple. So I decided to customize my list. Each item of my list is in the form of a card and this card has 2 views : ImageView and TextView. Here’s the sample of a card in listView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*nzHLfW2VgZTr80V6zqIEhQ.png" /><figcaption>This is how each item in the list will look like, its a card with 2 views; here this headset sign is an imageView and song name is the TextView.</figcaption></figure><p>Let’s see how to make this card for list items.</p><p><strong>res&gt;layout&gt;right-click&gt;new&gt;layout Resource File&gt;name (list_item.xml)</strong></p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.cardview.widget.CardView<br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_marginEnd=&quot;8dp&quot;<br>    android:layout_marginTop=&quot;8dp&quot;<br>    android:layout_marginStart=&quot;8dp&quot;&gt;<br>    &lt;RelativeLayout<br>        android:padding=&quot;8dp&quot;<br>        android:background=&quot;@drawable/list_bg&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;&gt;<br>        &lt;ImageView<br>            android:id=&quot;@+id/img_song&quot;<br>            android:layout_width=&quot;40dp&quot;<br>            android:layout_height=&quot;40dp&quot;<br>            android:layout_alignParentStart=&quot;true&quot;<br>            android:layout_alignParentTop=&quot;true&quot;<br>            android:background=&quot;@drawable/list_bg&quot;<br>            android:src=&quot;@drawable/ic_baseline_headset_24&quot;<br>            android:outlineAmbientShadowColor=&quot;@color/black&quot;/&gt;<br>        &lt;TextView<br>            android:id=&quot;@+id/song_name&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;40dp&quot;<br>            android:layout_alignParentEnd=&quot;true&quot;<br>            android:layout_marginStart=&quot;5dp&quot;<br>            android:layout_marginEnd=&quot;5dp&quot;<br>            android:layout_toRightOf=&quot;@+id/img_song&quot;<br>            android:padding=&quot;6dp&quot;<br>            android:textColor=&quot;@color/black&quot;<br>            android:text=&quot;Song name&quot;<br>            android:textStyle=&quot;italic&quot;<br>            android:textSize=&quot;15sp&quot;<br>            android:singleLine=&quot;true&quot;<br>            android:marqueeRepeatLimit=&quot;marquee_forever&quot;<br>            android:ellipsize=&quot;marquee&quot;<br>            android:scrollHorizontally=&quot;true&quot;/&gt;<br>    &lt;/RelativeLayout&gt;<br>&lt;/androidx.cardview.widget.CardView&gt;</pre><p>With the help of CardView we can display different views over each other. Here we are using relative layout within the card view bcz we want textView to be placed “toRightof” ImageView.</p><p><strong>ImageView</strong> : Here, the source of ImageView is from the vector. <strong>res&gt;drawable&gt;vector asset&gt;select a headset icon from there</strong>. Android Studio will create an xml file “@drawable/ic_baseline_headset_24.xml” for you; choose the color you want.</p><p><strong>TextView :</strong> Here, special thing about TextView is that it will be a single line irrespective of the length of the SongName. What if the length of the song name is too large to get accomodate inside the textView? Well then, rather than breaking the textView from the middle we will “ellipsize” it. (<em>Ellipsize means shortening the textView using “…” like “…aabb” or “aabb…”or “aa…bb” or we can give the output as “aabbcc” auto sliding from left to right, for this we need marquee</em>). Here we’re gonna use marquee, so if there’s a lengthy song name, complete song name in a single line will slide horizontally.</p><pre>android:marqueeRepeatLimit=&quot;marquee_forever&quot;<br>            android:ellipsize=&quot;marquee&quot;<br>            android:scrollHorizontally=&quot;true&quot;</pre><p><strong>Background :</strong> For the background of both ImageView and TextView , i wanted to have some different shapes and colours so i made a new drawable file “list_bg.xml” for that. <strong>res&gt;drawable&gt;right-click&gt;new&gt;drawable resource file&gt;name(list_bg.xml)</strong>. I choose rectangular shape and some color gradient as per my choice. Here’s the code for that:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    android:shape = &quot;rectangle&quot;<br>    &lt;gradient android:centerColor=&quot;#d3d3d3&quot;<br>        android:endColor=&quot;#7f7f7f&quot;<br>        android:startColor=&quot;#7f7f7f&quot; /&gt;<br>&lt;/shape&gt;</pre><p>With this we are done with the layout files for this very activity. Now we will implement the listView (display the items inside ListView).</p><p>So, we have to search for the songs(.mp3 or .wav files) in our phone and display the name of those files in our list (textView part of our list). This is what we will implement in this activity.</p><p>So, let’s start it :</p><p><strong>java&gt;package_name&gt;MainActivity.java :</strong></p><p>We will start by defining and initialising the views we are using in our Layout. Our main layout file is having only one View (ListView) although there are views within list view but we can’t define or initialise them for now. So;</p><pre>ListView listView;</pre><pre>listView = (ListView) findViewById(R.id.<em>Listsongs</em>);</pre><p>Now, as we are finding the music files that are within phone ; So we need a permission to read the external storage of the device. Also we will require one more permission i.e. Record Audio permission(why? we will see later). Add these permission in the “AndroidManifest.xml” :</p><pre>&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.RECORD_AUDIO&quot;/&gt;</pre><p>Here’s something new : We will ask permission from the user at the run time(while app started running) not while installing. There’s a class “Dexter” that simplify android runtime permissions . To learn more about Dexter, you can read from here.</p><p><a href="https://github.com/Karumi/Dexter">Karumi/Dexter</a></p><p>It will require you to add a dependency in build.gradle :</p><pre>implementation &#39;com.karumi:dexter:6.2.2&#39;</pre><p>Here we are going to add 2 runtime permissions; so our code will be :</p><pre>//Using Dexter to request the permission at runtime<br>public void RunTimePermission(){<br>    Dexter.<em>withContext</em>(MainActivity.this)<br>            .withPermissions(Manifest.permission.<em>READ_EXTERNAL_STORAGE</em>,Manifest.permission.<em>RECORD_AUDIO</em>)<br>            .withListener(new MultiplePermissionsListener() {<br>                @Override<br>                public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {<br>                    DisplaySongs();<br>                }<br>                @Override<br>                public void onPermissionRationaleShouldBeShown(List&lt;PermissionRequest&gt; list, PermissionToken permissionToken) {<br>                    permissionToken.continuePermissionRequest();<br>                }<br>            }).check();<br>}</pre><p>We will talk about permission listener here :</p><p>It overrides 2 methods ;</p><ul><li><strong>onPermissionsChecked()</strong> will be called if all permissions are granted.</li><li><strong>onPermissionRationaleShouldBeShown() </strong>will be called if the user has already declined the permission once.This method contains PermissionToken parameter using which you can call any of the two methods :</li><li><strong><em>continuePermissionRequest() </em></strong><em>: Continues with the permission request process.(the one we are using here in our case)</em></li><li><strong><em>cancelPermissionRequest()</em></strong><em> : Cancels the permission request process.</em></li></ul><p>So, here in this code snippet we are saying that : if our app will get the permission then we will call a method “DisplaySongs()” (discuss this method later) ; if user will deny the permission app will request again again.</p><p>With this, permission part is done.</p><p>Now we will find the songs from our devices. So basically we are going to look if there is any .mp3 or .wav file in our device’s storage, and after finding them i am going to add these files in an arrayList. This ArrayList is going to conatin all music files present in the external storage of my device. Code Snippet for the method to perform this function :</p><pre>//finding the list of songs (.mp3 / .wav) files in the external //storage<br>public ArrayList&lt;File&gt; FindSong(File file)<br>{<br>    ArrayList&lt;File&gt; arrayList = new ArrayList&lt;&gt;();<br>    File[] files = file.listFiles();<br>    for(File singlefile:files)<br>    {<br>        if(singlefile.isDirectory() &amp;&amp; !singlefile.isHidden())<br>        {<br>            arrayList.addAll(FindSong(singlefile));<br>        }<br>        else{<br>            if(singlefile.getName().endsWith(&quot;.mp3&quot;)||singlefile.getName().endsWith(&quot;.wav&quot;))<br>            {<br>                arrayList.add(singlefile);<br>            }<br>        }<br>    }<br>    return arrayList;<br>}</pre><p>Argument : (File) We will pass the absolute path for our External Directory as the argument for this funtion.</p><p>Return : it will return the arrayList containing the abstract pathnames of the files within this directory(that we pass as an argument).</p><p>Working : We will create an array of the abstract pathnames of the files within the directory (that we passed as an argument). We will iterate through this array and denote each file as “singleFile” . We will check if singleFile is an unhidden directory or not : (a) if yess; we will find the files within this directory(make a reccurssive call to this method) (b) if no; we will check if file name is ending with “.mp3” or “.wav” and add this file in our array list.</p><p>We now have an arrayList with all music files in our device. Now we will display the name of these Music Files in our ListView. So; firstly let’s extract the name of these music files and store it in some array. We can do this by :</p><pre>final ArrayList&lt;File&gt; mySongs = FindSong(Environment.<em>getExternalStorageDirectory</em>().getAbsoluteFile());<br>//adding the name of these music files in an Array of String<br>items = new String[mySongs.size()];<br>for(int i=0;i&lt;mySongs.size();i++)<br>{<br>    items[i]= mySongs.get(i).getName().toString().replace(&quot;.mp3&quot;,&quot;&quot;).replace(&quot;wav&quot;,&quot;&quot;);<br>}</pre><p>We extracted the name of the music Files and stored it in “item[]” array.</p><p>Now item[] exactly contains the content that we will show in our listView. To show the data of item[] array in ListView we need CustomAdapter(bcz our listView is customized, it contains 2 views listView and ImageView and we have to fill the data in TextView only).</p><pre>//class for customized listView<br> class CustomAdapter extends BaseAdapter{<br>     @Override<br>     public int getCount() {<br>         return items.length;<br>     }<br>     @Override<br>     public Object getItem(int position) {<br>         return null;<br>     }<br>     @Override<br>     public long getItemId(int position) {<br>         return 0;<br>     }<br>     @Override<br>     public View getView(int position, View convertView, ViewGroup parent) {<br>         View myView = getLayoutInflater().inflate(R.layout.<em>list_item</em>,null);<br>         TextView song_name = myView.findViewById(R.id.<em>song_name</em>);<br>         song_name.setSelected(true);<br>         song_name.setText(items[position]);<br>         return myView;<br>     }<br> }</pre><p>getView() method in this class returns the View to be displayed inside the parent View(ListView in our case). Here we want the layout we defined in “list_item.xml” to be the view of each child in the ListView. So we will inflate our listView with the same layout.</p><pre>View myView = getLayoutInflater().inflate(R.layout.<em>list_item</em>,null);</pre><p>Next we want is the name of song to appear in the TextView we defined in “list_item.xml” by this snippet:</p><pre>TextView song_name = myView.findViewById(R.id.<em>song_name</em>);<br>song_name.setSelected(true);<br>song_name.setText(items[position]);</pre><p>Finally we will return the myView.</p><p>And with this our CustomAdapter is ready ; we will now call this CustomAdapter for our ListView.</p><pre>CustomAdapter customAdapter = new CustomAdapter();<br>listView.setAdapter(customAdapter);</pre><p>With this our List is ready; now all we want from this activity is that; if user will click any of the list item , he will be directed to next activity where we will play the song. So we have to create a new activity <strong>(java&gt;package_name&gt;right-click&gt;new&gt;activity&gt;empty activity&gt;name (Music_Player)</strong></p><p>On the click of any item; we will move to the “Music_Player” activity where this song will be played. So, we have to call an intent on the click of items in ListView and we have to send some of the song’s credentials from the list to the other activity. This function wil achieve this :</p><pre>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {<br>    @Override<br>    public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {<br>        String songName = (String) listView.getItemAtPosition(position);<br>        startActivity(new Intent(getApplicationContext(),Music_Player.class)<br>        .putExtra(&quot;songs&quot;,mySongs)<br>        .putExtra(&quot;song_name&quot;,songName)<br>        .putExtra(&quot;pos&quot;,position));<br>    }<br>});</pre><p>We are passing key for ArrayList(having list of all music files), Song_name, Position (of song in list) from this Activity to Music_player Activity.</p><p>Some of the code snippet i defined above Together forms the function DisplaySongs() :</p><pre>void DisplaySongs()<br>{<br>    final ArrayList&lt;File&gt; mySongs = FindSong(Environment.<em>getExternalStorageDirectory</em>().getAbsoluteFile());<br>    //adding the name of these music files in an Array of String<br>    items = new String[mySongs.size()];<br>    for(int i=0;i&lt;mySongs.size();i++)<br>    {<br>        items[i]= mySongs.get(i).getName().toString().replace(&quot;.mp3&quot;,&quot;&quot;).replace(&quot;wav&quot;,&quot;&quot;);<br>    }<br>    //Array adapter will add the contents of the string array in list View<br>   /* ArrayAdapter&lt;String&gt; myAdapter = new ArrayAdapter&lt;String&gt;(MainActivity.this, android.R.layout.simple_list_item_1, items);<br>    listView.setAdapter(myAdapter);*/<br>    CustomAdapter customAdapter = new CustomAdapter();<br>    listView.setAdapter(customAdapter);<br>    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {<br>        @Override<br>        public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {<br>            String songName = (String) listView.getItemAtPosition(position);<br>            startActivity(new Intent(getApplicationContext(),Music_Player.class)<br>            .putExtra(&quot;songs&quot;,mySongs)<br>            .putExtra(&quot;song_name&quot;,songName)<br>            .putExtra(&quot;pos&quot;,position));<br>        }<br>    });<br>}</pre><p>Complete Java class:</p><p>MainActivity.java :</p><pre>package com.example.mymusic;<br><br>import androidx.appcompat.app.AppCompatActivity;<br><br>import android.Manifest;<br>import android.content.Intent;<br>import android.os.Bundle;<br>import android.os.Environment;<br>import android.view.View;<br>import android.view.ViewGroup;<br>import android.widget.AdapterView;<br>import android.widget.ArrayAdapter;<br>import android.widget.BaseAdapter;<br>import android.widget.ListView;<br>import android.widget.TextView;<br><br>import com.karumi.dexter.Dexter;<br>import com.karumi.dexter.MultiplePermissionsReport;<br>import com.karumi.dexter.PermissionToken;<br>import com.karumi.dexter.listener.PermissionDeniedResponse;<br>import com.karumi.dexter.listener.PermissionGrantedResponse;<br>import com.karumi.dexter.listener.PermissionRequest;<br>import com.karumi.dexter.listener.multi.MultiplePermissionsListener;<br>import com.karumi.dexter.listener.single.PermissionListener;<br><br>import java.io.File;<br>import java.util.ArrayList;<br>import java.util.List;<br><br>public class MainActivity extends AppCompatActivity {<br>    ListView listView;<br>    String[] items;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_main</em>);<br>        listView = (ListView) findViewById(R.id.<em>Listsongs</em>);<br>        RunTimePermission();<br><br>    }<br>    //Using Dexter to request the permission at runtime<br>    public void RunTimePermission(){<br>        Dexter.<em>withContext</em>(MainActivity.this)<br>                .withPermissions(Manifest.permission.<em>READ_EXTERNAL_STORAGE</em>,Manifest.permission.<em>RECORD_AUDIO</em>)<br>                .withListener(new MultiplePermissionsListener() {<br>                    @Override<br>                    public void onPermissionsChecked(MultiplePermissionsReport multiplePermissionsReport) {<br>                        DisplaySongs();<br>                    }<br>                    @Override<br>                    public void onPermissionRationaleShouldBeShown(List&lt;PermissionRequest&gt; list, PermissionToken permissionToken) {<br>                        permissionToken.continuePermissionRequest();<br>                    }<br>                }).check();<br>    }<br><br>    //finding the list of songs (.mp3 / .wav) files in the external storage<br>    public ArrayList&lt;File&gt; FindSong(File file)<br>    {<br>        ArrayList&lt;File&gt; arrayList = new ArrayList&lt;&gt;();<br>        File[] files = file.listFiles();<br>        for(File singlefile:files)<br>        {<br>            if(singlefile.isDirectory() &amp;&amp; !singlefile.isHidden())<br>            {<br>                arrayList.addAll(FindSong(singlefile));<br>            }<br>            else{<br>                if(singlefile.getName().endsWith(&quot;.mp3&quot;)||singlefile.getName().endsWith(&quot;.wav&quot;))<br>                {<br>                    arrayList.add(singlefile);<br>                }<br>            }<br>        }<br>        return arrayList;<br>    }<br><br>    //to display the songs in listView<br>    void DisplaySongs()<br>    {<br>        final ArrayList&lt;File&gt; mySongs = FindSong(Environment.<em>getExternalStorageDirectory</em>().getAbsoluteFile());<br>        //adding the name of these music files in an Array of String<br>        items = new String[mySongs.size()];<br>        for(int i=0;i&lt;mySongs.size();i++)<br>        {<br>            items[i]= mySongs.get(i).getName().toString().replace(&quot;.mp3&quot;,&quot;&quot;).replace(&quot;wav&quot;,&quot;&quot;);<br>        }<br>        //Array adapter will add the contents of the string array in list View<br>       /* ArrayAdapter&lt;String&gt; myAdapter = new ArrayAdapter&lt;String&gt;(MainActivity.this, android.R.layout.simple_list_item_1, items);<br>        listView.setAdapter(myAdapter);*/<br>        CustomAdapter customAdapter = new CustomAdapter();<br>        listView.setAdapter(customAdapter);<br>        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {<br>            @Override<br>            public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {<br>                String songName = (String) listView.getItemAtPosition(position);<br>                startActivity(new Intent(getApplicationContext(),Music_Player.class)<br>                .putExtra(&quot;songs&quot;,mySongs)<br>                .putExtra(&quot;song_name&quot;,songName)<br>                .putExtra(&quot;pos&quot;,position));<br>            }<br>        });<br>    }<br><br>   //class for customized listView<br>    class CustomAdapter extends BaseAdapter{<br>        @Override<br>        public int getCount() {<br>            return items.length;<br>        }<br>        @Override<br>        public Object getItem(int position) {<br>            return null;<br>        }<br>        @Override<br>        public long getItemId(int position) {<br>            return 0;<br>        }<br>        @Override<br>        public View getView(int position, View convertView, ViewGroup parent) {<br>            View myView = getLayoutInflater().inflate(R.layout.<em>list_item</em>,null);<br>            TextView song_name = myView.findViewById(R.id.<em>song_name</em>);<br>            song_name.setSelected(true);<br>            song_name.setText(items[position]);<br>            return myView;<br>        }<br>    }<br>}</pre><p>Now ; Let’s move to Music_Player Activity :</p><p>Let’s Design the UI for Music_Player Activity. So in this activity, we need Name of Song, Play and Pause Button, Fast Forward Button(forward song for 10sec), Revind Button(revind song 10 sec backward), Next Button(move to next song), Previous Button(move to previous song), seek bar (to slide through the song)and am gonna use an image view, a background, a bar visualiser to make it look nice. Here’s what we will get after designing the layout :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*cpw0_kHmNi3vAZb7Qzv_zQ.png" /></figure><p>Choose the background Image of your choice and paste it in the drawable folder, similarly choose the image you want for the imageView and paste it. We will need some of the clipart for the buttons. So create these Vector Asset in your drawable folder :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*dOhKk4Z4AH-uwCjkadmYNQ.png" /></figure><p>We are done with all our pre-requisites; lets head to the “activity_music__player.xml” :</p><p>Here’s how we gonna devide it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3nRjBrZ5EPIfU3DUkMGcQ.png" /><figcaption>Here’s the layout devision of the UI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*_D7GXxgwa53O_emTHz02nw.png" /></figure><p>So, <strong>res&gt;layout&gt;activity_music__player.xml</strong> :</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;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:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    tools:context=&quot;.Music_Player&quot;<br>    android:background=&quot;@drawable/bg&quot;<br>    android:orientation=&quot;vertical&quot;<br>    android:weightSum=&quot;10&quot;&gt;<br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        android:layout_weight=&quot;7&quot;<br>        android:gravity=&quot;center&quot;<br>        android:orientation=&quot;vertical&quot;&gt;<br>    &lt;TextView<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:id=&quot;@+id/text1&quot;<br>        android:layout_margin=&quot;20dp&quot;<br>        android:ellipsize=&quot;marquee&quot;<br>        android:marqueeRepeatLimit=&quot;marquee_forever&quot;<br>        android:padding=&quot;10dp&quot;<br>        android:singleLine=&quot;true&quot;<br>        android:text=&quot;Song Name&quot;<br>        android:textColor=&quot;@color/white&quot;<br>        android:textAlignment=&quot;center&quot;<br>        android:textStyle=&quot;italic&quot;/&gt;<br>        &lt;ImageView<br>            android:id=&quot;@+id/song_icon&quot;<br>            android:layout_width=&quot;200dp&quot;<br>            android:layout_height=&quot;200dp&quot;<br>            android:layout_marginBottom=&quot;8dp&quot;<br>            android:src=&quot;@drawable/headphone&quot;/&gt;<br>        &lt;RelativeLayout<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;60dp&quot;&gt;<br>            &lt;SeekBar<br>                android:id=&quot;@+id/seek_bar&quot;<br>                android:layout_centerInParent=&quot;true&quot;<br>                android:layout_alignParentBottom=&quot;true&quot;<br>                android:layout_margin=&quot;20dp&quot;<br>                android:layout_marginBottom=&quot;40dp&quot;<br>                android:layout_width=&quot;250dp&quot;<br>                android:layout_height=&quot;wrap_content&quot;/&gt;<br><br>            &lt;TextView<br>                android:id=&quot;@+id/txtStart&quot;<br>                android:layout_width=&quot;wrap_content&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_centerInParent=&quot;true&quot;<br>                android:layout_alignParentLeft=&quot;false&quot;<br>                android:layout_marginLeft=&quot;20dp&quot;<br>                android:layout_toLeftOf=&quot;@id/seek_bar&quot;<br>                android:text=&quot;0:10&quot;<br>                android:textColor=&quot;@color/white&quot;<br>                android:textSize=&quot;14sp&quot; /&gt;<br><br>            &lt;TextView<br>                android:id=&quot;@+id/txtStop&quot;<br>                android:layout_width=&quot;wrap_content&quot;<br>                android:layout_height=&quot;wrap_content&quot;<br>                android:layout_centerInParent=&quot;true&quot;<br>                android:layout_alignParentRight=&quot;false&quot;<br>                android:layout_marginRight=&quot;20dp&quot;<br>                android:layout_toRightOf=&quot;@id/seek_bar&quot;<br>                android:text=&quot;4:10&quot;<br>                android:textColor=&quot;@color/white&quot;<br>                android:textSize=&quot;14sp&quot; /&gt;<br>        &lt;/RelativeLayout&gt;<br>    &lt;/LinearLayout&gt;<br><br>    &lt;LinearLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        android:layout_weight=&quot;3&quot;&gt;<br><br>        &lt;RelativeLayout<br>            android:layout_width=&quot;match_parent&quot;<br>            android:layout_height=&quot;wrap_content&quot;&gt;<br><br>            &lt;Button<br>                android:id=&quot;@+id/playbtn&quot;<br>                android:layout_width=&quot;70dp&quot;<br>                android:layout_height=&quot;70dp&quot;<br>                android:layout_centerHorizontal=&quot;true&quot;<br>                android:background=&quot;@drawable/ic_baseline_pause_24&quot; /&gt;<br><br>            &lt;Button<br>                android:id=&quot;@+id/btnNext&quot;<br>                android:layout_width=&quot;50dp&quot;<br>                android:layout_height=&quot;50dp&quot;<br>                android:layout_marginTop=&quot;15dp&quot;<br>                android:layout_toRightOf=&quot;@id/playbtn&quot;<br>                android:background=&quot;@drawable/ic_baseline_skip_next_24&quot; /&gt;<br><br>            &lt;Button<br>                android:id=&quot;@+id/btnPrev&quot;<br>                android:layout_width=&quot;50dp&quot;<br>                android:layout_height=&quot;50dp&quot;<br>                android:layout_marginTop=&quot;15dp&quot;<br>                android:layout_toLeftOf=&quot;@id/playbtn&quot;<br>                android:background=&quot;@drawable/ic_baseline_skip_previous_24&quot; /&gt;<br><br>            &lt;Button<br>                android:id=&quot;@+id/btnRevind&quot;<br>                android:layout_width=&quot;50dp&quot;<br>                android:layout_height=&quot;50dp&quot;<br>                android:layout_alignParentLeft=&quot;true&quot;<br>                android:layout_marginLeft=&quot;10dp&quot;<br>                android:layout_marginTop=&quot;15dp&quot;<br>                android:background=&quot;@drawable/ic_baseline_fast_rewind_24&quot; /&gt;<br><br>            &lt;Button<br>                android:id=&quot;@+id/btnFastForward&quot;<br>                android:layout_width=&quot;50dp&quot;<br>                android:layout_height=&quot;50dp&quot;<br>                android:layout_alignParentRight=&quot;true&quot;<br>                android:layout_marginTop=&quot;15dp&quot;<br>                android:layout_marginRight=&quot;10dp&quot;<br>                android:background=&quot;@drawable/ic_baseline_fast_forward_24&quot; /&gt;<br>            &lt;com.gauravk.audiovisualizer.visualizer.BarVisualizer<br>                xmlns:custom=&quot;http://schemas.android.com/apk/res-auto&quot;<br>                android:id=&quot;@+id/blast&quot;<br>                android:layout_width=&quot;match_parent&quot;<br>                android:layout_height=&quot;70dp&quot;<br>                android:layout_alignParentBottom=&quot;true&quot;<br>                custom:avDensity=&quot;0.5&quot;<br>                custom:avType=&quot;outline&quot;<br>                custom:avColor=&quot;#DF00FE&quot;<br>                custom:avWidth=&quot;4dp&quot;<br>                custom:avSpeed=&quot;normal&quot;/&gt;<br><br>        &lt;/RelativeLayout&gt;<br><br>    &lt;/LinearLayout&gt;<br><br>&lt;/LinearLayout&gt;</pre><p>Everything is quite familiar except</p><p>“com.gauravk.audiovisualizer.visualizer.BarVisualizer” this bar visualizer. So what is the bar visualizer? Where did we get this code for bar visualizer?</p><p><a href="https://github.com/gauravk95/audio-visualizer-android">gauravk95/audio-visualizer-android</a></p><p>Have a look at this for answer.</p><p>And also; you might remember that in the very starting we took a permission from user for Audio Record. Well; bcz bar visualizer don’t work without this permission.</p><p>Let’s see the Implementation of the views we have defined in layout file.</p><p><strong>java&gt;package_name&gt;Music_Player.java:</strong></p><p>Let’s start by defining and initialising the views.</p><pre>public class Music_Player extends AppCompatActivity {<br>    Button PlayBtn,NextBtn,PrevBtn,FastForwardBtn,RevindBtn;<br>    TextView Name_Song,txt_Start,txt_End;<br>    SeekBar seekBar;<br>    BarVisualizer barVisualizer;<br>    ImageView imageView;</pre><pre><br>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.<em>activity_music__player</em>);<br>PlayBtn = (Button)findViewById(R.id.<em>playbtn</em>);<br>NextBtn = (Button)findViewById(R.id.<em>btnNext</em>);<br>PrevBtn = (Button)findViewById(R.id.<em>btnPrev</em>);<br>FastForwardBtn = (Button)findViewById(R.id.<em>btnFastForward</em>);<br>RevindBtn = (Button)findViewById(R.id.<em>btnRevind</em>);<br>Name_Song = (TextView)findViewById(R.id.<em>text1</em>);<br>txt_Start = (TextView)findViewById(R.id.<em>txtStart</em>);<br>txt_End = (TextView)findViewById(R.id.<em>txtStop</em>);<br>seekBar = (SeekBar)findViewById(R.id.<em>seek_bar</em>);<br>barVisualizer = (BarVisualizer)findViewById(R.id.<em>blast</em>);<br>imageView = (ImageView) findViewById(R.id.<em>song_icon</em>);</pre><p>Let’s get the credentials of the song that we passed through intent in this activity.</p><pre>String Sname;<br>public static final String <em>EXTRA_NAME </em>= &quot;song_name&quot;;<br>int position;<br>ArrayList&lt;File&gt; mySongs;<br></pre><pre>Intent i = getIntent();<br>Bundle bundle=i.getExtras();<br>mySongs = (ArrayList)bundle.getParcelableArrayList(&quot;songs&quot;);<br>String SONG_NAME = (String)bundle.getString(&quot;song_name&quot;);<br>position= (int)bundle.getInt(&quot;pos&quot;,0);<br>Name_Song.setSelected(true);<br>Uri uri= Uri.<em>parse</em>(mySongs.get(position).toString());<br>Sname = mySongs.get(position).getName();<br>Name_Song.setText(Sname);</pre><p>Android studio provides us a MediaPlayer class to control audio/video playbacks. So we gonna use it here.</p><pre>MediaPlayer mediaPlayer;</pre><pre>if(mediaPlayer!=null)<br>{<br>    mediaPlayer.stop();<br>    mediaPlayer.release();<br>}<br><br>mediaPlayer = MediaPlayer.<em>create</em>(getApplicationContext(),uri);<br>mediaPlayer.start();</pre><p>Before starting the mediaPlayer; we should always check if it has already started or paused that media (mediaPlayer!=null); if that comes to be true; we are gonna stop that song and release the objects related to it.</p><p>Let’s work on the implementation of utility buttons now.</p><p>Play /pause Button :</p><pre>PlayBtn.setOnClickListener(new View.OnClickListener() {<br>    @Override<br>    public void onClick(View v) {<br>        if(mediaPlayer.isPlaying())<br>        {<br>            PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_play_arrow_24</em>);<br>            mediaPlayer.pause();<br>        }<br>        else<br>        {<br>            PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_pause_24</em>);<br>            mediaPlayer.start();<br>        }<br>    }<br>});</pre><p>if we clicked the button while already song is playing ; we are gonna pause it and the play_arrow will get set ; else we will start the song and replayce the sign with pause button.</p><p>FastForward and Revind Buttons :</p><pre>FastForwardBtn.setOnClickListener(new View.OnClickListener() {<br>    @Override<br>    public void onClick(View v) {<br>        if(mediaPlayer.isPlaying())<br>        {<br>            mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+10000);<br>        }<br>    }<br>});<br>RevindBtn.setOnClickListener(new View.OnClickListener() {<br>    @Override<br>    public void onClick(View v) {<br>        if(mediaPlayer.isPlaying())<br>        {<br>            mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-10000);<br>        }<br>    }<br>});</pre><p>seekTo (milisecond) function is used to shift to milisecond time forward or back. Here we are getting 10 sec forward or backward.</p><p>For NextBtn and PrevBtn we have to define some more methods first.</p><p>I want my image view to show some animation when i get to the next or previous song.</p><pre>public void StartAnimation(View view)<br>{<br>    ObjectAnimator animator= ObjectAnimator.<em>ofFloat</em>(imageView,&quot;rotation&quot;,0f,360f);<br>    animator.setDuration(1000);<br>    AnimatorSet animatorSet = new AnimatorSet();<br>    animatorSet.playTogether(animator);<br>    animatorSet.start();<br>}</pre><p>We are creating a rotation animation for the imageView of our layout and we want this animation to come into play whenever we will shift from present song to next or previous song.</p><p>For NextBtn :</p><pre>NextBtn.setOnClickListener(new View.OnClickListener() {<br>    @Override<br>    public void onClick(View v) {<br>        mediaPlayer.stop();<br>        mediaPlayer.release();<br>        position = (((position+1)==mySongs.size())?0:position+1);<br>        Uri u = Uri.<em>parse</em>(mySongs.get(position).toString());<br>        mediaPlayer = MediaPlayer.<em>create</em>(getApplicationContext(),u);<br>        Sname = mySongs.get(position).getName();<br>        Name_Song.setText(Sname);<br>        mediaPlayer.start();<br>        PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_pause_24</em>);<br>        StartAnimation(imageView);<br>        int audioSessionId = mediaPlayer.getAudioSessionId();<br>        if(audioSessionId!=-1)<br>        {<br>            barVisualizer.setAudioSessionId(audioSessionId);<br>        }<br>    }<br>});</pre><p>When NextBtn is clicked :</p><p>👍Stop the song that was playing previously and Release the objects related to it.</p><p>👍Update the “position” variable and with the help of “position” variable ; update Uri, Song Name, Start the mediaPlayer for thath song.</p><p>👍Change the sign to pause button; perform the animation; start the barVisualizer till the entire audio session (if the song is paused in between barVisualizer will stop itself)</p><p>Similarly; for PrevButton :</p><pre>PrevBtn.setOnClickListener(new View.OnClickListener() {<br>    @Override<br>    public void onClick(View v) {<br>        mediaPlayer.stop();<br>        mediaPlayer.release();<br>        position=((position-1)&lt;0)?mySongs.size()-1:(position-1);<br>        Uri uri1 = Uri.<em>parse</em>(mySongs.get(position).toString());<br>        mediaPlayer = MediaPlayer.<em>create</em>(getApplicationContext(),uri1);<br>        Sname = mySongs.get(position).getName();<br>        Name_Song.setText(Sname);<br>        mediaPlayer.start();<br>        PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_pause_24</em>);<br>        StartAnimation(imageView);<br>        int audioSessionId = mediaPlayer.getAudioSessionId();<br>        if(audioSessionId!=-1)<br>        {<br>            barVisualizer.setAudioSessionId(audioSessionId);<br>        }<br>    }<br>});</pre><p>When any song gets complete ; i want to switch to next song; so we will implement this by :</p><pre>mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {<br>    @Override<br>    public void onCompletion(MediaPlayer mp) {<br>        NextBtn.performClick();<br>    }<br>});</pre><p>Now let’s see the implementation of; how to get Current_Time and end_time on both the sides of SeekBar. End Time will always be the same i.e. the duration of the song. Create time is converting the time is milisecond to time in “min:sec” format.</p><pre>String endTime = createTime(mediaPlayer.getDuration());<br>txt_End.setText(endTime);</pre><pre>public String createTime(int duration)<br>    {<br>        String time =&quot;&quot;;<br>        int min = duration/1000/60;<br>        int sec = duration/1000%60;<br>        time+=min+&quot;:&quot;;<br>        if(sec&lt;10)<br>        {<br>            time+=&quot;0&quot;;<br>        }<br>        time+=sec;<br>        return time;<br>    }<br>}</pre><p>Now for current time :</p><pre>final Handler handler= new Handler();<br>final int Delay =1000;<br>handler.postDelayed(new Runnable() {<br>    @Override<br>    public void run() {<br>        String currentTime = createTime(mediaPlayer.getCurrentPosition());<br>        txt_Start.setText(currentTime);<br>        handler.postDelayed(this,Delay);<br>    }<br>},Delay);</pre><p>There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.</p><p>Here we are concerned with (1); we are going to schedule “runnables after some delay” ; Look in the code snippet above : we want to schedule a runnable after the delay of 1000ms (1 sec)</p><pre>public void run() {<br>        String currentTime = createTime(mediaPlayer.getCurrentPosition());<br>        txt_Start.setText(currentTime);<br>        handler.postDelayed(this,Delay);<br>    }</pre><p>We are setting currentTime in the text view after every one sec.</p><p>For seek bar:</p><p>We are making a new thread, after setting the max point at which seek bar can reach , we will start our new thread, which will set the position of seekbar according to the currentPosition of song. This thread will execute till the entire song is not completed.</p><pre>Thread updateSeekBar;</pre><pre>updateSeekBar= new Thread(){<br>    @Override<br>    public void run() {<br>        int totalDuration = mediaPlayer.getDuration();<br>        int currentPosition = 0;<br>        while(currentPosition&lt;totalDuration)<br>        {<br>            try {<br>                <em>sleep</em>(500);<br>                currentPosition= mediaPlayer.getCurrentPosition();<br>                seekBar.setProgress(currentPosition);<br>                }<br>            catch (InterruptedException | IllegalStateException e)<br>            {<br>                e.printStackTrace();<br>            }<br><br>        }<br>    }<br>};</pre><pre><br>seekBar.setMax(mediaPlayer.getDuration());<br>updateSeekBar.start();<br>seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {<br>    @Override<br>    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {<br><br>    }<br><br>    @Override<br>    public void onStartTrackingTouch(SeekBar seekBar) {<br><br>    }<br><br>    @Override<br>    public void onStopTrackingTouch(SeekBar seekBar) {<br>        mediaPlayer.seekTo(seekBar.getProgress());<br>    }<br>});</pre><p>Entire code for the mainActivity.java is :</p><pre>package com.example.mymusic;<br><br>import androidx.annotation.NonNull;<br>import androidx.appcompat.app.AppCompatActivity;<br><br>import android.animation.AnimatorSet;<br>import android.animation.ObjectAnimator;<br>import android.content.Intent;<br>import android.media.MediaPlayer;<br>import android.net.Uri;<br>import android.os.Bundle;<br>import android.os.Handler;<br>import android.view.MenuItem;<br>import android.view.View;<br>import android.widget.Button;<br>import android.widget.ImageView;<br>import android.widget.SeekBar;<br>import android.widget.TextView;<br><br>import com.gauravk.audiovisualizer.visualizer.BarVisualizer;<br><br>import java.io.File;<br>import java.util.ArrayList;<br><br>public class Music_Player extends AppCompatActivity {<br>    Button PlayBtn,NextBtn,PrevBtn,FastForwardBtn,RevindBtn;<br>    TextView Name_Song,txt_Start,txt_End;<br>    SeekBar seekBar;<br>    BarVisualizer barVisualizer;<br>    ImageView imageView;<br><br>    String Sname;<br>    public static final String <em>EXTRA_NAME </em>= &quot;song_name&quot;;<br>    int position;<br>    ArrayList&lt;File&gt; mySongs;<br>    MediaPlayer mediaPlayer;<br>    Thread updateSeekBar;<br><br>    @Override<br>    public boolean onOptionsItemSelected(@NonNull MenuItem item) {<br>        if(item.getItemId()==android.R.id.<em>home</em>){<br>            onBackPressed();<br>        }<br>        return super.onOptionsItemSelected(item);<br>    }<br><br>    @Override<br>    protected void onDestroy() {<br>        if (barVisualizer != null)<br>        {<br>            barVisualizer.release();<br>        }<br>        super.onDestroy();<br>    }<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_music__player</em>);<br><br>        getSupportActionBar().setTitle(&quot;Now Playing&quot;);<br>        getSupportActionBar().setDisplayHomeAsUpEnabled(true);<br>        getSupportActionBar().setDisplayShowHomeEnabled(true);<br><br>        PlayBtn = (Button)findViewById(R.id.<em>playbtn</em>);<br>        NextBtn = (Button)findViewById(R.id.<em>btnNext</em>);<br>        PrevBtn = (Button)findViewById(R.id.<em>btnPrev</em>);<br>        FastForwardBtn = (Button)findViewById(R.id.<em>btnFastForward</em>);<br>        RevindBtn = (Button)findViewById(R.id.<em>btnRevind</em>);<br>        Name_Song = (TextView)findViewById(R.id.<em>text1</em>);<br>        txt_Start = (TextView)findViewById(R.id.<em>txtStart</em>);<br>        txt_End = (TextView)findViewById(R.id.<em>txtStop</em>);<br>        seekBar = (SeekBar)findViewById(R.id.<em>seek_bar</em>);<br>        barVisualizer = (BarVisualizer)findViewById(R.id.<em>blast</em>);<br>        imageView = (ImageView) findViewById(R.id.<em>song_icon</em>);<br><br><br>        Intent i = getIntent();<br>        Bundle bundle=i.getExtras();<br>        mySongs = (ArrayList)bundle.getParcelableArrayList(&quot;songs&quot;);<br>        String SONG_NAME = (String)bundle.getString(&quot;song_name&quot;);<br>        position= (int)bundle.getInt(&quot;pos&quot;,0);<br>        Name_Song.setSelected(true);<br>        Uri uri= Uri.<em>parse</em>(mySongs.get(position).toString());<br>        Sname = mySongs.get(position).getName();<br>        Name_Song.setText(Sname);<br><br>        if(mediaPlayer!=null)<br>        {<br>            mediaPlayer.stop();<br>            mediaPlayer.release();<br>        }<br><br>        mediaPlayer = MediaPlayer.<em>create</em>(getApplicationContext(),uri);<br>        mediaPlayer.start();<br><br><br><br>        updateSeekBar= new Thread(){<br>            @Override<br>            public void run() {<br>                int totalDuration = mediaPlayer.getDuration();<br>                int currentPosition = 0;<br>                while(currentPosition&lt;totalDuration)<br>                {<br>                    try {<br>                        <em>sleep</em>(500);<br>                        currentPosition= mediaPlayer.getCurrentPosition();<br>                        seekBar.setProgress(currentPosition);<br>                        }<br>                    catch (InterruptedException | IllegalStateException e)<br>                    {<br>                        e.printStackTrace();<br>                    }<br><br>                }<br>            }<br>        };<br>        seekBar.setMax(mediaPlayer.getDuration());<br>        updateSeekBar.start();<br>        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {<br>            @Override<br>            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {<br><br>            }<br><br>            @Override<br>            public void onStartTrackingTouch(SeekBar seekBar) {<br><br>            }<br><br>            @Override<br>            public void onStopTrackingTouch(SeekBar seekBar) {<br>                mediaPlayer.seekTo(seekBar.getProgress());<br>            }<br>        });<br><br>        String endTime = createTime(mediaPlayer.getDuration());<br>        txt_End.setText(endTime);<br><br>        final Handler handler= new Handler();<br>        final int Delay =1000;<br>        handler.postDelayed(new Runnable() {<br>            @Override<br>            public void run() {<br>                String currentTime = createTime(mediaPlayer.getCurrentPosition());<br>                txt_Start.setText(currentTime);<br>                handler.postDelayed(this,Delay);<br>            }<br>        },Delay);<br><br>        PlayBtn.setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View v) {<br>                if(mediaPlayer.isPlaying())<br>                {<br>                    PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_play_arrow_24</em>);<br>                    mediaPlayer.pause();<br>                }<br>                else<br>                {<br>                    PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_pause_24</em>);<br>                    mediaPlayer.start();<br>                }<br>            }<br>        });<br><br>        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {<br>            @Override<br>            public void onCompletion(MediaPlayer mp) {<br>                NextBtn.performClick();<br>            }<br>        });<br>        int audioSessionId = mediaPlayer.getAudioSessionId();<br>        if(audioSessionId!=-1)<br>        {<br>            barVisualizer.setAudioSessionId(audioSessionId);<br>        }<br><br>        NextBtn.setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View v) {<br>                mediaPlayer.stop();<br>                mediaPlayer.release();<br>                position = (((position+1)==mySongs.size())?0:position+1);<br>                Uri u = Uri.<em>parse</em>(mySongs.get(position).toString());<br>                mediaPlayer = MediaPlayer.<em>create</em>(getApplicationContext(),u);<br>                Sname = mySongs.get(position).getName();<br>                Name_Song.setText(Sname);<br>                mediaPlayer.start();<br>                PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_pause_24</em>);<br>                StartAnimation(imageView);<br>                int audioSessionId = mediaPlayer.getAudioSessionId();<br>                if(audioSessionId!=-1)<br>                {<br>                    barVisualizer.setAudioSessionId(audioSessionId);<br>                }<br>            }<br>        });<br>        PrevBtn.setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View v) {<br>                mediaPlayer.stop();<br>                mediaPlayer.release();<br>                position=((position-1)&lt;0)?mySongs.size()-1:(position-1);<br>                Uri uri1 = Uri.<em>parse</em>(mySongs.get(position).toString());<br>                mediaPlayer = MediaPlayer.<em>create</em>(getApplicationContext(),uri1);<br>                Sname = mySongs.get(position).getName();<br>                Name_Song.setText(Sname);<br>                mediaPlayer.start();<br>                PlayBtn.setBackgroundResource(R.drawable.<em>ic_baseline_pause_24</em>);<br>                StartAnimation(imageView);<br>                int audioSessionId = mediaPlayer.getAudioSessionId();<br>                if(audioSessionId!=-1)<br>                {<br>                    barVisualizer.setAudioSessionId(audioSessionId);<br>                }<br>            }<br>        });<br><br>        FastForwardBtn.setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View v) {<br>                if(mediaPlayer.isPlaying())<br>                {<br>                    mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()+10000);<br>                }<br>            }<br>        });<br>        RevindBtn.setOnClickListener(new View.OnClickListener() {<br>            @Override<br>            public void onClick(View v) {<br>                if(mediaPlayer.isPlaying())<br>                {<br>                    mediaPlayer.seekTo(mediaPlayer.getCurrentPosition()-10000);<br>                }<br>            }<br>        });<br><br>    }<br>    public void StartAnimation(View view)<br>    {<br>        ObjectAnimator animator= ObjectAnimator.<em>ofFloat</em>(imageView,&quot;rotation&quot;,0f,360f);<br>        animator.setDuration(1000);<br>        AnimatorSet animatorSet = new AnimatorSet();<br>        animatorSet.playTogether(animator);<br>        animatorSet.start();<br>    }<br>    public String createTime(int duration)<br>    {<br>        String time =&quot;&quot;;<br>        int min = duration/1000/60;<br>        int sec = duration/1000%60;<br>        time+=min+&quot;:&quot;;<br>        if(sec&lt;10)<br>        {<br>            time+=&quot;0&quot;;<br>        }<br>        time+=sec;<br>        return time;<br>    }<br>}</pre><p>You can download the full project from here :</p><p><a href="https://github.com/Monikajoshi2001/My-Music">Monikajoshi2001/My-Music</a></p><p>Thank You.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a166ff0ecb7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Application to add Captured Photos  in a Gridview.]]></title>
            <link>https://monikajoshimj1.medium.com/android-application-to-add-captured-photos-in-a-gridview-9f1aec27ce1d?source=rss-ba350809cae3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f1aec27ce1d</guid>
            <category><![CDATA[cameras]]></category>
            <category><![CDATA[dynamics]]></category>
            <category><![CDATA[app-gallery]]></category>
            <category><![CDATA[gridview]]></category>
            <category><![CDATA[android-studio]]></category>
            <dc:creator><![CDATA[Monika Joshi]]></dc:creator>
            <pubDate>Wed, 05 May 2021 18:37:36 GMT</pubDate>
            <atom:updated>2021-05-05T18:37:36.633Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android Application to add Captured Photos in a Gridview.</h3><p>So, as a beginner my first project in Android Studio was to make my own gallery kinda app. So, my app will do 2 things basically :</p><ol><li>It will capture the photo.</li><li>It will show those photos in Gridview and will also save them in my phone’s local gallery.</li></ol><p>And I learnt :</p><ol><li>Total working of Gridview.</li><li>Internal and External storage of my android device and how my app communicate with internal and external storage.</li></ol><p>So, am here sharing my code snippets and , every new thing that particular snippet told me. Though its a very basic app but really it took a lot of time but it was worthed ;)</p><ol><li><strong>res&gt;layout&gt;activity_main.xml</strong></li></ol><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;RelativeLayout 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;.MainActivity&quot;&gt;<br>&lt;GridView<br>    android:id=&quot;@+id/grid1&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:numColumns=&quot;auto_fit&quot;<br>    android:horizontalSpacing=&quot;10dp&quot;<br>    android:verticalSpacing=&quot;10dp&quot;<br>    android:listSelector=&quot;@color/blue&quot;/&gt;<br>    &lt;ImageButton<br>        android:id=&quot;@+id/cameraID&quot;<br>        android:layout_width=&quot;50dp&quot;<br>        android:layout_height=&quot;50dp&quot;<br>        android:layout_alignParentBottom=&quot;true&quot;<br>        android:layout_alignParentRight=&quot;true&quot;<br>        android:background=&quot;@drawable/circle&quot;<br>        android:foreground=&quot;@drawable/ic_baseline_add_24&quot;/&gt;<br>&lt;/RelativeLayout&gt;</pre><p>Its a Relative Layout with ImageButton and GridView.</p><p><strong>ImageButton : </strong>Its a simple button with an image on it. When clicked by user, it will open camera. I defined background of my button to have a circular shape and orange color. By this code :</p><p>In res&gt;drawable&gt;circle.xml</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;shape xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    android:shape=&quot;rectangle&quot;&gt;<br>    &lt;solid android:color=&quot;@color/orange&quot;/&gt;<br>    &lt;corners android:radius=&quot;300dp&quot;/&gt;<br>&lt;/shape&gt;</pre><p>Foreground of my ImageButton have a “+” sign. I defined this by code:</p><p>res&gt;drawable&gt;right click &gt; go to new &gt;vector asset&gt;choose a clipart with “+” . It will create an xml file for you . here you can change the size and color of your vector. Finally set this vector image as the foreground of your ImageButton. !!We are done with image button!! It will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/103/1*G9tY9R3e-3f3PKA9kWZwkw.jpeg" /></figure><p><strong>GridView : </strong>Its a 2D scrolling Grid having rows and columns. We insert the item to the GridView using a List Adapter. These items need not to be predefined and here also we will add the items to the gridview dynamically(with the click of each picture). Talking about the attributes of GridView in “activity_main.xml” file ; we are specifying horizontal and vertical spacing between the items in the Grid. The list selector color will tell the color of the item when we tap on it.</p><p>Now, to insert the items to the GridView we need an ADAPTER(it’s a bridge between our UI Component(grid) and data source that contain the data for UI component(data source is list in our case). So, this brings us to the need to define an Adapter class to implement the functionality of our Adapter.</p><p><strong>java&gt;package name&gt;right-click&gt;new java file&gt;imageAdapter.java</strong></p><pre>package com.example.mygallery;<br><br>import android.content.Context;<br>import android.graphics.Bitmap;<br>import android.graphics.BitmapFactory;<br>import android.view.View;<br>import android.view.ViewGroup;<br>import android.widget.BaseAdapter;<br>import android.widget.GridView;<br>import android.widget.ImageView;<br><br>import java.io.File;<br>import java.io.FileInputStream;<br>import java.io.IOException;<br>import java.util.List;<br><br>public class ImageAdapter extends BaseAdapter {<br>    private Context context;<br>    List&lt;String&gt; image_path;<br><br>    public ImageAdapter(Context c,List&lt;String&gt; i)<br>    {<br>        context=c;<br>        image_path=i;<br>    }<br>    @Override<br>    public int getCount() {<br>        if(image_path!=null)<br>        {<br>            return image_path.size();<br>        }<br>        else<br>            return  0;<br>    }<br><br>    @Override<br>    public Object getItem(int position) {<br>        return position;<br>    }<br><br>    @Override<br>    public long getItemId(int position) {<br>        return position;<br>    }<br><br>    @Override<br>    public View getView(int position, View convertView, ViewGroup parent)<br>    {<br>        ImageView imageView;<br>        BitmapFactory.Options bfOptions=new BitmapFactory.Options();<br>        bfOptions.inDither=false;                     //Disable Dithering mode<br>        bfOptions.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared<br>        bfOptions.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future<br>        bfOptions.inTempStorage=new byte[32 * 1024];<br>        if (convertView == null)<br>        {<br>            imageView = new ImageView(context);<br>            imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.<em>MATCH_PARENT</em>, ViewGroup.LayoutParams.<em>MATCH_PARENT</em>));<br>            imageView.setPadding(0, 0, 0, 0);<br>        }<br>        else<br>         {<br>            imageView = (ImageView) convertView;<br>         }<br>        FileInputStream fs = null;<br>        Bitmap bm;    <br>        try {<br>            fs = new FileInputStream(new File(image_path.get(position).toString()));<br>            if(fs!=null)<br>            {<br>                bm=BitmapFactory.<em>decodeFileDescriptor</em>(fs.getFD(), null, bfOptions);   //decoded bitmap<br>                imageView.setImageBitmap(bm);<br>                imageView.setId(position);<br>                imageView.setLayoutParams(new GridView.LayoutParams(200, 160));<br>            }<br>        } catch (IOException e)<br>        {<br>            e.printStackTrace();<br>        } finally{<br>            if(fs!=null) {<br>                try {<br>                    fs.close();<br>                } catch (IOException e) {<br>                    e.printStackTrace();<br>                }<br>            }<br>        }<br>        return imageView;<br>    }<br>}</pre><p>In this ImageAdapter class we have a constructor and some overriden methods:</p><ol><li>Constructor : which initialise 2 data members ; (a) context (b) List[List of the paths of the captured images].</li><li>getCount() : returns the size of the list i.e. it returns the number of elements gridview is gonna display.</li><li>getItem(int i) : it takes the index as an argument and returns the data item at that index.</li><li>getItemId(int i) : it takes the index and returns the id of the item being displayed in the gridview.</li><li>getView(int position, View convertView, ViewGroup parent): A VERY IMPORTANT FUNCTION.</li></ol><p>Arguments :</p><p>(a) int position : index of the items in the list which contain the path of captured we gonna display in gridView.</p><p>(b) View convertView : when we scroll down the gridview ; some of it’s views will not be visible to us in the screen. So those views can be reused ; these reused views are convertViews. If we are scrolling down our grid; we have to check if there is any convertView available to get reused. If not so ; we have to create a new View for the next item else we can reuse the convertView.(this explains the if-else part of the code for this function)</p><p>( c) ViewGroup parent : it’s a container view(grid view for our case) that will contain the view of items generated by the functions.</p><p>Return Type : It returns the view of items in the grid view.</p><p>Now, our image will be in the form of a file within a directory with some path name. How this file will have the image? this file’s gonna have the image in a compressed bitmap format(uses kinda co-ordinate format to store pixels of image). How we compressed the image and put it down in a file? This is what we gonna see ahead. For now all we know is : our image is in a file and it is in a compressed bitmap format and we need to : decode this and then put this image in our gridview.</p><p>For decoding image we gonna use</p><pre>bm=BitmapFactory.<em>decodeFileDescriptor</em>(fs.getFD(), null, bfOptions);     </pre><p>Now this function will return a decoded bitmap(bm) from the file (fs), with some padding(null in our case) and this bitmap (bm) so produced will be controlled by some options that we will have to set in our code, these are those options given by BitmapFactory class.</p><pre>BitmapFactory.Options bfOptions=new BitmapFactory.Options();<br>bfOptions.inDither=false; <br>bfOptions.inPurgeable=true;    <br>bfOptions.inInputShareable=true; <br>bfOptions.inTempStorage=new byte[32 * 1024];</pre><p>With this now we have a decoded bitmap and now we have to set this bitmap as the content of imageView of our parent GridView. We will specify the parameters of how we want the imageView to get arranged in GridView by a function called “setLayoutParams”</p><pre>imageView.setImageBitmap(bm);<br>imageView.setId(position);<br>imageView.setLayoutParams(new GridView.LayoutParams(200, 160));</pre><p>With this now we have finally learnt how to generate a view(imageView in our case) for the data (list containing the path of captured image files in our case) and finally arranging that view(imageView) in parentView(GridView).</p><p>With this our ImageAdapter class is done. Now we will head toward : capturing image &gt; adding compressed image in a file&gt;obtaining the path of the file&gt;adding that path to a list&gt;then passing that list to ImageAdapter (whose funtionallity has been defined already). This brings us to the new part:</p><p><strong>java&gt;package name&gt;MainActivity.java</strong></p><p>Our Layout just have 2 views(GridView and ImageButton), so firstly lets initialise and define them. Also we need to have a list to store the path of image files .</p><pre>@Override<br>protected void onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.<em>activity_main</em>);<br><br>    captureBtn = (ImageButton)findViewById(R.id.<em>cameraID</em>);<br>    captureBtn.setOnClickListener(this);<br>    grid = ( GridView) findViewById(R.id.<em>grid1</em>);<br><br>    listOfImagesPath = null;<br>    listOfImagesPath = RetriveCapturedImagePath();<br>    if(listOfImagesPath!=null){<br>        grid.setAdapter(new ImageAdapter(this,listOfImagesPath));<br>    }<br>}</pre><p>What is RetriveCapturedImagePath() method we’re gonna see it later. For now keep in mind that we are calling “setAdapter” method only when “listofImagesPath != null” otherwise it will give you a nullPointerException at runtime.</p><p>Moving ahead; let’s define OnClick method for our CaptureBtn. So basically we want that on the click of the button it will open the camera. That means we have to start an intent from the current activity to the camera. If the device is not supporting a camera this can cause an ”ActivityNotFoundException”, so we will have to keep the code within try-catch blocks .</p><pre>@Override<br>public void onClick(View arg0) {<em><br>    </em>if (arg0.getId() == R.id.<em>cameraID</em>) {<br>        try {<br>            Intent captureIntent = new Intent(MediaStore.<em>ACTION_IMAGE_CAPTURE</em>);<br>            startActivityForResult(captureIntent, CAMERA_CAPTURE);<br>        } catch(ActivityNotFoundException anfe){<br>            String errorMessage = &quot;Whoops – your device doesn’t support capturing images!&quot;;<br>            Toast toast = Toast.<em>makeText</em>(this, errorMessage, Toast.<em>LENGTH_SHORT</em>);<br>            toast.show();<br>        }<br>    }<br>}</pre><p>Notice the function startActivityForResult(intent,permission) ; this functions means that this intent will return the data in onActivityResult() method, so we have to handle that data in that very method.</p><p>This data returned by this intent will be the key associated with image we captured . So with the help of key (data) we will have to get the value(captured image) , we’re gonna use “bundles” for mapping this key-value pair. After we get the captured image(value), we will convert it into the bitmap with this code snippet :</p><pre>Bundle extras = data.getExtras();    //map from key to value<br>Bitmap thePic = extras.getParcelable(&quot;data&quot;);   //returns the //value(image) associated with the given key(data)and store it as //bitmap in &quot;thePic&quot;</pre><p>We have our captured image in a bitmap format. Now we have to store the compressed bitmap in a file, for this we need to create a path for the file first.</p><p>Our captured images will be stored in our phone’s gallery as well. So within the gallery we will create a directory called “GridViewDemo” to save our images. So firstly; we need to create the path to the directory; here’s the string path for our directory:</p><pre>public static final String <em>GridViewDemo_ImagePath </em>=<br>        Environment.<em>getExternalStorageDirectory</em>().getAbsolutePath() + &quot;/GridViewDemo/&quot;;</pre><p>Done with the path to directory; now we have to design path for each image file going to be in this directory. We will form the path to each file by using time of each click.</p><pre>String imgcurTime = dateFormat.format(new Date());<br>File imageDirectory = new File(<em>GridViewDemo_ImagePath</em>);<br>imageDirectory.mkdirs();<br>String _path = <em>GridViewDemo_ImagePath </em>+ imgcurTime + &quot;.jpg&quot;;</pre><p>As now we have the path of our image file; we will now create a file with that path name and then store compressed bitmap image in that file. We are gonna write in the file ; this can cause exception FileNotFound , we have to use try-catch block for that.</p><pre>try {<br>    FileOutputStream out = new FileOutputStream(_path);<br>    thePic.compress(Bitmap.CompressFormat.<em>JPEG</em>, 90, out);<br>    out.close();<br>} catch (FileNotFoundException e) {<br>    e.getMessage();<br>}</pre><p>As we are done with our file now; we can now add the path of the file to our list and send this list to our ImageAdapter.</p><pre>listOfImagesPath = RetriveCapturedImagePath();<br>if (listOfImagesPath != null) {<br>    grid.setAdapter(new ImageAdapter(this, listOfImagesPath));<br>}</pre><p>RetrieveCapturedImagePath () : this method will return the list conatining path of all the image files in the directory.</p><pre>private List&lt;String&gt; RetriveCapturedImagePath() {<br>    List&lt;String&gt; tFileList = new ArrayList&lt;String&gt;();<br>    File f = new File(<em>GridViewDemo_ImagePath</em>);<br>    if (f.exists()) {<br>        File[] files=f.listFiles();<br>        Arrays.<em>sort</em>(files);<br>        for(int i=0; i&lt;files.length; i++){<br>            File file = files[i];<br>            if(file.isDirectory())<br>                continue;<br>            tFileList.add(file.getPath());<br>        }<br>    }<br>    return tFileList;<br>}</pre><p>This function is basically getting pathname (getPath()) of each image file in the directory and adding it to a list.</p><p>Complete code for MainActivity.java :</p><pre>package com.example.mygallery;<br><br>import androidx.annotation.NonNull;<br>import androidx.appcompat.app.AppCompatActivity;<br>import androidx.core.app.ActivityCompat;<br>import androidx.core.content.ContextCompat;<br><br>import android.Manifest;<br>import android.app.Activity;<br>import android.content.ActivityNotFoundException;<br>import android.content.Intent;<br>import android.content.pm.PackageManager;<br>import android.graphics.Bitmap;<br>import android.media.Image;<br>import android.net.Uri;<br>import android.os.Bundle;<br>import android.os.Environment;<br>import android.provider.MediaStore;<br>import android.view.Menu;<br>import android.view.View;<br>import android.widget.AdapterView;<br>import android.widget.Button;<br>import android.widget.GridView;<br>import android.widget.ImageButton;<br>import android.widget.Toast;<br><br>import java.io.File;<br>import java.io.FileNotFoundException;<br>import java.io.FileOutputStream;<br>import java.io.IOException;<br>import java.text.DateFormat;<br>import java.text.SimpleDateFormat;<br>import java.util.ArrayList;<br>import java.util.Arrays;<br>import java.util.Date;<br>import java.util.List;<br><br>public class MainActivity extends Activity implements View.OnClickListener {<br>    ImageButton captureBtn = null;<br>    final int CAMERA_CAPTURE = 1;<br>    private Uri picUri;<br>    private DateFormat dateFormat = new SimpleDateFormat(&quot;yyyy-MM-dd HH:mm:ss&quot;);<br>    private GridView grid;<br>    private  List&lt;String&gt; listOfImagesPath;<br><br>    public static final String <em>GridViewDemo_ImagePath </em>=<br>            Environment.<em>getExternalStorageDirectory</em>().getAbsolutePath() + &quot;/GridViewDemo/&quot;;<br><br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(savedInstanceState);<br>        setContentView(R.layout.<em>activity_main</em>);<br><br>        captureBtn = (ImageButton)findViewById(R.id.<em>cameraID</em>);<br>        captureBtn.setOnClickListener(this);<br>        grid = ( GridView) findViewById(R.id.<em>grid1</em>);<br><br>        listOfImagesPath = null;<br>        listOfImagesPath = RetriveCapturedImagePath();<br>        if(listOfImagesPath!=null){<br>            grid.setAdapter(new ImageAdapter(this,listOfImagesPath));<br>        }<br>    }<br><br><br>    @Override<br>    public void onClick(View arg0) {<br>        // <em>TODO Auto-generated method stub<br>        </em>if (arg0.getId() == R.id.<em>cameraID</em>) {<br>            try {<br>                //use standard intent to capture an image<br>                Intent captureIntent = new Intent(MediaStore.<em>ACTION_IMAGE_CAPTURE</em>);<br>                //we will handle the returned data in onActivityResult<br>                startActivityForResult(captureIntent, CAMERA_CAPTURE);<br>            } catch(ActivityNotFoundException anfe){<br>                //display an error message<br>                String errorMessage = &quot;Whoops – your device doesn’t support capturing images!&quot;;<br>                Toast toast = Toast.<em>makeText</em>(this, errorMessage, Toast.<em>LENGTH_SHORT</em>);<br>                toast.show();<br>            }<br>        }<br>    }<br><br>    protected void onActivityResult(int requestCode, int resultCode, Intent data) {<br>        super.onActivityResult(requestCode, resultCode, data);<br>        if (resultCode == <em>RESULT_OK</em>) {<br>            //user is returning from capturing an image using the camera<br>            if (requestCode == CAMERA_CAPTURE) {<br>                Bundle extras = data.getExtras();<br>                Bitmap thePic = extras.getParcelable(&quot;data&quot;);<br>                String imgcurTime = dateFormat.format(new Date());<br>                File imageDirectory = new File(<em>GridViewDemo_ImagePath</em>);<br>                imageDirectory.mkdirs();<br>                String _path = <em>GridViewDemo_ImagePath </em>+ imgcurTime + &quot;.jpg&quot;;<br>                try {<br>                    FileOutputStream out = new FileOutputStream(_path);<br>                    thePic.compress(Bitmap.CompressFormat.<em>JPEG</em>, 90, out);<br>                    out.close();<br>                } catch (FileNotFoundException e) {<br>                    e.getMessage();<br>                } catch (IOException e) {<br>                    e.printStackTrace();<br>                }<br>                listOfImagesPath = null;<br>                listOfImagesPath = RetriveCapturedImagePath();<br>                if (listOfImagesPath != null) {<br>                    grid.setAdapter(new ImageAdapter(this, listOfImagesPath));<br>                }<br>            }<br>        }<br>    }<br><br>    private List&lt;String&gt; RetriveCapturedImagePath() {<br>        List&lt;String&gt; tFileList = new ArrayList&lt;String&gt;();<br>        File f = new File(<em>GridViewDemo_ImagePath</em>);<br>        if (f.exists()) {<br>            File[] files=f.listFiles();<br>            Arrays.<em>sort</em>(files);<br>            for(int i=0; i&lt;files.length; i++){<br>                File file = files[i];<br>                if(file.isDirectory())<br>                    continue;<br>                tFileList.add(file.getPath());<br>            }<br>        }<br>        return tFileList;<br>    }<br>}</pre><p>Don’t forget to add these permissions in Manifest.xml:</p><pre>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;<br>&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;</pre><p>Output :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WeJwlIYmFkDU7Z7Y7lXO0w.jpeg" /></figure><p>This all for this.</p><p>Thank You!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f1aec27ce1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>