<?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 Niga Kumara on Medium]]></title>
        <description><![CDATA[Stories by Niga Kumara on Medium]]></description>
        <link>https://medium.com/@nigakumara?source=rss-8dbabece95ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ZXnMCJCaBAPFBxZd.jpg</url>
            <title>Stories by Niga Kumara on Medium</title>
            <link>https://medium.com/@nigakumara?source=rss-8dbabece95ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:05:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nigakumara/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[Android fundamentals 10.1 Part B: Deleting data from a Room database]]></title>
            <link>https://medium.com/@nigakumara/android-fundamentals-10-1-part-b-deleting-data-from-a-room-database-40698c505015?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/40698c505015</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Tue, 23 Apr 2019 16:15:11 GMT</pubDate>
            <atom:updated>2019-04-23T16:15:11.608Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Niga Satrio Kumara</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*GDQYvBAj6qd5VAxW.gif" /></figure><p>This codelab (practical) follows on from <a href="https://codelabs.developers.google.com/codelabs/android-training-livedata-viewmodel/#0">10.1 Part A: Room, LiveData, and ViewModel</a>. This codelab gives you more practice at using the API provided by the Room library to implement database functionality. You will add the ability to delete specific items from the database. This codelab also includes a coding challenge, in which you update the app so the user can edit existing data.</p><h3>What you’ll do</h3><ul><li>Update the RoomWordsSample app to keep data when the app closes.</li><li>Allow users to delete all words by selecting an Options menu item.</li><li>Allow users to delete a specific word by swiping an item in the list.</li><li>Optionally, in a coding challenge, extend the app to allow the user to update existing words.</li></ul><h3>task 1: Initialize data only if the database is empty</h3><h4>1.1 Add a method to the DAO to get a single word</h4><p>Currently, the WordDao interface has a method for getting all the words, but not for getting any single word. The method to get a single word does not need to return LiveData, because your app will call the method explicitly when needed.</p><p>In the WordDao interface, add a method to get any word:</p><pre>@Query(&quot;SELECT * from word_table LIMIT 1&quot;)<br>    Word[] getAnyWord();</pre><h4>1.2 Update the initialization method to check whether data exists</h4><ol><li>PopulateDBAsync is an inner class in WordRoomDatbase. In PopulateDBAsync, update the doInBackground() method to check whether the database has any words before initializing the data:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Umshn5vcse1-Q7RjIH4lMQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdnBySmajrHOXkqCdVhI7w.png" /></figure><h3>Task 2: Delete all words</h3><p>Here are the general steps for implementing a method to use the Room library to interact with the database:</p><ul><li>Add the method to the DAO, and annotate it with the relevant database operation. For the deleteAll() method, you already did this step in the previous practical.</li><li>Add the method to the WordRepository class. Write the code to run the method in the background.</li><li>To call the method in the WordRepository class, add the method to the WordViewModel. The rest of the app can then access the method through the WordViewModel.</li></ul><h4>2.1 Add deleteAll() to the WordDao interface and annotate it</h4><ol><li>In WordDao, check that the deleteAll() method is defined and annotated with the SQL that runs when the method executes:</li></ol><pre>@Query(&quot;DELETE FROM word_table&quot;)<br>void deleteAll();</pre><h4>2.2 Add deleteAll() to the WordRepository class</h4><p>Add the deleteAll() method to the WordRepository and implement an AsyncTask to delete all words in the background.</p><ol><li>In WordRepository, define deleteAllWordsAsyncTask as an inner class. Implement doInBackground() to delete all the words by calling deleteAll() on the DAO:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YbiFnZxFQID0pjqxKcQ1Q.png" /></figure><ol><li>In the WordRepository class, add the deleteAll() method to invoke the AsyncTask that you defined.</li></ol><pre>public void deleteAll()  {<br>   new deleteAllWordsAsyncTask(mWordDao).execute();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_fBzRjQP3jQGpQRC_sTQ7A.png" /></figure><h4>2.3 Add deleteAll() to the WordViewModel class</h4><p>Make the deleteAll() method available to the MainActivity by adding it to the WordViewModel.</p><ol><li>In the WordViewModel class, add the deleteAll() method:</li></ol><pre>public void deleteAll() {mRepository.deleteAll();}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3gik4VUt4oKl_pSyh3kDnA.png" /></figure><h3>Task 3: Add an Options menu item to delete all data</h3><h3>3.1 Add the Clear all data menu option</h3><ol><li>In menu_main.xml, change the menu option title and id, as follows:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Yol26moIVw72waZw6hg-g.png" /></figure><ol><li>In MainActivity, implement the onOptionsItemSelected() method to invoke the deleteAll()method on the WordViewModel object.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QX-ybAeIFnhwiCH_SLuwbA.png" /></figure><p>Run your app. In the Options menu, select Clear all data. All words should disappear.</p><h3>Task 4: Delete a single word</h3><h4>4.1 Add deleteWord() to the DAO and annotate it</h4><ol><li>In WordDao, add the deleteWord() method:</li></ol><pre>@Delete<br>void deleteWord(Word word);</pre><h4>4.2 Add deleteWord() to the WordRepository class</h4><ol><li>In WordRepository, define another AsyncTask called deleteWordAsyncTask as an inner class. Implement doInBackground() to delete a word by calling deleteWord() on the DAO:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbVL-GOWDps3MfWh5MRV3Q.png" /></figure><p>In WordRepository, add the deleteWord() method to invoke the AsyncTask you defined.</p><pre>public void deleteWord(Word word)  {<br>   new deleteWordAsyncTask(mWordDao).execute(word);<br>}</pre><h4>4.3 Add deleteWord() to the WordViewModel class</h4><p>To make the deleteWord() method available to other classes in the app, in particular, MainActivity, add it to WordViewModel.</p><ol><li>In WordViewModel, add the deleteWord() method:</li></ol><pre>public void deleteWord(Word word) {mRepository.deleteWord(word);}</pre><h3>Task 5: Enable users to swipe words away</h3><p>Use the <a href="https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper.html">ItemTouchHelper</a> class provided by the Android Support Library (version 7 and higher) to implement swipe functionality in your RecyclerView. The ItemTouchHelper class has the following methods:</p><ul><li>onMove() is called when the user moves the item. You will not implement any move functionality in this app.</li><li>onSwipe() is called when the user swipes the item. You implement this method to delete the word that was swiped.</li></ul><h4>5.1 Enable the adapter to detect the swiped word</h4><ol><li>In WordListAdapter, add a method to get the word at a given position.</li></ol><pre>public Word getWordAtPosition (int position) {<br>   return mWords.get(position);<br>}</pre><p>2. In MainActivity, in onCreate(), create the ItemTouchHelper. Attach the ItemTouchHelper to the RecyclerView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2zpPTmuRj5egRcZrps1KQ.png" /></figure><p>Things to notice in the code:</p><p>onSwiped() gets the position of the ViewHolder that was swiped:</p><pre>int position = viewHolder.getAdapterPosition();</pre><p>Given the position, you can get the word displayed by the ViewHolder by calling the getWordAtPosition()method that you defined in the adapter:</p><pre>Word myWord = adapter.getWordAtPosition(position);</pre><p>Delete the word by calling deleteWord() on the WordViewModel:</p><pre>mWordViewModel.deleteWord(myWord);</pre><p>Now run your app and delete some words</p><p>swipe deleting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTAj6DnYBuGqldtSy2MzkA.png" /></figure><p>Deleting crocodile notification..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O02GBrGmjmt5J32yabZXiw.png" /></figure><p>FINISH :)))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40698c505015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android fundamentals 10.1 Part A: Room, LiveData, and ViewModel]]></title>
            <link>https://medium.com/@nigakumara/android-fundamentals-10-1-part-a-room-livedata-and-viewmodel-195a80a22a46?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/195a80a22a46</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Tue, 23 Apr 2019 15:55:52 GMT</pubDate>
            <atom:updated>2019-04-23T15:55:52.432Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By niga satrio kumara</em></p><figure><img alt="Image result for view model gif" src="https://cdn-images-1.medium.com/proxy/1*78J2gE_YraJK65-l0KVZsQ.gif" /></figure><p>The Android operating system provides a strong foundation for building apps that run well on a wide range of devices and form factors. However, issues like complex lifecycles and the lack of a recommended app architecture make it challenging to write robust apps. The <a href="https://developer.android.com/topic/libraries/architecture/index.html">Android Architecture Components</a> provide libraries for common tasks such as lifecycle management and data persistence to make it easier to implement the <a href="https://developer.android.com/topic/libraries/architecture/guide.html">recommended architecture</a>.</p><h3>Task 1: Create the RoomWordsSample app</h3><h4>1.1 Create an app with one Activity</h4><ul><li>Name the app RoomWordsSample.</li><li>If you see check boxes for Include Kotlin support and Include C++ support, uncheck both boxes.</li><li>Select only the Phone &amp; Tablet form factor, and set the minimum SDK to API 14 or higher.</li><li>Select the Basic Activity.</li></ul><h4>1.2 Update Gradle files</h4><p>as usual</p><h3>Task 2: Create the Word entity</h3><h4>2.1 Create the Word class</h4><ol><li>Create a class called Word.</li><li>Add a constructor that takes a word string as an argument. Add the @NonNull <a href="https://developer.android.com/reference/android/support/annotation/package-summary.html">annotation</a> so that the parameter can never be null.</li><li>Add a “getter” method called getWord()that returns the word. Room requires &quot;getter&quot; methods on the entity classes so that it can instantiate your objects.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iaOVx08JQf_5iNlDlu9JdA.png" /></figure><h4>2.2 Annotate the Word class</h4><p>complee code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-VpZjqlp9inZrDWpYUZLQ.png" /></figure><p>If you get errors for the annotations, you can import them manually, as follows:</p><pre>import android.arch.persistence.room.ColumnInfo;<br>import android.arch.persistence.room.Entity;<br>import android.arch.persistence.room.PrimaryKey;<br>import android.support.annotation.NonNull;</pre><h4>Task 3: Create the DAO</h4><h3>3.1 Implement the DAO class</h3><p>The DAO for this practical is basic and only provides queries for getting all the words, inserting words, and deleting all the words.</p><ol><li>Create a new interface and call it WordDao.</li><li>Annotate the class declaration with @Dao to identify the class as a DAO class for Room.</li><li>Declare a method to insert one word:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NkM6e4DZCytmbU33r6ljmA.png" /></figure><ol><li>Annotate the insert() method with @Insert. You don&#39;t have to provide any SQL! (There are also @<a href="https://developer.android.com/reference/android/arch/persistence/room/Delete.html">Delete</a>and @<a href="https://developer.android.com/reference/android/arch/persistence/room/Update.html">Update</a> annotations for deleting and updating a row, but you do not use these operations in the initial version of this app.)</li><li>Declare a method to delete all the words:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PT4Z_VJ4aqjuLkPWqaddhw.png" /></figure><p>There is no convenience annotation for deleting multiple entities, so annotate the deleteAll() method with the generic @Query. Provide the SQL query as a string parameter to @Query. Annotate the deleteAll() method as follows:</p><pre>@Query(&quot;DELETE FROM word_table&quot;)</pre><p>Create a method called getAllWords() that returns a List of Words:</p><pre>List&lt;Word&gt; getAllWords();</pre><p>Annotate the getAllWords() method with an SQL query that gets all the words from the word_table, sorted alphabetically for convenience:</p><pre>@Query(&quot;SELECT * from word_table ORDER BY word ASC&quot;)</pre><p>Complete code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kmqIGfEXI8Qx1v6qNuM3xg.png" /></figure><h3>Task 4: Use LiveData</h3><p>LiveData, which is a <a href="https://developer.android.com/topic/libraries/architecture/lifecycle.html">lifecycle library </a>class for data observation, can help your app respond to data changes. If you use a return value of type <a href="https://developer.android.com/reference/android/arch/lifecycle/LiveData.html">LiveData</a> in your method description, Room generates all necessary code to update the LiveData when the database is updated.</p><h4>4.1 Return LiveData in WordDao</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZbVlOuEMokFLKN_7cPPI7Q.png" /></figure><h3>Task 5: Add a Room database</h3><p>Room is a database layer on top of an SQLite database. Room takes care of mundane tasks that you used to handle with a database helper class such as <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html">SQLiteOpenHelper</a>.</p><h4>5.1 Implement a Room databasCreate a public abstract class that extends <a href="https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.html">RoomDatabase</a> and call it WordRoomDatabase.</h4><pre>public abstract class WordRoomDatabase extends RoomDatabase {}</pre><p>Define the DAOs that work with the database. Provide an abstract “getter” method for each @Dao.</p><pre>public abstract WordDao wordDao();</pre><p>Create the WordRoomDatabase as a <a href="https://en.wikipedia.org/wiki/Singleton_pattern">singleton</a> to prevent having multiple instances of the database opened at the same time, which would be a bad thing. Here is the code to create the singleton:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XXkyPkwBdk4WW2v8iLx3Fw.png" /></figure><p>Add code to create a database where indicated by the Create database here comment in the code above.</p><p>The following code uses Room’s database builder to create a <a href="https://developer.android.com/reference/android/arch/persistence/room/RoomDatabase.html">RoomDatabase</a> object named &quot;word_database&quot; in the application context from the WordRoomDatabase class.</p><pre><em>// Create database here</em><br>INSTANCE = Room.databaseBuilder(context.getApplicationContext(),<br>       WordRoomDatabase.class, &quot;word_database&quot;)<br>       .build();</pre><p>Add a migration strategy for the database.</p><pre><em>// Wipes and rebuilds instead of migrating </em><br><em>// if no Migration object.</em><br><em>// Migration is not part of this practical.</em><br>.fallbackToDestructiveMigration()</pre><h3>Task 6: Create the Repository</h3><h4>6.1 Implement the Repository</h4><ol><li>Create a public class called WordRepository.</li><li>Add member variables for the DAO and the list of words.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fI1G_oWNKMwn0N-4g2kRow.png" /></figure><p>Add a constructor that gets a handle to the database and initializes the member variables.</p><pre>WordRepository(Application application) {<br>    WordRoomDatabase db = WordRoomDatabase.getDatabase(application);<br>    mWordDao = db.wordDao();<br>    mAllWords = mWordDao.getAllWords();<br>}</pre><p>Add a wrapper method called getAllWords() that returns the cached words as LiveData. Room executes all queries on a separate thread. Observed LiveData notifies the observer when the data changes.</p><pre>LiveData&lt;List&lt;Word&gt;&gt; getAllWords() {<br>   return mAllWords;<br>}</pre><ol><li>Create the insertAsyncTask as an inner class. You should be familiar with AsyncTask, so here is the insertAsyncTask code for you to copy:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgSZ4LFbh266CXKuwTkZrA.png" /></figure><p>Here is the complete code for the WordRepository class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kuNis1OZITvVUn07Jdw1DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jtKef21YHccypjQDq_avw.png" /></figure><h3>Task 7: Create the ViewModel</h3><h4>7.1 Implement the WordViewModel</h4><ol><li>Create a class called WordViewModel that extends <a href="https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel.html">AndroidViewModel</a>.</li></ol><p>This is a memory leak. If you need the application context, use <a href="https://developer.android.com/reference/android/arch/lifecycle/AndroidViewModel.html">AndroidViewModel</a>, as shown in this practical. &lt;/div&gt;</p><pre>public class WordViewModel extends AndroidViewModel {}</pre><p>Add a private member variable to hold a reference to the Repository.</p><pre>private WordRepository mRepository;</pre><p>Add a private LiveData member variable to cache the list of words.</p><pre>private LiveData&lt;List&lt;Word&gt;&gt; mAllWords;</pre><p>Add a constructor that gets a reference to the WordRepository and gets the list of all words from the WordRepository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STQQBCB294mw0VGcizXbjg.png" /></figure><p>Add a “getter” method that gets all the words. This completely hides the implementation from the UI.</p><pre>LiveData&lt;List&lt;Word&gt;&gt; getAllWords() { return mAllWords; }</pre><p>Create a wrapper insert() method that calls the Repository&#39;s insert() method. In this way, the implementation of insert() is completely hidden from the UI.</p><pre>public void insert(Word word) { mRepository.insert(word); }</pre><p>Here is the complete code for WordViewModel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7mmyMpvuCOHi1UY9vOrYA.png" /></figure><h3>Task 8: Add XML layouts for the UI</h3><h4>8.1 Add styles</h4><p>Change the colors in colors.xml to the following: (to use Material Design colors):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1nxhsrvJvIKrAI99kDMXsQ.png" /></figure><p>Add a style for text views in the values/styles.xml file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abOFV6qTOp2skuAeBb6Bsw.png" /></figure><h4>8.2 Add item layout</h4><ul><li>Add a layout/recyclerview_item.xml layout:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jHTCoNVLbmVNAklDZiGs5Q.png" /></figure><h4>8.3 Add the RecyclerView</h4><p>In the layout/content_main.xml file, add a background color to the ConstraintLayout:</p><pre>android:background=&quot;@color/colorScreenBackground&quot;</pre><p>In content_main.xml file, replace the TextView element with a RecyclerView element:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nffnwqdHo7eKmVTx7xhfAA.png" /></figure><h4>8.4 Fix the icon in the FAB</h4><p>The icon in your floating action button (FAB) should correspond to the available action. In the layout/activity_main.xml file, give the FloatingActionButton a + symbol icon:</p><ol><li>Select File &gt; New &gt; Vector Asset.</li><li>Select Material Icon.</li><li>Click the Android robot icon in the Icon: field, then select the + (&quot;add&quot;) asset.</li><li>In the layout/activity_main.xml file, in the FloatingActionButton, change the srcCompat attribute to:</li></ol><pre>android:src=&quot;@drawable/ic_add_black_24dp&quot;</pre><h3>Task 9: Create an Adapter and adding the RecyclerView</h3><h3>Create the WordListAdapter class</h3><ul><li>Add a class WordListAdapter that extends RecyclerView.Adapter. The adapter caches data and populates the RecyclerView with it. The inner class WordViewHolder holds and manages a view for one list item.</li></ul><p>Here is the code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A9rkb0RBDCaD8BZcT7igtQ.png" /></figure><h4>9.2 Add RecyclerView to MainActivity</h4><ol><li>Add the RecyclerView in the onCreate() method of MainActivity:</li></ol><pre>RecyclerView recyclerView = findViewById(R.id.recyclerview);<br>final WordListAdapter adapter = new WordListAdapter(this);<br>recyclerView.setAdapter(adapter);<br>recyclerView.setLayoutManager(new LinearLayoutManager(this));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rqiqfm6J3r_Y8aveqFUtmw.png" /></figure><p>Run your app to make sure the app compiles and runs. There are no items, because you have not hooked up the data yet. The app should display the empty recycler view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72p1-KjEKL9Z3BkZ2YV4gA.png" /></figure><h3>Task 10: Populate the database</h3><h4>10.1 Create the callback for populating the database</h4><ol><li>Add the onOpen() callback in the WordRoomDatabase class:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwLBx33wLl7tH1uquWlFeQ.png" /></figure><p>2. Create an inner class PopulateDbAsync that extends AsycTask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GGaKaGvPpg0uSnrj81kA_w.png" /></figure><h3>Task 11: Connect the UI with the data</h3><h4>11.1 Display the words</h4><p>In MainActivity, create a member variable for the <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html">ViewModel</a>, because all the activity&#39;s interactions are with the WordViewModel only.</p><pre>private WordViewModel mWordViewModel;</pre><p>In the onCreate() method, get a ViewModel from the ViewModelProviders class.</p><pre>mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);</pre><p>Also in onCreate(), add an observer for the LiveData returned by getAllWords().<br>When the observed data changes while the activity is in the foreground, the onChanged() method is invoked and updates the data cached in the adapter. Note that in this case, when the app opens, the initial data is added, so onChanged() method is called.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiDFMidWeq_kKpwcF00uTw.png" /></figure><p>Run the app. The initial set of words appears in the RecyclerView.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VCCgJSkjXI_-ZVRQI13ToQ.png" /></figure><h4>Task 12: Create an Activity for adding words</h4><p>Now you will add an Activity that lets the user use the FAB to enter new words. This is what the interface for the new activity will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fp9LCeGkWS3TjnbXvs2FzA.png" /></figure><h4>12.1 Create the NewWordActivity</h4><ol><li>Add these string resources in the values/strings.xml file:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8FNUbY15eIoep5xuMRLng.png" /></figure><ol><li>Add a style for buttons in value/styles.xml:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Souxq_vQU2nP9JIlu4ME-Q.png" /></figure><ol><li>Use the Empty Activity template to create a new activity, NewWordActivity. Verify that the activity has been added to the Android Manifest.</li></ol><pre>&lt;activity android:name=&quot;.NewWordActivity&quot;&gt;&lt;/activity&gt;<br></pre><p>Update the activity_new_word.xml file in the layout folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSFevnEZ0VJ7VN8JBS3WKQ.png" /></figure><ol><li>Implement the NewWordActivity class. The goal is that when the user presses the Save button, the new word is put in an Intent to be sent back to the parent Activity.</li></ol><p>Here is the code for the NewWordActivity activity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ye9PgcWX1GccdT1MieC_fg.png" /></figure><h4>12.2 Add code to insert a word into the database</h4><ol><li>In MainActivity, add the onActivityResult() callback for the NewWordActivity. If the activity returns with RESULT_OK, insert the returned word into the database by calling the insert() method of the WordViewModel.</li></ol><pre>public void onActivityResult(int requestCode, int resultCode, Intent data) {<br>   super.onActivityResult(requestCode, resultCode, data);</pre><pre>   if (requestCode == NEW_WORD_ACTIVITY_REQUEST_CODE &amp;&amp; resultCode == RESULT_OK) {<br>       Word word = new Word(data.getStringExtra(NewWordActivity.EXTRA_REPLY));<br>       mWordViewModel.insert(word);<br>   } else {<br>       Toast.makeText(<br>               getApplicationContext(),<br>               R.string.empty_not_saved,<br>               Toast.LENGTH_LONG).show();<br>   }<br>}</pre><p>Define the missing request code:</p><pre>public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;</pre><p>In MainActivity,start NewWordActivity when the user taps the FAB. Replace the code in the FAB&#39;s onClick() click handler with the following code:</p><pre>Intent intent = new Intent(MainActivity.this, NewWordActivity.class);<br>startActivityForResult(intent, NEW_WORD_ACTIVITY_REQUEST_CODE);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aGIIyiPf0MjApxzppvng3g.png" /></figure><p>In the WordDao interface, change the annotation for the insert() method to:</p><pre>@Insert(onConflict = OnConflictStrategy.IGNORE)</pre><p>Run your app :))))</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=195a80a22a46" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Firebase Android]]></title>
            <link>https://medium.com/@nigakumara/firebase-android-da56e2c892c6?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/da56e2c892c6</guid>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Sat, 30 Mar 2019 09:43:25 GMT</pubDate>
            <atom:updated>2019-04-01T16:37:54.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>Firebase Android fundamental</h3><p><em>By Niga Satrio Kumara</em></p><figure><img alt="Image result for firebase gif" src="https://cdn-images-1.medium.com/proxy/1*1F2CGO_OyhOnp397-1ysNw.gif" /></figure><p><strong>Firebase</strong> is a technology that allows you to make web applications with no server-side programming so that development turns out to be quicker and easier. It supports the web, iOS, OS X, and Android clients.</p><h4>Get The Sample Code</h4><p>Clone the GitHub repository from the command line:</p><pre>$ git clone <a href="https://github.com/firebase/friendlychat-android">https://github.com/firebase/friendlychat-android</a></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbW2fXYX-ZjJ-UFuctQuaQ.png" /></figure><p>Import The Starter App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*09hmNeaC48kLOEtL9fSAVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uW123k0u2HodFyHTesKQqQ.png" /></figure><h4>Run the starter app</h4><p>Now that you have imported the project into Android Studio and configured the google-services plugin with your JSON file, you are ready to run the app for the first time. Connect your Android device, and click Run (</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*Esb9o6XUVkl74_aO.png" /></figure><p>)in the Android Studio toolbar.</p><p>The app should launch on your device. At this point, you should see an empty message list, and sending and receiving messages will not work. In the next section, you authenticate users so they can use Friendly Chat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*je1XlWFpkq4dFYI87JoLSw.png" /></figure><h3>Enable Authentication</h3><p>Go to your project in the Firebase console and select Database. Select Get Started in the Realtime Database option. When prompted for security rules, choose to start in either test mode or locked mode, choose test mode. Once the default rules are established, select the Rules tab and update the rules configuration with the following:</p><pre>{<br>  &quot;rules&quot;: {<br>    &quot;.read&quot;: &quot;auth != null&quot;,<br>    &quot;.write&quot;: &quot;auth != null&quot;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWZdFH7sBPMt-P2ziyFlrw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eS_VhWLTp7SNW75tteGEeA.png" /></figure><h3>Configure Authentication APIs</h3><p>Before your application can access the Firebase Authentication APIs on behalf of your users, you will have to enable it</p><ol><li>Navigate to the <a href="http://console.firebase.google.com/">Firebase console</a> and select your project</li><li>Select Authentication</li><li>Select the Sign In Method tab</li><li>Toggle the Google switch to enabled (blue)</li><li>Press Save on the resulting dialog</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eMiCxpXZc-CnBeGFp2ZKYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vJmkgvPT-YLfBo73o4frcg.png" /></figure><h3>Add Firebase Auth dependency</h3><p>The firebase-auth SDK allows easy management of authenticated users of your application. Confirm the existence of this dependency in your app/build.gradle file.</p><h3>app/build.gradle</h3><pre>implementation &#39;com.google.firebase:firebase-auth:15.0.0&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*20kl9igb8QdBZkjfG1G5ag.png" /></figure><h3>Check for current user</h3><p>Now let’s modify MainActivity.java to send the user to the sign-in screen whenever they open the app and are unauthenticated.</p><p>Add the following to the onCreate method after mUsername has been initialized:</p><p>MainActivity.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KjxlYMqD5Yfhb0VM2HWh4Q.png" /></figure><p>Then add a new case to onOptionsItemSelected() to handle the sign out button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9RxSgiC64fxe-hQqSRsvTg.png" /></figure><h3>Implement the Sign-In screen</h3><pre><em>// Firebase instance variables</em><br>private FirebaseAuth mFirebaseAuth;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdIqOTCqopvuk_iizd-bzA.png" /></figure><pre><em>/ Initialize FirebaseAuth</em><br>mFirebaseAuth = FirebaseAuth.getInstance();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NudV24ehoe3fhhoJIJ0-LQ.png" /></figure><p>Next, initiate signing in with Google. Update SignInActivity&#39;s onClick method to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yC1Hh6af_yxrY3lmGwENEg.png" /></figure><p>Add the required signIn method that actually presents the user with the Google Sign-In UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fR7oD2VBVVcLf0bGRcrOg.png" /></figure><p>Next, add the onActivityResult method to SignInActivity to handle the sign in result. If the result of the Google Sign-In was successful, use the account to authenticate with Firebase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKZGxT_CQLJYjva-GAntmA.png" /></figure><p>Add the required firebaseAuthWithGoogle method to authenticate with the signed in Google account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8HSXRrp0nV47g3XK1fgaiQ.png" /></figure><p>That’s it! You’ve implemented authentication using Google as an Identity Provider in just a few method calls and without needing to manage any server-side configuration.</p><h4>Run the app</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWNA8J4ye19ray3n0pZaLw.png" /></figure><h3>Read Messages</h3><p>After importing the JSON file, your database should look like this:</p><pre>root<br>        messages<br>                -K2ib4H77rj0LYewF7dP<br>                        text: &quot;hello&quot;<br>                        name: &quot;anonymous&quot;<br>                -K2ib5JHRbbL0NrztUfO<br>                        text: &quot;how are you&quot;<br>                        name: &quot;anonymous&quot;<br>                -K2ib62mjHh34CAUbide<br>                        text: &quot;i am fine&quot;<br>                        name: &quot;anonymous&quot;</pre><h4>Add Firebase Realtime Database and Firebase Storage dependencies</h4><p>In the dependencies block of the app/build.gradle file, the following dependencies should be included. For this codelab, they are already added for convenience; confirm this by looking in the app/build.gradle file:</p><h4>Dependency in app/build.gradle</h4><pre>implementation &#39;com.google.firebase:firebase-database:15.0.0&#39;<br>implementation &#39;com.google.firebase:firebase-storage:15.0.0&#39;</pre><p>Synchronize Message</p><pre><em>// Firebase instance variables</em><br>private DatabaseReference mFirebaseDatabaseReference;<br>private FirebaseRecyclerAdapter&lt;FriendlyMessage, MessageViewHolder&gt;<br>        mFirebaseAdapter;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PfyycdSF1B2X1iN_3uvLvA.png" /></figure><p>Modify your MainActivity’s onCreate method by replacing <em>mProgressBar.setVisibility(ProgressBar.INVISIBLE); </em>with the code defined below. This code initially adds all existing messages and then listens for new child entries under the messages path in your Firebase Realtime Database. It adds a new element to the UI for each message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVeQXZTJl3oaPvue-4rurw.png" /></figure><p>Appropriately start and stop listening for updates from Firebase Realtime Database. Update the <em>onPause</em> and <em>onResume</em> methods in MainActivity as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mCje9zlg0PhhgGSucF8ReA.png" /></figure><h4>Send Messages</h4><p>Update the onClick method of mSendButton in the onCreate method in the MainActivity class. This code is at the bottom of the onCreate method already. Update the onClick body to match the code below:</p><pre>mSendButton = (Button) findViewById(R.id.sendButton);<br>mSendButton.setOnClickListener(new View.OnClickListener() {<br>   @Override<br>   public void onClick(View view) {<br>       FriendlyMessage friendlyMessage = new <br>               FriendlyMessage(mMessageEditText.getText().toString(),<br>                               mUsername,<br>                               mPhotoUrl,<br>                               null <em>/* no image */</em>);<br>       mFirebaseDatabaseReference.child(MESSAGES_CHILD)<br>               .push().setValue(friendlyMessage);<br>       mMessageEditText.setText(&quot;&quot;);<br>   }<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yL2w5shkjmGI_2EqlaIeUA.png" /></figure><h4>Select Image</h4><p>With the following code snippet you will allow the user to select an image from the device’s local storage. Update the onClick method of mAddMessageImageView in the onCreate method in the MainActivity class. This code is at the bottom of the onCreate method already. Update the onClick body to match the code below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JdmucXBFJOKjQEDdWt_aSg.png" /></figure><h4>Handle image selection and write temp message</h4><p>Once the user has selected an image, a call to the MainActivity&#39;s onActivityResult will be fired. This is where you handle the user&#39;s image selection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXqMKo1821Jh0kGrJ0TeKQ.png" /></figure><h4>Test Sending Message :)</h4><h3>Add Messages to the On-device Index</h3><p>You can use Firebase App Indexing to index personal content to the user’s device. This allows your users to search the Google app and find messages they added in the FriendlyChat application.</p><h4>Add the app indexing dependency</h4><p>The firebase-appindexing dependency provides the ability to write messages to the on-device index and to log user actions. Confirm this dependency in your app/build.gradle file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMeWV8QBXFxdYW98OIgGSg.png" /></figure><h4>Add an intent filter</h4><p>Add an intent filter into your AndroidManifest.xml file to handle incoming links of the form <a href="http://friendlychat.firebase.google.com/message/*."><em>http://friendlychat.firebase.google.com/message/*</em>.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6ZcsYPKsntEpy2FZd9mww.png" /></figure><h4>Add personal content to index</h4><p>Any time a user sends a message from their device, you can add that message to the on-device index for future discoverability through the Google app.</p><p>First, add the following code to create a message to write to the on-device index:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hAen8eXk2zvXihQm5aQJcg.png" /></figure><p>Then, call indexMessage() whenever there is a new message. You can index the FriendlyMessage when the viewHolder for it is populated in the same FirebaseRecyclerAdapter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7D3QmwwGW4U1mZbcQm2vVg.png" /></figure><h4>Log user actions</h4><p><a href="https://firebase.google.com/docs/app-indexing/android/log-actions">Logging user actions</a> in your app helps improve your users’ experience when they search for your app content in the Google app.</p><p>To log the VIEW_ACTION user action, add the following function to MainActivity.java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YC3KxmPnLm0DZOkcIs54vQ.png" /></figure><p>Next, add the FirebaseUserActions.getInstance().end(...) method to indicate the end of logging a user action. You can do this right after you&#39;ve added the new message to the index. Pass getMessageViewAction() from above to this method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8Ixy6PrOkJWxU-z-bdixA.png" /></figure><h4>Test your implementation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*uPlaZLPrgPlYKF17fkUNsw.png" /><figcaption>Yeah :)</figcaption></figure><h3>Receive Re-engagement Notifications</h3><p>You can use Firebase Cloud Messaging (FCM) to send notifications to users of your app. In this section we will configure the application to receive reengagement notifications which you can send from Firebase console.</p><h4>Add FCM dependency</h4><p>The firebase-messaging dependency provides the ability to send and receive FCM messages. Confirm the existence of this dependency to your app/build.gradle file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrKDvnKEdrm6uY5Z7fNP_w.png" /></figure><h4>Add FCM Services</h4><p>The RegistrationIntentService class is a background service which is used to request the InstanceID token which identifies the application to the FCM server.</p><p>To handle data messages (which are passed silently to the app rather than automatically creating a notification) you can override the onMessageReceived method from the FirebaseMessagingService base class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1_Eb7RUfMzvMJKhxmedtA.png" /></figure><p>Modify it to extend FirebaseInstanceIdService and override the onTokenRefresh method to subscribe to a topic. Use the following code to update the onTokenRefresh method in MyFirebaseInstanceIdService to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BG8_JRj4qClGL1g7v9IIA.png" /></figure><p>Add service declarations for the MyFirebaseMessagingService and the MyFirebaseInstanceIdService as children of the application element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEiR9743qrmgQZp6UPxrvg.png" /></figure><p>That’s it! FCM is all ready to receive messages.</p><h3>Remotely Configure Friendly Message Length</h3><p>Firebase Remote Config allows you to remotely configure your application without having to deploy any new code. In this codelab “Friendly Messages” are restricted to a maximum length.</p><h4>Add Config Rules in Firebase console</h4><p>In the Remote Config section of Firebase console click Add Your First Parameter. Set the parameter key to friendly_msg_length and the parameter value to 10. Click Add Parameter. Make sure to click Publish Changeswhen you are done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaJNsJvfrIKqVjEG6Wi0qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gD_4rIgce5F5VowptgGSPg.png" /></figure><h4>Add Firebase Remote Config dependency</h4><p>The firebase-config dependency provides the ability to remotely configure applications. Confirm that the following dependency is added to your app/build.gradle file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1vjNbugv6OQKJsetnUmN2w.png" /></figure><h4>MainActivity.java (instance variable)</h4><pre><em>// Firebase instance variables</em><br>private FirebaseRemoteConfig mFirebaseRemoteConfig;</pre><h4>Request and use config</h4><p>In the MainActivity onCreate method, add the following snippet to initialize the FirebaseRemoteConfig and then invoke the fetchConfig method. Add it just above the initialization of the Firebase Realtime Database :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MtYBlzNE3q6TbsilFNsZA.png" /></figure><p>Add fetchConfig and applyRetrievedLengthLimit methods to MainActivity. These methods fetch and activate the retrieved configuration from the Remote Config API. The retrieved configuration determines the max number of characters that a Friendly Message can contain. The default max is 10, set in the FirebaseRemoteConfigSettings object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgwB2pq8HN03iKUu3WjOag.png" /></figure><p>Add a call to fetchConfig in the onOptionsItemSelected method in MainActivity. The onOptionsItemSelected method should now look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRlT6cdj-cJC1RqBM9UK7g.png" /></figure><h4>Test Remote Config</h4><ol><li>Click the run button</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/0*8wPZp5KcoPiVvTl7.png" /></figure><p>Check that the Friendly Message character limit has been set to 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J1oV5DHIlYdY6DyqSMAatg.png" /></figure><h3>Send Install Invites</h3><p>Firebase App Invites provide a simple way for your users to share your application with their friends through Email or SMS.</p><h3>Add AppInvite dependency</h3><p>Confirm that the firebase-appinvites dependency is in your app/build.gradle file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*co84KRKcMLVay7cVWZgmLg.png" /></figure><h4>Setup GoogleApiClient</h4><p>Confirm that MainActivity implements the GoogleApiClient.OnConnectionFailedListener interface:</p><pre>public class MainActivity extends AppCompatActivity implements<br>       GoogleApiClient.OnConnectionFailedListener {</pre><p>Confirm that the required onConnectionFailed method is implemented:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpEV1mrJd7NfiJe9Amchdw.png" /></figure><h4>Send invitations</h4><p>Add the sendInvitation method to MainActivity such that it creates and starts the intent which provides the user the ability to send invitations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_U0EXSrdrXDuETcjkLqCjA.png" /></figure><p>Handle the Activity result invite callback, which will indicate whether or not the sending of the invites occurred successfully. Update the onActivityResult method in MainActivity so it looks like the snippet below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B804Iu1IwFealfFGrBhASQ.png" /></figure><p>Add a call to sendInvitation to the onOptionsItemSelected method in MainActivity. The onOptionsItemSelected method should now look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_ZN77LfZ77u4HHlvrg8VA.png" /></figure><h4>Test App Invite</h4><ol><li>Click the run button</li></ol><p>2.Tap the menu overflow at the top right of the screen</p><p>3.Select the Invite option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1bNMcpNLbufHharuTgDycw.png" /></figure><h3>Track User Flows</h3><p>Google Analytics for Firebase provides a way for you to understand the way users move through your application, where they succeed and where they get stuck. It can also be used to understand the most used parts of your application.</p><h4>Add Analytics dependency</h4><p>Confirm the existence of the firebase-analytics dependency your app/build.gradle file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2b12z-_P28JZUcfqGYrcvA.png" /></figure><p>In MainActivity initialize mFirebaseAnalytics by adding the following line to the onCreate method. By initializing Google Analytics for Firebase you will automatically track the lifecycle of your application throughout user sessions without writing any more code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5AQWO0N4DVREbpyCT_yhdg.png" /></figure><h4>Send Custom Events</h4><p>Initializing Google Analytics for Firebase provides some default metrics like app installs and session lifecycle, however you may want to add custom events that help you understand how users interact with your app in specific ways.</p><p>In MainActivity, log inviting events in the onActivityResult callback. Your onActivityResult callback should handle the REQUEST_INVITE requestCode like the code below. You can see that in each case we send a SHAREevent but with different custom parameters for success and failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Zu8PJZskaECFrh-qMHUKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtwmBOMC76LABj-oHWOCzA.png" /></figure><h3>Monetize with Ads</h3><p>AdMob gives you a way to easily monetize your application, you simply add the AdView placeholder and Google handles the ad delivery for you.</p><h4>Add AdMob dependency</h4><p>Confirm the play-services-ads dependency exists in your app/build.gradle file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*suBJ86yZNX7Hpan--OraPw.png" /></figure><h3>Add ads namespace</h3><p>Verify that the ads namespace is in the root RelativeLayout tag in the activity_main.xml file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGaWrNKD-ZZIQjZbChqdMw.png" /></figure><h3>Add AdView to main layout</h3><p>Include the view that will contain the ad. In your activity_main.xml file inside the root RelativeLayout add the following AdView tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p6aSNObeEHpPZVaTh9ZJsQ.png" /></figure><p>Update RecyclerView element to be laid out below the AdView, RecyclerView should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qX_UWX610-1CzMAqF5wI1A.png" /></figure><h4>Add AdView variable</h4><p>In the MainActivity add an instance variable that represents the AdView:</p><h4>MainActivity.java</h4><pre>private AdView mAdView;</pre><h4>Request Ad</h4><p>In MainActivity in the onCreate method, request the ad to be placed in the AdView:</p><h4>MainActivity.java</h4><pre>mAdView = (AdView) findViewById(R.id.adView);<br>AdRequest adRequest = new AdRequest.Builder().build();<br>mAdView.loadAd(adRequest);</pre><h4>Handle lifecycle events</h4><p>In MainActivity add Activity lifecycle event handling, pausing, resuming and destroying where necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*51UEW-R55yb6ixgHQTRL3g.png" /></figure><h3>Test AdMob</h3><ol><li>Click the Run button.</li><li>Verify that Test Ad shows as in the screenshot in step 1.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y1cK1gMZKehPtMUkDTsPeg.png" /></figure><p>THAT ALL GUYS!! THANKS FOR READING :)))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*VxafDUOrZN7790Zi.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da56e2c892c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Searching a SQLite Database]]></title>
            <link>https://medium.com/@nigakumara/searching-a-sqlite-database-5e67198d78d6?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e67198d78d6</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Sat, 30 Mar 2019 05:31:22 GMT</pubDate>
            <atom:updated>2019-03-30T05:31:22.432Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Niga Satrio Kumara</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*Dicd7h75vA0PMHIG.gif" /></figure><h3>Task 1. Add Search</h3><h4>1.1. Add an Options Menu with Search item</h4><p>Create a menu with one item <strong>Search</strong>. Reference the code snippet for values.</p><pre>&lt;menu<br>   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>   tools:context=&quot;com.android.example.wordlistsqlsearchable.MainActivity&quot;&gt;<br><br>   &lt;item<br>       android:id=&quot;@+id/action_search&quot;<br>       android:title=&quot;Search...&quot;<br>       android:orderInCategory=&quot;1&quot;<br>       app:showAsAction=&quot;never&quot; /&gt;<br>&lt;/menu&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-av9isiyqSBd4C6BRmc2fA.png" /></figure><p>In MainAcvitiy, inflate the menu by overriding onCreateOptionsMenu.</p><pre>@Override<br>public boolean onCreateOptionsMenu(Menu menu) {<br>   getMenuInflater().inflate(R.menu.menu_main, menu);<br>   return true;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZnqDR1Md4z3BWmyWo0NRg.png" /></figure><p>Override onOptionsItemSelected method. Switch on action_search, and just return true.</p><pre>@Override<br>public boolean onOptionsItemSelected(MenuItem item) {<br>   switch (item.getItemId()) {<br>       case R.id.action_search:<br>           return true;<br>   }<br>   return super.onOptionsItemSelected(item);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7Qe5DPd_Lu9xlI8efpMPA.png" /></figure><p>Run your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*65lly2NuwOzvSo7Fd3b1GA.png" /></figure><h3>1.2. Create the layout for the search activity</h3><p>This layout is similar to activity_edit_word, so you can take advantage of existing code and copy it.</p><ol><li>Create a copy of activity_editword and call it activity_search.xml.</li><li>In activity_search.xml, change the id’s and strings to be representative of searching.</li><li>Change the onClick method for the button to showResult.</li><li>Add a TextView with an id of search_result, at least 300dp height, and 18sp font size.</li><li>Run your app. You should notice no difference.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DSfc9sGXuewtNwFyv4AEow.png" /></figure><h3>1.3. Add an Activity for searching</h3><ol><li>Create a new activity, SearchActivity. If your create it by New &gt; Android &gt; Activity then DON’T generate the layout file because we created it in the previous task.</li><li>Add a private TextView class variable mTextView.</li><li>Add a private EditText class variable mEditWordView.</li><li>Add a private WordListOpenHelper variable mDB.</li><li>In onCreate, initialize mDB with a new WordListOpenHelper(this).</li><li>In onCreate, initialize mTextView and mEditWordView to their respective views.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LP29YchY_PzJEsy4bsvWgQ.png" /></figure><p>Add the activity to the AndroidManifest.</p><pre>&lt;activity<br>    android:name=&quot;com.android.example.wordlistsqlsearchable.SearchActivity&quot;&gt;<br>&lt;/activity&gt;</pre><h4>1.4. Trigger SearchActivity from the menu</h4><p>To start SearchActivity when the menu item is selected, insert code to start SearchActivity into the switch statement in the onOptionSelected() method in MainActivity</p><ul><li>Intent intent = new Intent(getBaseContext(), SearchActivity.class); startActivity(intent);</li></ul><ol><li>Build and run your app to make sure SearchActivity is launched when the “Search” menu item is selected from the OptionsMenu.</li><li>Enter a search string and press “Search”. Your app crashes.</li><li>Find out why the app has crashed, then move to the next task.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RI2p4_m5wHQS4TXMPOR22A.png" /></figure><h4>1.5. Implement the onClick handler for the Search button in the SearchActivity</h4><p>When the Search button is pressed, several things need to happen:</p><ul><li>The event handler calls public void showResult(View view) in SearchActivity.</li><li>Your app has to get the current value from the mEditWordView, which is your search string.</li><li>You print the “Result for” and the word in mTextView.</li><li>You call the (not yet written) search function on mDB (mDB.search(word) and get back a SQlite database cursor. You will implement the search function in the next task.</li><li>You process the cursor and add the result to mTextView.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-DzairHNieXbvsVNFSZgw.png" /></figure><h4>1.6. Implement the search method in WordListOpenHelper</h4><ol><li>The table is already defined as the WORD_LIST_TABLE constant.</li><li>In search(), create a variable for the columns. You need only the value from the KEY_WORD column.</li></ol><ul><li>String[] columns = new String[]{KEY_WORD};</li></ul><p>Add the % to the searchString parameter.</p><ul><li>searchString = &quot;%&quot; + searchString + &quot;%&quot;;</li></ul><p>Create the where clause. Omit “WHERE” as it’s implied. Use a question mark for the argument to LIKE. Make sure you have the correct spacing.</p><ul><li>String where = KEY_WORD + &quot; LIKE ?&quot;;</li></ul><p>Specify the argument to the where clause, which is the searchString.</p><ul><li>String[] whereArgs = new String[]{searchString};</li></ul><p>Add a Cursor cursor variable and initialize it to null.</p><p>In a try/catch block.</p><p>Get a readable database if mReadable is not set yet.</p><p>Query the database using the above form of the query. Pass null for the unused parameters.</p><p>Handle the exception. You can just log it.</p><p>Return the cursor.</p><p>Run your app and search for some strings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSdikO2mtsBuXBDuWua7TA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2vGfRn02I7xaDzL8cX_68A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e67198d78d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQLite Database]]></title>
            <link>https://medium.com/@nigakumara/sqlite-database-2fc5d2f30002?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fc5d2f30002</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Sat, 30 Mar 2019 04:58:24 GMT</pubDate>
            <atom:updated>2019-03-30T04:58:24.389Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Niga Satrio Kumara</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*OWatLNU2E4k9oqit.png" /></figure><p>A SQLite database is a good storage solution when you have structured data that you need to store persistently and access, search, and change frequently.</p><p>When you use a SQLite database, all interactions with the database are through an instance of the <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html">SQLiteOpenHelper</a> class which executes your requests and manages your database for you.</p><h3>What you will DO</h3><ul><li>Implement a custom class to model your data.</li><li>Create a subclass of SQLiteOpenHelper that creates and manages your app’s database.</li><li>Display data from the database in the RecyclerView.</li><li>Implement functionality to add, modify, and delete data in the UI, and store the changes in the database.</li></ul><h3>Task 0. Download and run the starter code</h3><p>Run the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikdU5ydDjKfIHUIe-LGOgw.png" /></figure><h3>Task 1. Extend SQLiteOpenHelper to create and populate a database</h3><p><a href="http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html">SQLOpenHelper</a> is a utility class in the Android SDK for interacting with a <a href="https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html">SQLite database</a> object. It includes onCreate() and onUpdate() methods that you must implement, and insert, delete, update, and query convenience methods for all your database interactions.</p><h4>1.1 Create a skeleton WordListOpenHelper class</h4><p>Create a new Java class<strong> WordListOpenHelper</strong> with the following signature.</p><pre>public class WordListOpenHelper extends SQLiteOpenHelper {}<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7raE8jMnxvIs5ZwsKzZVKw.png" /></figure><p>In the code editor, hover over the error, then click the light bulb image and select <strong>Implement methods</strong>. Make sure both methods are highlighted and click <strong>OK</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhWXc0y5_91Tko6zzbKcyQ.png" /></figure><p>Add the missing constructor for WordListOpenHelper. (You will define the undefined constants next.)</p><pre>public WordListOpenHelper(Context context) {<br>   super(context, DATABASE_NAME, null, DATABASE_VERSION);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pBurUhDcMD6zFGD-3tjD3A.png" /></figure><h4>1.2. Add database constants to WordListOpenHelper</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncYslOsEeOATfceSFMeE1Q.png" /></figure><p>Run Your App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbhtwTfNuHrWqKdi7gdStA.png" /></figure><h4>1.3. Build the SQL query and code to create the database</h4><p>Below the constants, add the following code to construct the query. Refer to the SQLite Primer if you need help understanding this query.</p><pre>// Build the SQL query that creates the table.<br>private static final String WORD_LIST_TABLE_CREATE =<br>       &quot;CREATE TABLE &quot; + WORD_LIST_TABLE + &quot; (&quot; +<br>               KEY_ID + &quot; INTEGER PRIMARY KEY, &quot; +<br>               // id will auto-increment if no value passed<br>               KEY_WORD + &quot; TEXT );&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F6VnZfcCzlq6Qses3vdA4A.png" /></figure><p>Add instance variables for the references to writable and readable databases. Storing these references saves you to work of getting a database reference every time you need to read or write.</p><pre>private SQLiteDatabase mWritableDB;<br>private SQLiteDatabase mReadableDB;</pre><p>In the onCreate method, add code to create a database and the table (The helper class does not create another database, if one already exists.)</p><pre>@Override<br>public void onCreate(SQLiteDatabase db) {<br>    db.execSQL(WORD_LIST_TABLE_CREATE);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mQy_HSEWPG7PVTz-ZmyfA.png" /></figure><h4>1.4 Create the database in onCreate of the MainActivity</h4><p>Open MainActivity.java and add an instance variable for the open helper:</p><ul><li>private WordListOpenHelper mDB;</li></ul><p>In onCreate, initialize mDB with an instance of WordListOpenHelper. This calls onCreate of the WordListOpenHelper, which creates the database.</p><ul><li>mDB = new WordListOpenHelper(this);</li></ul><p>Add a breakpoint, run the app with the debugger, and check that mDB is an instance for WordListOpenHelper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5TCzbuGOgyf5HqzZdKWkBQ.png" /></figure><h4>1.5 Add data to the database</h4><ol><li>Open WordListOpenHelper.java.</li><li>In onCreate, after creating the database, add a function call to</li></ol><ul><li>fillDatabaseWithData(db);</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUf_OU_Dgxi-1pG7BDfpgw.png" /></figure><p>Next, implement the fillDatabaseWithData() method in WordListOpenHelper.</p><p>Implement the method stub.</p><p>private void fillDatabaseWithData(SQLiteDatabase db){}</p><p>Inside the method, declare a string of words as your mock data.</p><ul><li>String[] words = {&quot;Android&quot;, &quot;Adapter&quot;, &quot;ListView&quot;, &quot;AsyncTask&quot;, &quot;Android Studio&quot;, &quot;SQLiteDatabase&quot;, &quot;SQLOpenHelper&quot;, &quot;Data model&quot;, &quot;ViewHolder&quot;,&quot;Android Performance&quot;, &quot;OnClickListener&quot;};</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gxA2RC3suhTAxGewudb7zw.png" /></figure><p>Create a container for the data. The insert method that you will call next requires the values to fill a row as an instance of <a href="http://developer.android.com/reference/android/content/ContentValues.html">ContentValues</a>. A ContentValues stores the data for one row as key-value pairs, where the key is the name of the column and the value is the value to set.</p><pre>// Create a container for the data.<br>ContentValues values = new ContentValues();</pre><p>Add key/value for the first row to values, then insert that row into the database. Repeat for all the words in your array of words.</p><pre>for (int i=0; i &lt; words.length; i++) {<br>     // Put column/value pairs into the container.<br>     // put() overrides existing values.<br>     values.put(KEY_WORD, words[i]);<br>     db.insert(WORD_LIST_TABLE, null, values);<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqEvj0RsIOmSy-ZS__h4HQ.png" /></figure><p>Run your app. You will not see any changes in the user interface.</p><h3>Task 2. Create a data model for a single word</h3><h4>2.1. Create a data model for your word data</h4><ol><li>Create a new class and call it WordItem.</li><li>Add the following class variables.</li></ol><ul><li>private int mId; private String mWord;</li></ul><p>Add an empty constructor.</p><p>Add getters and setters for the id and word.</p><p>Run your app. You will not see any visible UI changes, but there should be no errors</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC8MskmpBJNQ8GeHvBugzw.png" /></figure><h4>Task 3. Implement the query() method in WordListOpenHelper</h4><ol><li>Create a query method that takes an integer position argument and returns a WordItem.</li></ol><ul><li>public WordItem query(int position) { }</li></ul><p>Construct a query that returns only the nth row of the result. Use LIMIT with position as the row, and 1 as the number of rows.</p><ul><li>String query = &quot;SELECT * FROM &quot; + WORD_LIST_TABLE + &quot; ORDER BY &quot; + KEY_WORD + &quot; ASC &quot; + &quot;LIMIT &quot; + position + &quot;,1&quot;;</li></ul><p>Instantiate a Cursor variable to null to hold the result from the database</p><ul><li>Cursor cursor = null;</li></ul><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYDAUUZ4WdYTHWnMT-mjhA.png" /></figure><p>Instantiate a WordItem entry.</p><ul><li>WordItem entry = new WordItem();</li></ul><p>Add a try/catch/finally block.</p><ul><li>try {} catch (Exception e) {} finally {}</li></ul><p>Inside the try block,</p><p>get a readable database if it doesn’t exist.</p><ul><li>if (mReadableDB == null) { mReadableDB = getReadableDatabase(); }</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B7zzNtxqbp5T3c5k4Or5CQ.png" /></figure><h4>3.2. The onUpgrade method</h4><p><strong>Important:</strong> While it’s OK to drop the table in a sample app, In a production app you need to carefully migrate the user’s valuable data.</p><p><strong>Boilerplate code for onUpgrade():</strong></p><pre>@Override<br>public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {<br>   Log.w(WordListOpenHelper.class.getName(),<br>           &quot;Upgrading database from version &quot; + oldVersion + &quot; to &quot;<br>                   + newVersion + &quot;, which will destroy all old data&quot;);<br>   db.execSQL(&quot;DROP TABLE IF EXISTS &quot; + WORD_LIST_TABLE);<br>   onCreate(db);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HWlTbQGtRSk3WCsaTmpVQ.png" /></figure><h3>Task 4. Display data in the RecyclerView</h3><h4>4.1. Update WordListAdapter to display WordItems</h4><ol><li>Open WordListAdapter.</li><li>In onBindViewHolder replace the code that displays mock data with code to get an item from the database and display it. You will notice an error on mDB.</li></ol><ul><li>WordItem current = mDB.query(position); holder.wordItemView.setText(current.getWord());</li></ul><p>Declare mDB as an instance variable.</p><ul><li>WordListOpenHelper mDB;</li></ul><ol><li>To get the value for mDB, change the constructor for WordListAdapter and add a second parameter for the WordListOpenHelper.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4dDcKEUuitc1e4MTlQ2NQ.png" /></figure><ol><li>Assign the value of the parameter to mDB. Your constructor should look like this:</li></ol><ul><li>public WordListAdapter(Context context, WordListOpenHelper db) { mInflater = LayoutInflater.from(context); mContext = context; mDB = db; }</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UtBwvM6oBTtWT61-zhwLUA.png" /></figure><p>Open MainActivity and add the missing mDB argument.</p><ul><li>mAdapter = new WordListAdapter (this, mDB);</li></ul><p>Run your app.</p><h3>Task 5. Add new words to the database</h3><p>When the user clicks the FAB, an activity opens that lets them enter a word that gets added to the database when they click save.</p><h4>5.1. Write the insert() method</h4><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHxuJ34vlwWHidltfQnE4g.png" /></figure><h4>5.2. Get the word to insert from the user and update the database</h4><p>The starter code comes with an EditWordActivity that gets a word from the user and returns it to the main activity. In MainActivity, you just have to fill in the onActivityResult() method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPhg_Cwn4rFW5fhIQkgJdg.png" /></figure><h4>5.3. Implement getItemCount()</h4><p>In order for the new items to be displayed properly, getItemCount in WordListAdapter has to return the actual number of entries in the database instead of the number of words in the starter list of words.</p><ol><li>Change getItemCount to the code below, which will trigger an error.</li></ol><ul><li>return (int) mDB.count();</li></ul><p>Open WordListOpenHelper and implement count() to return the number of entries in the database.</p><ul><li>public long count(){ if (mReadableDB == null) { mReadableDB = getReadableDatabase(); } return DatabaseUtils.queryNumEntries(mReadableDB, WORD_LIST_TABLE); }</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZCioo7BU4vbGQl1jtc7Qg.png" /></figure><p>Run your app and add some words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UcIYQQJRhnIOZtRb4dV21g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0II2A9WLd6sCWjbIozun9g.png" /></figure><h3>Task 6. Delete words from the database</h3><p>To implement the delete functionality you need to:</p><ul><li>Implement the delete() method in WordListOpenHelper</li><li>Add a click handler to the DELETE button in WordListAdapter</li></ul><h4>6.1. Write the delete() method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o9-IRs4wnBo5DQ8mAQdwzQ.png" /></figure><h4>6.2. Add a click handler to DELETE button</h4><p>You can now add a click handler to the DELETE button that calls the delete() method you just wrote.</p><p>Take a look at the MyButtonOnClickListener class in your starter code. The MyButtonOnClickListener class implements a click listener that stores the id, and the word that you need to make changes to the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G94mDFMSRSt78d7KYuYnRw.png" /></figure><h3>Task 7. Update words in the database</h3><p>To update existing words you have to:</p><ul><li>Add an update() method to WordListOpenHelper.</li><li>Add a click handler to the EDIT button of your view.</li></ul><h4>7.1. Write the update() method</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93m2oPyQci01kak8MMcSwg.png" /></figure><h4>7.2. Add a click listener to the EDIT button</h4><p>And here is the code for the Edit click listener when we bind the View in the onBindViewHolder method of WordListAdapter. This listener has nothing database specific. It starts the EditWordActivity Activity using an Intent and passes it the current id, position, and word in the Extras.</p><p>If you get an error on the EXTRA_POSITION constant, add it with a value of “POSITION”,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1rqkcfiqkABXk6nE6Fmjw.png" /></figure><h3>7.3. Add updating to onActivityResult</h3><p>As implemented, clicking edit starts an activity that shows the user the current word, and they can edit it. To make the update happen,</p><p>Add one line of code to the onActivityResult method in your MainActivity.</p><ul><li>else if (id &gt;= 0) { mDB.update(id, word); }</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZgKoUYltvnZsppUwth3ALA.png" /></figure><p>Run your app and play with it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xiSAvRpcu42rSQ1hvHem9A.png" /></figure><h4>Finisih! Thanks for reading!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fc5d2f30002" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android fundamentals 09.2: App settings]]></title>
            <link>https://medium.com/@nigakumara/android-fundamentals-09-2-app-settings-68a9f6537f13?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a9f6537f13</guid>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 18:23:18 GMT</pubDate>
            <atom:updated>2019-03-26T18:23:18.675Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Niga Satrio Kumara</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*nvreSn1k0PaTZAeI.gif" /></figure><p>Apps often include settings that allow users to modify app features and behaviors. For example, some apps allow the user to set their home location, default units for measurements, and other settings that apply to the entire app. Users don’t access settings frequently, because once a user changes a setting, such as a home location, they rarely need to go back and change it again.</p><h3>What you’ll do</h3><ul><li>Create an app that includes Settings in the options menu.</li><li>Add a Settings option toggle switch.</li><li>Add code to set the default value for the setting, and access the setting value after it has changed.</li><li>Use and customize the Android Studio Settings Activity template.</li></ul><h4>1.1 Create the project and add the xml directory and resource file</h4><ol><li>Run the app, and tap the overflow icon in the app bar to see the options menu, as shown in the figure below. The only item in the options menu is Settings.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_AfzY0R_ir3c7DlJISdAcQ.png" /></figure><ol><li>You need to create a new resource directory to hold the XML file containing the settings. Select the res directory in the Project &gt; Android pane, and choose File &gt; New &gt; Android Resource Directory. The New Resource Directory dialog appears.</li><li>In the Resource type drop-down menu, choose xml. The Directory name automatically changes to xml. Click OK.</li><li>The xml folder appears in the Project &gt; Android pane inside the res folder. Select xml and choose File &gt; New &gt; XML resource file (or right-click xml and choose New &gt; XML resource file).</li><li>Enter the name of the XML file, preferences, in the File name field, and click OK. The preferences.xml file appears inside the xml folder, and the layout editor appears, as shown in the figure below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZprQvkyu5t_BkfSJ8Xu2g.png" /></figure><h4>1.2 Add the XML preference and attributes for the setting</h4><p>Drag a SwitchPreference from the Palette pane on the left side to the top of the layout, as shown in the figure below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OenqcNZu3cOqhwiRfT-dvA.png" /></figure><p>Change the values in the Attributes pane on the right side of the layout editor as follows, and as shown in the figure below:</p><ul><li>defaultValue: true</li><li>key: example_switch</li><li>title: Settings option</li><li>summary: Turn this option on or off</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THHwpDMeD7yvezxS-jpb8Q.png" /></figure><p>Click the Text tab at the bottom of the layout editor to see the XML code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lD3ZGv31U1_mU50ckOS6pQ.png" /></figure><p>Extract the string resources for the android:title and android:summary attribute values to @string/switch_title and @string/switch_summary.</p><h4>1.3 Use SwitchPreferenceCompat</h4><p>In the preferences.xml file in the xml folder, change &lt;SwitchPreference in the code to &lt;android.support.v7.preference.SwitchPreferenceCompat:</p><pre>&lt;android.support.v7.preference.SwitchPreferenceCompat<br>        android:defaultValue=&quot;true&quot;<br>        android:key=&quot;example_switch&quot;<br>        android:summary=&quot;@string/switch_summary&quot;<br>        android:title=&quot;@string/switch_title&quot; /&gt;</pre><p>Open the styles.xml file in the values folder, and add the following preferenceTheme item to the AppThemedeclaration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3X4PsCs2C4A8M2CiYtlJew.png" /></figure><h4>1.4 Add an Activity for settings</h4><ol><li>Select app at the top of the Project &gt; Android pane, and choose New &gt; Activity &gt; Empty Activity.</li><li>Name the Activity SettingsActivity. Uncheck the Generate Layout File option (you don&#39;t need one), and leave unchecked the Launcher Activity option.</li><li>Leave the Backwards Compatibility (AppCompat) option checked. The Package name should already be set to com.example.android.<em>projectname</em>.</li><li>Click Finish.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wnjvsaW3XAgbXE1orAgfg.png" /></figure><h4>1.5 Add a Fragment for a specific setting</h4><ol><li>Select app again, and choose New &gt; Fragment &gt; Fragment (Blank).</li><li>Name the fragment SettingsFragment. Uncheck the Create layout XML? option (you don’t need one).</li><li>Uncheck the options to include fragment factory methods and interface callbacks.</li><li>The Target Source Set should be set to main.</li><li>Click Finish. The result is the following class definition in SettingsFragment:</li><li>Edit the class definition of SettingsFragment to extend PreferenceFragmentCompat:</li></ol><pre>public class SettingsFragment extends PreferenceFragmentCompat {</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJoTI6k5WJDKgaTqYd0IvA.png" /></figure><p>Android Studio creates the following onCreatePreferences() stub:</p><pre>@Override<br>public void onCreatePreferences(Bundle <br>                       savedInstanceState, String rootKey) {<br>}</pre><p>In order to extend the Fragment, Android Studio adds the following import statement:</p><pre>import android.support.v7.preference.PreferenceFragmentCompat;</pre><p>Delete the entire onCreateView() method in the fragment.</p><p>You can safely delete the empty constructor from SettingsFragment as well, because the Fragment is not displayed by itself:</p><pre>public SettingsFragment() {<br>        <em>// Required empty public constructor</em><br>}</pre><p>You need to associate with this Fragment the preferences.xml settings resource you created in a previous step. Add to the newly created onCreatePreferences() stub a call to <a href="https://developer.android.com/reference/android/support/v7/preference/PreferenceFragmentCompat.html#setPreferencesFromResource(int,%20java.lang.String)">setPreferencesFromResource()</a>passing the id of the XML file (R.xml.preferences) and the rootKey to identify the preference root in PreferenceScreen:</p><pre>setPreferencesFromResource(R.xml.preferences, rootKey);</pre><p>The onCreatePreferences() method should now look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jt2zqaC3Edr_oGJHXJnHPQ.png" /></figure><h4>1.6 Display the Fragment in SettingsActivity</h4><ol><li>Add the following code to the end of the onCreate() method so that the Fragment is displayed as the main content:</li></ol><pre>getSupportFragmentManager().beginTransaction()<br>         .replace(android.R.id.content, new SettingsFragment())<br>         .commit();</pre><p>The entire onCreate() method in SettingsActivity should now look like the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOplafCRWg6KrVPU_t32mA.png" /></figure><h4>1.7 Connect the Settings menu item to SettingsActivity</h4><ol><li>Open MainActivity and find the if block in the onOptionsItemSelected() method, which handles the tap on Settings in the options menu:</li></ol><pre>if (id == R.id.action_settings) {<br>   return true;<br>}</pre><ol><li>Add an Intent to the if block to launch SettingsActivity:</li></ol><pre>if (id == R.id.action_settings) {<br>    Intent intent = new Intent(this, SettingsActivity.class);<br>    startActivity(intent);<br>    return true;<br>}</pre><ol><li>To add the app bar Up navigation button to SettingsActivity, you need to edit its declaration in the AndroidManifest.xml file to define the SettingsActivity parent as MainActivity. Open AndroidManifest.xml and find the SettingsActivity declaration:</li></ol><pre>&lt;activity android:name=&quot;.SettingsActivity&quot;&gt;&lt;/activity&gt;</pre><p>Change the declaration to the following:</p><pre>&lt;activity android:name=&quot;.SettingsActivity&quot;<br>            android:label=&quot;Settings&quot;<br>            android:parentActivityName=&quot;.MainActivity&quot;&gt;<br>            &lt;meta-data<br>                android:name=&quot;android.support.PARENT_ACTIVITY&quot;<br>                android:value=&quot;.MainActivity&quot;/&gt;<br>&lt;/activity&gt;</pre><p>Run the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nj7ao9objMMs6VxZJkgtmg.png" /></figure><h4>1.8 Save the default values in shared preferences</h4><ol><li>Add the following to the end of the onCreate() method after the FloatingActionButton code:</li></ol><pre>android.support.v7.preference.PreferenceManager<br>            .setDefaultValues(this, R.xml.preferences, false);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fv5_EwrXX55k0J22Z4xxgw.png" /></figure><h4>1.9 Read the changed settings value from shared preferences</h4><ol><li>Open SettingsActivity and create a static String variable to hold the key for the value:</li></ol><pre>public static final String <br>            KEY_PREF_EXAMPLE_SWITCH = &quot;example_switch&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmPJcBe8THFpUrlAF1DDXQ.png" /></figure><ol><li>Open MainActivity and add the following at end of the onCreate() method:</li></ol><pre>SharedPreferences sharedPref =   <br>           android.support.v7.preference.PreferenceManager<br>                      .getDefaultSharedPreferences(this);<br>Boolean switchPref = sharedPref.getBoolean<br>           (SettingsActivity.KEY_PREF_EXAMPLE_SWITCH, false);<br>Toast.makeText(this, switchPref.toString(), <br>           Toast.LENGTH_SHORT).show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rj234uXYuUY5TYyVkVgUnA.png" /></figure><p>Run the app and Tap Settings to see the Settings Activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SDCdbBA2D_6oWvTGDbla_A.png" /></figure><h4>Task 2: Use the Settings Activity template</h4><p>In a previous practical you created an app called <a href="https://github.com/google-developer-training/android-fundamentals-apps-v2/tree/master/DroidCafeOptionsUp">DroidCafeOptionsUp</a> using the Basic Activity template, which provides an options menu in the app bar as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SiEwn6vkgBi1TLtsgiT0HQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-WyZDnInDZnzIwWoJ7sbMQ.png" /></figure><p>Legend for the figure above:</p><ol><li>App bar</li><li>Options menu action icons</li><li>Overflow button</li><li>Options overflow menu</li></ol><h4>2.1 Explore the Settings Activity template</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U_Amy9t0s2F5QfE_RrhhjQ.png" /></figure><p>You can open and then add to or customize the XML files for the settings you want:</p><ul><li>pref_data_sync.xml: PreferenceScreen layout for &quot;Data &amp; sync&quot; settings.</li><li>pref_general.xml: PreferenceScreen layout for &quot;General&quot; settings.</li><li>pref_headers.xml: Layout of headers for the Settings main screen.</li><li>pref_notification.xml: PreferenceScreen layout for &quot;Notifications&quot; settings.</li></ul><h4>2.2 Add the Settings menu item and connect it to the activity</h4><ol><li>Expand the res folder in the Project &gt; Android pane, and open menu_main.xml file. Click the Text tab to show the XML code.</li><li>Add another menu item called Settings with the new resource id action_settings:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kjBNQV-cn5V_DRBuDdteqg.png" /></figure><ol><li>Extract the string resource for &quot;Settings&quot; in the android:title attribute to the resource name settings.</li><li>Open MainActivity, and find the switch case block in the onOptionsItemSelected() method which handles the tap on items in the options menu. Shown below is a snippet of that method showing the first case(for action_order):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gFdQZhj9SblE3VuzpUH5iA.png" /></figure><p>Note in the above code that the first case uses an Intent to launch OrderActivity. Add a new case for action_settings to the switch case block with similar Intent code to launch SettingsActivity(but without the intent.putExtra):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4UzbNY3wt6ckqh7QM4XoA.png" /></figure><ol><li>Run the app using a phone or emulator so that you can see how the Settings Activity template handles the phone screen size.</li><li>Tap the overflow icon for the options menu, and tap Settings to see the Settings Activity, as shown on the left side of the figure below.</li><li>Tap each setting header (General, Notifications, and Data &amp; sync), as shown in the center of the figure below, to see the group of settings on each child screen of the Settings screen, shown on the right side of the figure below.</li><li>Tap the Up button in the Settings Activity to return to MainActivity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-XPlWErPkm6cRRBYuOm1Q.png" /></figure><h4>2.3 Customize the settings provided by the template</h4><ol><li>Expand the res &gt; values folder and open the strings.xml file. Scroll the contents to the &lt;!-- Example settings for Data &amp; Sync --&gt; comment:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SOpPAC3jBB3iidNdmxhX_Q.png" /></figure><p>Change each value in the pref_market_titles string array (15 minutes, 30 minutes, 1 hour, etc.) to be the titles of markets, such as United States, Canada, etc., rather than frequencies.</p><ol><li>Refactor &gt; Rename the string array resource name pref_sync_frequency_values to pref_market_values.</li><li>Change each value in the pref_market_values string array (15, 30, 60, etc.) to be values for the markets—abbreviations that correspond to the countries above, such as US, CA, etc.:</li></ol><pre>&lt;string-array name=&quot;pref_market_values&quot;&gt;<br>        &lt;item&gt;US&lt;/item&gt;<br>        &lt;item&gt;CA&lt;/item&gt;<br>        &lt;item&gt;UK&lt;/item&gt;<br>        &lt;item&gt;IN&lt;/item&gt;<br>        &lt;item&gt;JA0&lt;/item&gt;<br>        &lt;item&gt;-1&lt;/item&gt;<br>&lt;/string-array&gt;</pre><ol><li>Scroll down to the pref_title_system_sync_settings string resource, and edit the resource (which is set to System sync settings) to Account settings.</li><li>Refactor &gt; Rename the string array resource name pref_title_system_sync_settings to pref_title_account_settings.</li><li>Open the pref_account.xml file. The ListPreference in this layout defines the setting you just changed. Note that the string resources for the android:entries, android:entryValues and android:titleattributes are now changed to the values you supplied in the previous steps:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCFio-8X7WOwbu5FBEyiXQ.png" /></figure><h4>2.4 Add code to set the default values for the settings</h4><ol><li>Open MainActivity and find the onCreate() method.</li><li>Add the following PreferenceManager.setDefaultValues statements at the end of the onCreate()method:</li></ol><pre>PreferenceManager.setDefaultValues(this, <br>                R.xml.pref_general, false);<br>PreferenceManager.setDefaultValues(this, <br>                R.xml.pref_notification, false);<br>PreferenceManager.setDefaultValues(this, <br>                R.xml.pref_account, false);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePn648qYmaBJkaW7wrVpMw.png" /></figure><h4>2.5 Add code to read values for the settings</h4><ol><li>Add the following code at the end of the MainActivity onCreate() method. You can add it immediately after the code you added in the previous step to set the defaults for the settings:</li></ol><pre>SharedPreferences sharedPref = PreferenceManager<br>                        .getDefaultSharedPreferences(this);<br>String marketPref = sharedPref<br>                        .getString(&quot;sync_frequency&quot;, &quot;-1&quot;);<br>displayToast(marketPref);</pre><ol><li>Run the app. When the app’s main screen first appears, you see a Toast message at the bottom of the screen. The first time you run the app, you should see &quot;-1&quot; displayed in the Toast because you haven&#39;t changed the setting yet.</li><li>Tap Settings in the options menu, and tap Account in the Settings screen. Tap Market, and choose Canada as shown below:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5IfKu9_e8IaRN0asKB-oQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jo7IGWfQv2GNezUWX9WOZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOPNFRYMHxlkvIbGV6rmWg.png" /></figure><ol><li>Tap the Up button in the app bar to return to the Settings screen, and tap it again to return to the main screen.</li><li>Run the app again from Android Studio. You should see a Toast message with &quot;CA&quot; (for Canada), and the Marketsetting is now set to Canada.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwn-cPi7hmDA79cZluw61g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a9f6537f13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android fundamentals 09.1: Shared preferences]]></title>
            <link>https://medium.com/@nigakumara/android-fundamentals-09-1-shared-preferences-a480ec1dad4e?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/a480ec1dad4e</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Tue, 26 Mar 2019 04:01:52 GMT</pubDate>
            <atom:updated>2019-03-26T04:01:52.712Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Niga Satrio Kumara</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*eXEvdArhYCQSHmtngBIypg.jpeg" /><figcaption>Image Source : <a href="https://android.i-visionblog.com/working-with-android-shared-preferences-4668efa298a8">https://android.i-visionblog.com/working-with-android-shared-preferences-4668efa298a8</a></figcaption></figure><p>Shared preferences allow you to store small amounts of primitive data as key/value pairs in a file on the device. To get a handle to a preference file, and to read, write, and manage preference data, use the <a href="https://developer.android.com/reference/android/content/SharedPreferences">SharedPreferences</a> class. The Android framework manages the shared preferences file itself. The file is accessible to all the components of your app, but it is not accessible to other apps.</p><h3>What you’ll do</h3><ul><li>Update an app so it can save, retrieve, and reset shared preferences.</li></ul><h4>📌 Task 1: Explore HelloSharedPrefs</h4><h3>1.1 Open and run the HelloSharedPrefs project</h3><p>📎 Download the <a href="https://github.com/google-developer-training/android-fundamentals-starter-apps-v2/tree/master/HelloSharedPrefs">HelloSharedPrefs-Starter</a> code.</p><p>📎 Open the project in Android Studio, and build and run the app.</p><p>Test the app by trying these steps:</p><ol><li>Click the Count button to increment the number in the main text view.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OjFZZXRXIQS-Xn3rKT6tg.png" /></figure><p>2. Click any of the color buttons to change the background color of the main text view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1uKpJlWa-DmZd6GUSoCD7Q.png" /></figure><p>3.Rotate the device and note that both background color and count are preserved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IrBNpZFEsz9tqrutclGsfg.png" /></figure><p>4.Click the Reset button to set the color and count back to the defaults.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAFFSkIna05nZr5bzOxGMw.png" /></figure><h4>📌 1.2 Explore the Activity code</h4><ol><li>Open MainActivity.</li><li>Examine the code.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZD-B7m5rh-rM3-DOm95dA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkmKQH8i2Zo3OiESLAk9XQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OsCh12uOYly3gU3Bk1wRA.png" /></figure><ul><li>The count (mCount) is defined as an integer. The countUp() onClick method increments this value and updates the main TextView.</li><li>The color (mColor) is also an integer that is initially defined as grey in the colors.xml resource file as default_background.</li><li>The changeBackground() onClick method gets the background color of the button that was clicked, and then sets the main text view to that color.</li><li>Both the mCount and mColor integers are saved to the instance state bundle in onSaveInstanceState(), and restored in onCreate(). The bundle keys for count and color are defined by private variables (COUNT_KEY) and (COLOR_KEY).</li></ul><h3>📌 Task 2: Save and restore data to a shared preferences file</h3><h4>📌 2.1 Initialize the preferences</h4><ol><li>Add member variables to the MainActivity class to hold the name of the shared preferences file, and a reference to a SharedPreferences object.</li></ol><pre>private SharedPreferences mPreferences;<br>private String sharedPrefFile = <br>   &quot;com.example.android.hellosharedprefs&quot;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMXaNGM0ppKr1Zv2KErGsw.png" /></figure><p>In the onCreate() method, initialize the shared preferences. Insert this code before the if statement:</p><pre>mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);</pre><p>The <a href="https://developer.android.com/reference/android/content/Context#getSharedPreferences(java.lang.String,%20int)">getSharedPreferences()</a> method (from the activity <a href="https://developer.android.com/reference/android/content/Context">Context</a>) opens the file at the given filename (sharedPrefFile) with the mode MODE_PRIVATE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cPS1GPWwZYKbLISt-RTTTA.png" /></figure><h4>📌 2.2 Save preferences in onPause()</h4><p>Add the onPause() lifecycle method to MainActivity.</p><pre>@Override<br>protected void onPause(){<br>   super.onPause();</pre><pre>   <em>// ...</em><br>}</pre><p>In onPause(), get an editor for the SharedPreferences object:</p><pre>SharedPreferences.Editor preferencesEditor = mPreferences.edit();</pre><p>A shared preferences editor is required to write to the shared preferences object. Add this line to onPause() after the call to super.onPause().</p><p>Use the <a href="https://developer.android.com/reference/android/content/SharedPreferences.Editor#putInt(java.lang.String,%20int)">putInt()</a> method to put both the mCount and mColor integers into the shared preferences with the appropriate keys:</p><pre>preferencesEditor.putInt(COUNT_KEY, mCount);<br>preferencesEditor.putInt(COLOR_KEY, mColor);</pre><p>The SharedPreferences.Editor class includes multiple &quot;put&quot; methods for different data types, including <a href="https://developer.android.com/reference/android/content/SharedPreferences.Editor#putInt(java.lang.String,%20int)">putInt()</a> and <a href="https://developer.android.com/reference/android/content/SharedPreferences.Editor#putString(java.lang.String,%20java.lang.String)">putString()</a>.</p><p>Call apply() to save the preferences:</p><pre>preferencesEditor.apply();</pre><p>The <a href="https://developer.android.com/reference/android/content/SharedPreferences.Editor#apply()">apply()</a> method saves the preferences asynchronously, off of the UI thread. The shared preferences editor also has a <a href="https://developer.android.com/reference/android/content/SharedPreferences.Editor#commit()">commit()</a> method to synchronously save the preferences. The commit() method is discouraged as it can block other operations.</p><p>Delete the entire onSaveInstanceState() method. Because the activity instance state contains the same data as the shared preferences, you can replace the instance state altogether.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*itLcvb7Anth-xLaWQgfU6w.png" /></figure><h4>📌 2.3 Restore preferences in onCreate()</h4><ol><li>Locate the part of the onCreate() method that tests if the savedInstanceState argument is null and restores the instance state:</li></ol><pre>if (savedInstanceState != null) {<br>   mCount = savedInstanceState.getInt(COUNT_KEY);<br>   if (mCount != 0) {<br>       mShowCountTextView.setText(String.format(&quot;%s&quot;, mCount));<br>   }<br>   mColor = savedInstanceState.getInt(COLOR_KEY);<br>   mShowCountTextView.setBackgroundColor(mColor);<br>}</pre><ol><li>Delete that entire block.</li><li>In the onCreate() method, in the same spot where the instance state code was, get the count from the preferences with the COUNT_KEY key and assign it to the mCount variable.</li></ol><pre>mCount = mPreferences.getInt(COUNT_KEY, 0);</pre><p>Update the value of the main TextView with the new count.</p><pre>mShowCountTextView.setText(String.format(&quot;%s&quot;, mCount));</pre><p>Get the color from the preferences with the COLOR_KEY key and assign it to the mColor variable.</p><pre>mColor = mPreferences.getInt(COLOR_KEY, mColor);</pre><p>Update the background color of the main text view.</p><pre>mShowCountTextView.setBackgroundColor(mColor);</pre><p>Run the app. Click the Count button and change the background color to update the instance state and the preferences.</p><p>Rotate the device or emulator to verify that the count and color are saved across configuration changes.</p><p>Force-quit the app using one of these methods:</p><ul><li>In Android Studio, select Run &gt; Stop ‘app.’</li><li>On the device, press the Recents button (the square button in the lower right corner). Swipe the HelloSharedPrefs app card to quit the app, or click the X in the right corner of the card.</li></ul><p>Re-run the app. The app restarts and loads the preferences, maintaining the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BLaY6uG04aYcheiU49L2jQ.png" /></figure><h4>📌 2.4 Reset preferences in the reset() click handler</h4><p>In the reset() onClick method, after the color and count are reset, get an editor for the SharedPreferencesobject:</p><pre>SharedPreferences.Editor preferencesEditor = mPreferences.edit();</pre><p>Delete all the shared preferences:</p><pre>preferencesEditor.clear();</pre><p>Apply the changes:</p><pre>preferencesEditor.apply();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cbml3MHN5idzhK4HGJGD1A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a480ec1dad4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android fundamentals 04.5: RecyclerView]]></title>
            <link>https://medium.com/@nigakumara/android-fundamentals-04-5-recyclerview-ba4c9aee0b12?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba4c9aee0b12</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Sun, 03 Mar 2019 12:34:56 GMT</pubDate>
            <atom:updated>2019-03-03T12:34:56.914Z</atom:updated>
            <content:encoded><![CDATA[<p>By Niga Satrio Kumara</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*aoSLcOFEmDA9bRsQ.gif" /></figure><p><a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html">RecyclerView</a> is a subclass of ViewGroup and is a more resource-efficient way to display scrollable lists. Instead of creating a View for each item that may or may not be visible on the screen, RecyclerView creates a limited number of list items and reuses them for visible content.</p><p>In this practical you do the following:</p><ul><li>Use RecyclerView to display a scrollable list.</li><li>Add a click handler to each list item.</li><li>Add items to the list using a <a href="https://material.google.com/components/buttons-floating-action-button.html">floating action button (FAB)</a>, the pink button in the screenshot in the app overview section. Use a FAB for the primary action that you want the user to take</li></ul><h3>What you’ll do</h3><ul><li>Create a new app that uses a <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html">RecyclerView</a> to display a list of items as a scrollable list and associate click behavior with the list items.</li><li>Use a FAB to let the user add items to the RecyclerView.</li></ul><h3>Task 1: Create a new project and dataset</h3><h4>1.1. Create the project and layout</h4><h4>1.2. Add code to create data</h4><p>In this step you create a <a href="https://developer.android.com/reference/java/util/LinkedList.html">LinkedList</a> of 20 word strings that end in increasing numbers, as in [&quot;Word 1&quot;, &quot;Word 2&quot;, &quot;Word 3&quot;, .... ].</p><p>Open MainActivity and add a private member variable for the mWordList linked list.</p><pre>public class MainActivity extends AppCompatActivity {<br>    private final LinkedList&lt;String&gt; mWordList = new LinkedList&lt;&gt;();<br>    <em>// ... Rest of MainActivity code ...</em><br>}</pre><p>Add code within the onCreate() method that populates mWordList with words:</p><pre><em>// Put initial data into the word list.</em><br>for (int i = 0; i &lt; 20; i++) {<br>            mWordList.addLast(&quot;Word &quot; + i);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iduGNssgklJOzy5PySsvwA.png" /></figure><h4>1.3. Change the FAB icon</h4><p>For this practical, you will use a FAB to generate a new word to insert into the list. The Basic Activity template provides a FAB, but you may want to change its icon. As you learned in another lesson, you can choose an icon from the set of icons in Android Studio for the FAB. Follow these steps:</p><ol><li>Expand res in the Project &gt; Android pane, and right-click (or Control-click) the drawable folder.</li><li>Choose New &gt; Image Asset. The Configure Image Asset dialog appears.</li><li>Choose Action Bar and Tab Items in the drop-down menu at the top of the dialog.</li><li>Change ic_action_name in the Name field to ic_add_for_fab.</li><li>Click the clip art image (the Android logo next to Clipart:) to select a clip art image as the icon. A page of icons appears. Click the icon you want to use for the FAB, such as the plus (+) sign.</li><li>Choose HOLO_DARK from the Theme drop-down menu. This sets the icon to be white against a dark-colored (or black) background. Click Next.</li><li>Click Finish in the Confirm Icon Path dialog.</li></ol><h3>Task 2: Create a RecyclerView</h3><h4>2.1. Modify the layout in content_main.xml</h4><p>To add a RecyclerView element to the XML layout, follow these steps:</p><ol><li>Open content_main.xml in your RecyclerView app. It shows a “Hello World” TextView at the center of a ConstraintLayout.</li><li>Click the Text tab to show the XML code.</li><li>Replace the entire TextView element with the following:</li></ol><pre>&lt;android.support.v7.widget.RecyclerView<br>        android:id=&quot;@+id/recyclerview&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;&gt;<br>&lt;/android.support.v7.widget.RecyclerView&gt;</pre><p>You need to specify the full path (android.support.v7.widget.RecyclerView), because RecyclerView is part of the Support Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OhJVOnHr2Cxt7jj2b2TyqQ.png" /></figure><h4>2.2. Create the layout for one list item</h4><p>Create a simple word item layout using a vertical LinearLayout with a TextView:</p><ol><li>Right-click the app &gt; res &gt; layout folder and choose New &gt; Layout resource file.</li><li>Name the file wordlist_item and click OK.</li><li>In the new layout file, click the Text tab to show the XML code.</li><li>Change the ConstraintLayout that was created with the file to a LinearLayout with the following attributes (extract resources as you go):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v71kFV6idnti1C5TYVDpxA.png" /></figure><h4>2.3 Create a style from the TextView attributes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bW0MKxiQHVqWF1JaBbVhsQ.png" /></figure><h4>2.4. Create an adapter</h4><ol><li>Right-click java/com.android.example.recyclerview and select New &gt; Java Class.</li><li>Name the class WordListAdapter.</li><li>Give WordListAdapter the following signature:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuDscPK7-ni9D3wg1CT5lg.png" /></figure><h4>2.5 Create the ViewHolder for the adapter</h4><p>To create the ViewHolder, follow these steps:</p><ol><li>Inside the WordListAdapter class, add a new WordViewHolder inner class with this signature:</li></ol><pre>class WordViewHolder extends RecyclerView.ViewHolder {}</pre><p>You will see an error about a missing default constructor. You can see details about the errors by hovering your mouse cursor over the red-underlined code or over any red horizontal line on the right margin of the editor pane.</p><p>Add variables to the WordViewHolder inner class for the TextView and the adapter:</p><pre>public final TextView wordItemView;<br>final WordListAdapter mAdapter;</pre><p>In the inner class WordViewHolder, add a constructor that initializes the ViewHolder TextView from the word XML resource, and sets its adapter:</p><pre>public WordViewHolder(View itemView, WordListAdapter adapter) {<br>   super(itemView);<br>   wordItemView = itemView.findViewById(R.id.word);<br>   this.mAdapter = adapter;<br>}</pre><ol><li>Run your app to make sure that you have no errors. Your will still see only a blank view.</li><li>Click the Logcat tab to see the Logcat pane, and note the E/RecyclerView: No adapter attached; skipping layout warning. You will attach the adapter to the RecyclerView in another step.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l4xbat7mQBdJaxOxCFWOUg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Rr50KsmtZCLNXhYUubwhw.png" /></figure><h4>2.6 Storing your data in the adapter</h4><p>You need to hold your data in the adapter, and WordListAdapter needs a constructor that initializes the word list from the data. Follow these steps:</p><p>To hold your data in the adapter, create a private linked list of strings in WordListAdapter and call it mWordList.</p><pre>private final LinkedList&lt;String&gt; mWordList;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHJ1isNcjIUM4KL8aYBOSw.png" /></figure><p>You can now fill in the getItemCount() method to return the size of mWordList:</p><pre>@Override<br>public int getItemCount() {<br>   return mWordList.size();<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rYo1ncnWRUaE0PQ5LXElLQ.png" /></figure><p>WordListAdapter needs a constructor that initializes the word list from the data. To create a View for a list item, the WordListAdapter needs to inflate the XML for a list item. You use a <em>layout inflator </em>for that job. <a href="http://developer.android.com/reference/android/view/LayoutInflater.html">LayoutInflator</a> reads a layout XML description and converts it into the corresponding View items. Start by creating a member variable for the inflater in WordListAdapter:</p><pre>private LayoutInflater mInflater;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vk_Qb1BFDZRuKNVyQiL1A.png" /></figure><p>Implement the constructor for WordListAdapter. The constructor needs to have a context parameter, and a linked list of words with the app&#39;s data. The method needs to instantiate a LayoutInflator for mInflaterand set mWordList to the passed in data:</p><pre>public WordListAdapter(Context context, <br>                               LinkedList&lt;String&gt; wordList) {<br>   mInflater = LayoutInflater.from(context);<br>   this.mWordList = wordList;<br>}</pre><p>Fill out the onCreateViewHolder() method with this code:</p><pre>@Override<br>public WordViewHolder onCreateViewHolder(ViewGroup parent, <br>                                                     int viewType) {<br>   View mItemView = mInflater.inflate(R.layout.wordlist_item, <br>                                                     parent, false);<br>   return new WordViewHolder(mItemView, this);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4hNiNC31mE34u5xLtTccYg.png" /></figure><p>The onCreateViewHolder() method is similar to the onCreate() method. It inflates the item layout, and returns a ViewHolder with the layout and the adapter.</p><p>Fill out the onBindViewHolder() method with the code below:</p><pre>@Override<br>public void onBindViewHolder(WordViewHolder holder, int position) {<br>   String mCurrent = mWordList.get(position);<br>   holder.wordItemView.setText(mCurrent);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viCLush1ZDCEL4uXhvLaeg.png" /></figure><p>The onBindViewHolder() method connects your data to the view holder.</p><p>run your app to make sure that there are no errors.</p><h3>2.7. Create the RecyclerView in the Activity</h3><p>Now that you have an adapter with a ViewHolder, you can finally create a RecyclerView and connect all the pieces to display your data.</p><ol><li>Open MainActivity.</li><li>Add member variables for the RecyclerView and the adapter.</li></ol><pre>private RecyclerView mRecyclerView;<br>private WordListAdapter mAdapter;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LeFZUPpSiYyLnEJ4IQ41Kw.png" /></figure><p>In the onCreate() method of MainActivity, add the following code that creates the RecyclerView and connects it with an adapter and the data. The comments explain each line. You must insert this code <em>after</em> the mWordList initialization.</p><pre><em>// Get a handle to the RecyclerView.</em><br>mRecyclerView = findViewById(R.id.recyclerview);<br><em>// Create an adapter and supply the data to be displayed.</em><br>mAdapter = new WordListAdapter(this, mWordList);<br><em>// Connect the adapter with the RecyclerView.</em><br>mRecyclerView.setAdapter(mAdapter);<br><em>// Give the RecyclerView a default layout manager.</em><br>mRecyclerView.setLayoutManager(new LinearLayoutManager(this));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WR4oSP5bytUGl7k_gYLmSg.png" /></figure><p>Run your app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RbJQ0MOWSuKsii3Emxm9zQ.png" /></figure><h3>Task 3: Make the list interactive</h3><h4>3.1. Make items respond to clicks</h4><ol><li>Open WordListAdapter.</li><li>Change the WordViewHolder class signature to implement <a href="https://developer.android.com/reference/android/view/View.OnClickListener.html">View.onClickListener</a>:</li></ol><pre>class WordViewHolder extends RecyclerView.ViewHolder <br>                             implements View.OnClickListener {</pre><ol><li>Click the class header and on the red light bulb to implement stubs for the required methods, which in this case is just the onClick() method.</li><li>Add the following code to the body of the onClick() method.</li></ol><pre><em>// Get the position of the item that was clicked.</em><br>int mPosition = getLayoutPosition();<br><em>// Use that to access the affected item in mWordList.</em><br>String element = mWordList.get(mPosition);<br><em>// Change the word in the mWordList.</em><br>mWordList.set(mPosition, &quot;Clicked! &quot; + element);<br><em>// Notify the adapter, that the data has changed so it can </em><br><em>// update the RecyclerView to display the data.</em><br>mAdapter.notifyDataSetChanged();</pre><p>Connect the onClickListener with the View. Add this code to the WordViewHolder constructor (below the this.mAdapter = adapter line):</p><pre>itemView.setOnClickListener(this);</pre><p>Run your app. Click items to see the text change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3N5Iy7Y5GVGm8HeNXYum6A.png" /></figure><h4>3.2. Add behavior to the FAB</h4><p>Open MainActivity. The onCreate() method sets an OnClickListener() to the FloatingActionButton with an onClick() method for taking an action. Change the onClick() method to the following:</p><pre>@Override<br>public void onClick(View view) {<br>    int wordListSize = mWordList.size();<br>    <em>// Add a new word to the wordList.</em><br>    mWordList.addLast(&quot;+ Word &quot; + wordListSize);<br>    <em>// Notify the adapter, that the data has changed.</em><br>    mRecyclerView.getAdapter().notifyItemInserted(wordListSize);<br>    <em>// Scroll to the bottom.</em><br>    mRecyclerView.smoothScrollToPosition(wordListSize);<br>}</pre><ol><li>Run the app.</li><li>Scroll the list of words and click items.</li><li>Add items by clicking the FAB.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rR8tEnhI3tDl9KQgTDEBQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba4c9aee0b12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android fundamentals 04.4: User navigation]]></title>
            <link>https://medium.com/@nigakumara/android-fundamentals-04-4-user-navigation-3d6dbbad001c?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d6dbbad001c</guid>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Sun, 03 Mar 2019 11:32:16 GMT</pubDate>
            <atom:updated>2019-03-03T11:32:16.171Z</atom:updated>
            <content:encoded><![CDATA[<p>by Niga satrio kumara</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*uYC9Dvpxwjvxz90W.gif" /></figure><p>In the early stages of developing an app, you should determine the path you want users to take through your app to do each task. (The tasks are things like placing an order or browsing content.) Each path enables users to navigate across, into, and out of the tasks and pieces of content within the app.</p><h3>What you’ll do</h3><ul><li>Continue adding features to the Droid Cafe project from the previous practical.</li><li>Provide the Up button in the app bar to navigate up to the parent Activity.</li><li>Create a new app with tabs for navigating Activity screens that can also be swiped.</li></ul><h3>Task 1: Add an Up button for ancestral navigation</h3><p>As you learned previously, when adding activities to an app, you can add Up-button navigation to a child Activity such as OrderActivity by declaring the parent of the Activity to be MainActivity in the AndroidManifest.xml file. You can also set the android:label attribute for a title for the Activity screen, such as &quot;Order Activity&quot;. Follow these steps:</p><ol><li>If you don’t already have the Droid Cafe app open from the previous practical, download the Android Studio project <a href="https://github.com/google-developer-training/android-fundamentals-apps-v2/tree/master/DroidCafeOptions">DroidCafeOptions</a> and open the project.</li><li>Open AndroidManifest.xml and change the Activity element for OrderActivity to the following:</li></ol><pre>&lt;activity android:name=&quot;com.example.android.droidcafeinput.OrderActivity&quot;<br>    android:label=&quot;Order Activity&quot;<br>    android:parentActivityName=&quot;.MainActivity&quot;&gt;<br>    &lt;meta-data android:name=&quot;android.support.PARENT_ACTIVITY&quot;<br>        android:value=&quot;.MainActivity&quot;/&gt;<br>&lt;/activity&gt;</pre><ol><li>Extract the android:label value &quot;Order Activity&quot; to a string resource named title_activity_order.</li><li>Run the app.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnGsKvaqMGwZ-9tQ6soT1w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cnuFx-0pqJSUjjM36RY95w.png" /></figure><h3>Task 2: Use tab navigation with swipe views</h3><h4>2.1 Create the project and layout</h4><ol><li>Create a new project using the Empty Activity template. Name the app Tab Experiment.</li><li>Edit the build.gradle (Module: app) file, and add the following line to the dependencies section for the Android Design Support Library, which you need in order to use a <a href="https://developer.android.com/reference/android/support/design/widget/TabLayout.html">TabLayout</a>:</li></ol><pre>implementation &#39;com.android.support:design:26.1.0&#39;</pre><p>If Android Studio suggests a version with a higher number, edit the line above to update the version.</p><ol><li>In order to use a Toolbar rather than an app bar and app title, add the following attributes to the res &gt; values &gt; styles.xml file to hide the app bar and the title:</li></ol><pre>&lt;style name=&quot;AppTheme&quot; parent=&quot;Theme.AppCompat.Light.DarkActionBar&quot;&gt;<br>   <em>&lt;!-- Other style attributes --&gt;</em>      <br>   &lt;item name=&quot;windowActionBar&quot;&gt;false&lt;/item&gt;<br>   &lt;item name=&quot;windowNoTitle&quot;&gt;true&lt;/item&gt;<br>&lt;/style&gt;</pre><ol><li>Open activity_main.xml layout file, and click the Text tab to view the XML code.</li><li>Change the ConstraintLayout to RelativeLayout, as you&#39;ve done in previous exercises.</li><li>Add the android:id attribute and android:padding of 16dp to the RelativeLayout.</li><li>Remove the TextView supplied by the template, and add a Toolbar, a TabLayout, and a ViewPagerwithin the RelativeLayout as shown in the code below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tfPUghmgkg_ojlp4lnf2cA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XGgC8kNK14uNDtIIxRIABg.png" /></figure><h4>2.2 Create a class and layout for each fragment and Edit the fragment layout (2.3)</h4><p>To add a fragment representing each tabbed screen, follow these steps:</p><ol><li>Click com.example.android.tabexperiment in the Android &gt; Project pane.</li><li>Choose File &gt; New &gt; Fragment &gt; Fragment (Blank).</li><li>Name the fragment TabFragment1.</li><li>Select the Create layout XML? option.</li><li>Change the Fragment Layout Name for the XML file to tab_fragment1.</li><li>Clear the Include fragment factory methods? option and the Include interface callbacks? option. You don’t need these methods.</li><li>Click Finish.</li></ol><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EbcbsRpdt8h8IBDhGmjoYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Srki8qyxGGPH0VRWsVFLw.png" /><figcaption>Fragment 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5fpiKpoLIFUQ55iwP8trA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIa-tYoAvbAmpF7EZRFJKA.png" /><figcaption>Fragment 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLMzSeO_gKqJZDiHGYstIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6bjq9nE_W0H5l09bwlX9eg.png" /><figcaption>Fragment 3</figcaption></figure><h4>2.4 Inflate the Toolbar and TabLayout</h4><p>Open MainActivity and add the following code inside the onCreate() method to inflate the Toolbar using <a href="https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html#setSupportActionBar(android.support.v7.widget.Toolbar)">setSupportActionBar()</a>:</p><pre>protected void onCreate(Bundle savedInstanceState) {<br>    <em>// ... Code inside onCreate() method</em><br>    android.support.v7.widget.Toolbar toolbar = <br>                                  findViewById(R.id.toolbar);<br>    setSupportActionBar(toolbar);<br>    <em>// Create an instance of the tab layout from the view.</em><br>}</pre><p>Open strings.xml, and create the following string resources:</p><pre>&lt;string name=&quot;tab_label1&quot;&gt;Top Stories&lt;/string&gt;<br>&lt;string name=&quot;tab_label2&quot;&gt;Tech News&lt;/string&gt;<br>&lt;string name=&quot;tab_label3&quot;&gt;Cooking&lt;/string&gt;</pre><p>At the end of the onCreate() method, create an instance of the tab layout from the tab_layout element in the layout, and set the text for each tab using <a href="https://developer.android.com/reference/android/support/design/widget/TabLayout.html#addTab(android.support.design.widget.TabLayout.Tab)">addTab()</a>:</p><pre><em>// Create an instance of the tab layout from the view.</em><br>TabLayout tabLayout = findViewById(R.id.tab_layout);<br><em>// Set the text for each tab.</em><br>tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label1));<br>tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label2));<br>tabLayout.addTab(tabLayout.newTab().setText(R.string.tab_label3));<br><em>// Set the tabs to fill the entire layout.</em><br>tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);<br><em>// Use PagerAdapter to manage page views in fragments.</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEOhLGacbD2TZgOLgVOuvA.png" /></figure><h4>2.5 Use PagerAdapter to manage screen views</h4><p>Below the code you added to the onCreate() method in the previous task, add the following code to use PagerAdapter to manage screen (page) views in the fragments:</p><pre><em>// Use PagerAdapter to manage page views in fragments.</em><br><em>// Each page is represented by its own fragment.</em><br>final ViewPager viewPager = findViewById(R.id.pager);<br>final PagerAdapter adapter = new PagerAdapter<br>              (getSupportFragmentManager(), tabLayout.getTabCount());<br>viewPager.setAdapter(adapter);<br><em>// Setting a listener for clicks.</em></pre><p>At the end of the onCreate() method, set a listener (<a href="https://developer.android.com/reference/android/support/design/widget/TabLayout.TabLayoutOnPageChangeListener.html">TabLayoutOnPageChangeListener</a>) to detect if a tab is clicked, and create the onTabSelected() method to set the ViewPager to the appropriate tabbed screen. The code should look as follows:</p><pre><em>// Setting a listener for clicks.</em><br>viewPager.addOnPageChangeListener(new<br>                TabLayout.TabLayoutOnPageChangeListener(tabLayout));<br>tabLayout.addOnTabSelectedListener(new <br>                TabLayout.OnTabSelectedListener() {<br>    @Override<br>    public void onTabSelected(TabLayout.Tab tab) {<br>        viewPager.setCurrentItem(tab.getPosition());<br>    }</pre><pre>    @Override<br>    public void onTabUnselected(TabLayout.Tab tab) {<br>    }</pre><pre>    @Override<br>    public void onTabReselected(TabLayout.Tab tab) {<br>    }<br>});</pre><p>Run the app. Tap each tab to see each “page” (screen). You should also be able to swipe left and right to visit the different “pages”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cus5QTxztYJ1nDqJRBSnnA.png" /></figure><p>Run :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJWyxh_32Dniodfs2SiMpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UC26XnU0EaAIFUUNLXMiew.png" /><figcaption>Tab 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wXDokpwUep9fk5BeECZ1lA.png" /><figcaption>Tab 3</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d6dbbad001c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android fundamentals 07.3: Broadcast receiver]]></title>
            <link>https://medium.com/@nigakumara/android-fundamentals-07-3-broadcast-receiver-52a276422fea?source=rss-8dbabece95ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/52a276422fea</guid>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Niga Kumara]]></dc:creator>
            <pubDate>Sun, 03 Mar 2019 09:11:04 GMT</pubDate>
            <atom:updated>2019-03-03T09:11:04.182Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Niga satrio Kumara</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*dGyRvlXsCNRA-MLo.gif" /></figure><p><em>Broadcasts</em> are messages that the Android system and Android apps send when events occur that might affect the functionality of other apps or app components. For example, the Android system sends a <em>system broadcast </em>when the device boots up, or when headphones are connected or disconnected. If the wired headset is unplugged, you might like your media app to pause the music.</p><h3>What you’ll do</h3><ul><li>Subclass a BroadcastReceiver to show a toast when a broadcast is received.</li><li>Register your receiver to listen for system broadcasts.</li><li>Send and receive a custom broadcast intent.</li></ul><h4>Task 1. Set up the PowerReceiver project</h4><ol><li>In Android Studio, create a new Java project called PowerReceiver. Accept the default options and use the Empty Activity template.</li><li>To create a new broadcast receiver, select the package name in the Android Project View and navigate to File &gt; New &gt; Other &gt; Broadcast Receiver.</li><li>Name the class CustomReceiver. Make sure that Java is selected as the source language, and that Exported and Enabled are selected. Exported allows your broadcast receiver to receive broadcasts from outside your app. Enabled allows the system to instantiate the receiver.</li></ol><h4>1.2 Register your receiver for system broadcasts</h4><ol><li>(Optional) Navigate to your AndroidManifest.xml file. Android Studio has generated a &lt;receiver&gt;element, but you don&#39;t need it, because you can&#39;t use a static receiver to listen for power-connection system broadcasts. Delete the entire &lt;receiver&gt; element.</li><li>In MainActivity.java, create a CustomReceiver object as a member variable and initialize it.</li></ol><pre>private CustomReceiver mReceiver = new CustomReceiver();</pre><h3>Create an intent filter with Intent actions</h3><p>Intent filters specify the types of intents a component can receive. They are used in filtering out the intents based on Intent values like action and category.</p><p>In MainActivity.java, at the end of the onCreate() method, create an <a href="https://developer.android.com/reference/android/content/IntentFilter">IntentFilter</a> object.</p><pre>IntentFilter filter = new IntentFilter();</pre><p>When the system receives an Intent as a broadcast, it searches the broadcast receivers based on the action value specified in the IntentFilter object.</p><p>In MainActivity.java, at the end of onCreate(), add the actions <a href="https://developer.android.com/reference/android/content/Intent.html#ACTION_POWER_CONNECTED">ACTION_POWER_CONNECTED</a> and <a href="https://developer.android.com/reference/android/content/Intent.html#ACTION_POWER_DISCONNECTED">ACTION_POWER_DISCONNECTED</a> to the IntentFilter object.</p><pre>filter.addAction(Intent.ACTION_POWER_DISCONNECTED);<br>filter.addAction(Intent.ACTION_POWER_CONNECTED);</pre><h3>Register and unregister the receiver</h3><p>In MainActivity.java, at the end of onCreate(), register your receiver using the MainActivity context. Your receiver is active and able to receive broadcasts as long as your MainActivity is running.</p><pre><em>// Register the receiver using the activity context.</em><br>this.registerReceiver(mReceiver, filter);</pre><p>In MainActivity.java, override the onDestroy() method and unregister your receiver. To save system resources and avoid leaks, dynamic receivers must be unregistered when they are no longer needed or before the corresponding activity or app is destroyed, depending on the context used.</p><pre>@Override<br>   protected void onDestroy() {<br>       <em>//Unregister the receiver</em><br>       this.unregisterReceiver(mReceiver);<br>       super.onDestroy();<br>   }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av5MS1vA0Oq5UciB6bD1ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yo0FH_3_7z60-lAZwLd_zQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNh_uK-PtN73VXUXAbC8UA.png" /></figure><h4>1.3 Implement onReceive() in your BroadcastReceiver</h4><p>When a broadcast receiver intercepts a broadcast that it’s registered for, the Intent is delivered to the receiver&#39;s <a href="https://developer.android.com/reference/android/content/BroadcastReceiver#onReceive(android.content.Context,%20android.content.Intent)">onReceive()</a> method.</p><p>In CustomReceiver.java, inside the onReceive() method, implement the following steps:</p><ol><li>Delete the entire onReceive() method implementation, including the UnsupportedOperationExceptioncode.</li><li>Get the Intent action from the intent parameter and store it in a String variable called intentAction.</li></ol><pre>@Override<br>public void onReceive(Context context, Intent intent) {<br>   String intentAction = intent.getAction();<br>}</pre><p>Create a switch statement with the intentAction string. (Before using intentAction, do a null check on it.) Display a different toast message for each action your receiver is registered for.</p><pre>if (intentAction != null) {<br>   String toastMessage = &quot;unknown intent action&quot;;<br>   switch (intentAction){<br>       case Intent.ACTION_POWER_CONNECTED:<br>           toastMessage = &quot;Power connected!&quot;;<br>           break;<br>       case Intent.ACTION_POWER_DISCONNECTED:<br>           toastMessage = &quot;Power disconnected!&quot;;<br>           break;<br>   }</pre><pre>  <em>//Display the toast.</em><br>}</pre><p>After the switch statement, add code to display a toast message for a short time:</p><pre>Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show();</pre><p>Run your app. After the app is running, connect or disconnect your device’s power supply. A Toast is displayed each time you connect or disconnect the power supply, as long as your Activity is running.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sods-Yp3IKCKFLMMS8p2aQ.png" /></figure><p>Result :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUkt7qkc09vEqqQtN19uMQ.png" /></figure><h4>Task 2. Send and receive a custom broadcast</h4><p>Android provides three ways for your app to send custom broadcasts:</p><ul><li><em>Normal broadcasts</em> are asynchronous. Receivers of normal broadcasts run in an undefined order, often at the same time. To send a normal broadcast, create a broadcast intent and pass it to <a href="https://developer.android.com/reference/android/content/Context.html#sendBroadcast(android.content.Intent)">sendBroadcast(Intent)</a>.</li><li><em>Local broadcasts</em> are sent to receivers that are in the same app as the sender. To send a local broadcast, create a broadcast intent and pass it to <a href="https://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html#sendBroadcast(android.content.Intent)">LocalBroadcastManager.sendBroadcast</a>.</li><li><em>Ordered broadcasts</em> are delivered to one receiver at a time. As each receiver executes, it can propagate a result to the next receiver, or it can cancel the broadcast so that the broadcast is not passed to other receivers. To send an ordered broadcast, create a broadcast intent and pass it to <a href="https://developer.android.com/reference/android/content/Context.html#sendOrderedBroadcast(android.content.Intent,%20java.lang.String)">sendOrderedBroadcast(Intent, String)</a>.</li></ul><h4>2.1 Define your custom broadcast action string</h4><ol><li>Create a constant member variable in both your MainActivity and your CustomReceiver class. You&#39;ll use this variable as the broadcast Intent action.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2AdsvOMYQiTO2KiJDn1VAA.png" /></figure><h3>2.2 Add a “Send Custom Broadcast” button</h3><ol><li>In your activity_main.xml layout file, replace the Hello World Textview with a Button that has the following attributes:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ppjral5fvFpg0W73q6jijQ.png" /></figure><p>Extract the string resource.</p><p>The sendCustomBroadcast() method will be the click-event handler for the button. To create a stub for sendCustomBroadcast() in Android Studio:</p><ol><li>Click the yellow highlighted sendCustomBroadcast method name. A red light bulb appears on the left.</li><li>Click the red light bulb and select Create ‘sendCustomBroadcast(View)’ in ‘MainActivity’.</li></ol><h4>2.3 Implement sendCustomBroadcast()</h4><p>In MainActivity.java, inside the sendCustomBroadcast() method, implement the following steps:</p><p>Create a new Intent, with your custom action string as the argument.</p><pre>Intent customBroadcastIntent = new Intent(ACTION_CUSTOM_BROADCAST);</pre><p>After the custom Intent declaration, send the broadcast using the LocalBroadcastManager class:</p><pre>LocalBroadcastManager.getInstance(this).sendBroadcast(customBroadcastIntent);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n9I_bOrOoUqf6-cwngTJhg.png" /></figure><h4>2.4 Register and unregister your custom broadcast</h4><p>In MainActivity.java, inside onCreate() method, get an instance of LocalBroadcastManager and register your receiver with the custom Intent action:</p><pre>LocalBroadcastManager.getInstance(this)<br>             .registerReceiver(mReceiver,<br>                          new IntentFilter(ACTION_CUSTOM_BROADCAST));</pre><p>In MainActivity.java, inside the onDestroy() method, unregister your receiver from the LocalBroadcastManager:</p><pre>LocalBroadcastManager.getInstance(this)<br>          .unregisterReceiver(mReceiver);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vbJEuK81F8QfMEt1AYIRQ.png" /></figure><h4>2.5 Respond to the custom broadcast</h4><p>In CustomReceiver.java, inside the onReceive() method, add another case statement in the switchblock for the custom Intent action. Use &quot;Custom Broadcast Received&quot; as the text for the toast message.</p><pre>case ACTION_CUSTOM_BROADCAST:<br>   toastMessage = &quot;Custom Broadcast Received&quot;;<br>   break;</pre><ol><li>Extract the string resource.</li><li>Run your app and tap the Send Custom Broadcast button to send a custom broadcast. Your receiver (CustomReceiver) displays a toast message.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejc_hog0HW1IsER4mdz27w.png" /></figure><p>That’s it! Your app delivers a custom broadcast and is able to receive both system and custom broadcasts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52a276422fea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>