[{"text": "\nAndroid Menus\n\nIn android, Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of menu, users can experience a smooth and consistent experience throughout the application. In order to use menu, we should define it in a separate XML file and use that file in our application based on our requirements. Also, we can use menu APIs to represent user actions and other options in our android application activities.\nHow to define Menu in XML File?\nAndroid Studio provides a standard XML format for the type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application. Here, we should create a new folder menu inside of our project directory (res/menu) to define the menu and also add a new XML file to build the menu with the following elements. Below is the example of defining a menu in the XML file (menu_example.xml).\nWay to create menu directory and menu resource file:\nTo create the menu directory just right-click on res folder and navigate to res->New->Android Resource Directory. Give resource directory name as menu and resource type also menu. one directory will be created under res folder.\nTo create xml resource file simply right-click on menu folder and navigate to New->Menu Resource File. Give name of file as menu_example. One menu_example.xml file will be created under menu folder.XML \n
\n \n \n \n It is the root element that helps in defining Menu in XML file and it also holds multiple elements.\n- It is used to create a single item in the menu. It also contains nested
element in order to create a submenu.\n It is optional and invisible for - elements to categorize the menu items so they can share properties like active state, and visibility.activity_main.xml\nIf we want to add a submenu in menu item, then we need to add a
element as the child of an - . Below is the example of defining a submenu in a menu item.XML \n
\n- \n\n
\n \n \n \n \n Android Different Types of Menus\nIn android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following:Android Options Menu\nAndroid Context Menu\nAndroid Popup MenuAndroid Options Menu is a primary collection of menu items in an android application and is useful for actions that have a global impact on the searching application. Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and is useful for elements that affect the selected content or context frame. Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content."}, {"text": "\nHow to add a Pie Chart into an Android Application\n\nA Pie Chart is a circular statistical graphic, which is divided into slices to illustrate numerical proportions. It depicts a special chart that uses \u201cpie slices\u201d, where each sector shows the relative sizes of data. A circular chart cuts in the form of radii into segments describing relative frequencies or magnitude also known as a circle graph. A pie chart represents numbers in percentages, and the total sum of all segments needs to equal 100%. \nHere is the Final Application which will be created.\nhttps://media.geeksforgeeks.org/wp-content/uploads/20240521115249/Pie-Chart-Android-Java.mp4\nStep-by-Step Implementation of Pie Chart in Android ApplicationSo let\u2019s see the steps to add a Pie Chart into an Android app. \nStep 1: Opening/Creating a New ProjectTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. \nNote: SelectJavaas the programming language.\nBy default, there will be two files activity_main.xml and MainActivity.java.\nStep 2: Before going to the Coding Section first you have to do some Pre-Task. 1. Navigate to Gradle Scripts->build.gradle (Module: app) Add the dependencies mentioned below:dependencies{ // For Card view implementation 'androidx.cardview:cardview:1.0.0' // Chart and graph library implementation 'com.github.blackfizz:eazegraph:1.2.2@aar' implementation 'com.nineoldandroids:library:2.4.0'}After Importing following dependencies and click the \u201csync Now\u201d on the above pop up. \n2. Naviagate to app->res->values->colors.xml: Add and Set the colors for your app. \ncolors.xml\n\n #024265 \n #024265 \n #05af9b #fb7268 \n #ededf2 \n #E3E0E0 #FFA726 \n #66BB6A \n #EF5350 \n #29B6F6 Step 3: Designing the Layout of the ApplicationBelow is the code for the xml file. \nactivity_main.xml After using this code in .xml file, the Layout will be like:Step 4: Changes in the MainActivity File to Add Functionality in the Application Open the MainActivity.java file there within the class, first of all create the object of TextView class and the pie chart class. \nJava // Create the object of TextView and PieChart class\n TextView tvR, tvPython, tvCPP, tvJava;\n PieChart pieChart;Secondly inside onCreate() method, we have to link those objects with their respective id\u2019s that we have given in .XML file. \nJava // Link those objects with their respective\n // id's that we have given in .XML file\n tvR = findViewById(R.id.tvR);\n tvPython = findViewById(R.id.tvPython);\n tvCPP = findViewById(R.id.tvCPP);\n tvJava = findViewById(R.id.tvJava);\n pieChart = findViewById(R.id.piechart);Create a private void setData() method outside onCreate() method and define it.Inside setData() method the most important task is going to happen that is how we set the data in the text file and as well as on the piechart. First of all inside setData() method set the percentage of language used in their respective text view. \nJava // Set the percentage of language used\n tvR.setText(Integer.toString(40));\n tvPython.setText(Integer.toString(30));\n tvCPP.setText(Integer.toString(5));\n tvJava.setText(Integer.toString(25));And then set this data to the pie chart and also set their respective colors using addPieSlice() method. \nJava // Set the data and color to the pie chart\n pieChart.addPieSlice(new PieModel(\"R\",Integer.parseInt(tvR.getText().toString()),\n Color.parseColor(\"#FFA726\")));\n \n pieChart.addPieSlice(new PieModel(\"Python\",Integer.parseInt(tvPython.getText().toString()),\n Color.parseColor(\"#66BB6A\"))); pieChart.addPieSlice(new PieModel(\"C++\",Integer.parseInt(tvCPP.getText().toString()),\n Color.parseColor(\"#EF5350\"))); pieChart.addPieSlice(new PieModel(\"Java\",Integer.parseInt(tvJava.getText().toString()),\n Color.parseColor(\"#29B6F6\")));For better look animate the piechart using startAnimation(). \nJava // To animate the pie chart\n pieChart.startAnimation();At last invoke the setData() method inside onCreate() method. \nBelow is the complete code for MainActivity.java file: \nMainActivity.javapackage com.example.final_pie_chart_java;// Import the required libraries\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport org.eazegraph.lib.charts.PieChart;\nimport org.eazegraph.lib.models.PieModel;public class MainActivity\n extends AppCompatActivity { // Create the object of TextView\n // and PieChart class\n TextView tvR, tvPython, tvCPP, tvJava;\n PieChart pieChart; @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); // Link those objects with their\n // respective id's that\n // we have given in .XML file\n tvR = findViewById(R.id.tvR);\n tvPython = findViewById(R.id.tvPython);\n tvCPP = findViewById(R.id.tvCPP);\n tvJava = findViewById(R.id.tvJava);\n pieChart = findViewById(R.id.piechart); // Creating a method setData()\n // to set the text in text view and pie chart\n setData();\n } private void setData()\n { // Set the percentage of language used\n tvR.setText(Integer.toString(40));\n tvPython.setText(Integer.toString(30));\n tvCPP.setText(Integer.toString(5));\n tvJava.setText(Integer.toString(25)); // Set the data and color to the pie chart\n pieChart.addPieSlice(\n new PieModel(\n \"R\",\n Integer.parseInt(tvR.getText().toString()),\n Color.parseColor(\"#FFA726\")));\n pieChart.addPieSlice(\n new PieModel(\n \"Python\",\n Integer.parseInt(tvPython.getText().toString()),\n Color.parseColor(\"#66BB6A\")));\n pieChart.addPieSlice(\n new PieModel(\n \"C++\",\n Integer.parseInt(tvCPP.getText().toString()),\n Color.parseColor(\"#EF5350\")));\n pieChart.addPieSlice(\n new PieModel(\n \"Java\",\n Integer.parseInt(tvJava.getText().toString()),\n Color.parseColor(\"#29B6F6\"))); // To animate the pie chart\n pieChart.startAnimation();\n }\n}Output:Run The Application, Check this article Android | Running your first Android app as the reference.Note : To access the full android application using Pie chat check this repository: Pie Chart Android Application\nClick Here to Learn How to Create Android Application\n"}, {"text": "\nDesugaring in Android\n\nGoogle has officially announced Kotlin as a recommended language for Android Development and that\u2019s why so many developers are switching from Java to Kotlin for Android development. So day by day new APIs are been introduced in Android by the Google Team and which are available in newer versions of Android devices as well. So Desugaring is also one of the important features in Android that we should enable in our app which will allow our apps to work in lower API levels as well. So in this article, we will learn about Desugaring.What is Desugaring?\nWhy we need Desugaring?\nPractical Implementation of Desugaring.\nWhat\u2019s happening under the hood?What is Desugaring?\nAndroid devices are getting optimized day by day. So many features in Android for users as well as developers are getting optimized. When any operating system of Android is developed, it is delivered with so many Java classes which provides support to different apps in user\u2019s devices for various functionalities such as time, date, and many other features. Now if we consider time API it was introduced in API level 26 and the apps which use this API will crash on the lower API level devices such as Marshmallow and lower versions. So in this case to avoid the app crashes Desugaring comes into play. It allows lower API levels to work with new JAVA libraries.\nWhy We Need Desugaring?\nSuppose for example we are using a new time API which is introduced in API level 26 and we have used this API of time in our app. This app will work perfectly for API level 26 and above but when we will install this app on the lower API level let suppose API level 23 or lower than that then our app will crash because our device OS supports the features provided from API level 23 and we are using features of API level 26 which will not work. So for avoiding this app crashes and to support the new features from API level 26 into API level 23 we have to add Desugaring in our app.\nPractical Implementation of Desugaring in Android\nWhen we are using features provided by API level 26 in the devices lower than API level 26 then the app will crash. In the apps with a lower API level, we will get to see an error as NoClassDefFoundError. So to resolve this error we have to enable Desugaring in Android.\nStep by Step implementation of Desugaring\nStep 1: Navigate to the Gradle Scripts > build.gradle(:app) and inside your dependencies section add the dependency given belowcoreLibraryDesugaring \u2018com.android.tools:desugar_jdk_libs:1.0.9\u2019Now after adding this dependency you have to add the below line in your compileOptions part of your codecoreLibraryDesugaringEnabled trueStep 2: Now we have to enable multiDex in our app for that navigate to your Gradle file inside that in the section of defaultConfig section add the below line asmultiDexEnabled trueAnd sync your project. After the successful project sync, Desugaring has been implemented in our app and now we will not get to see NoClassDefFoundError in the devices with lower API levels. The complete code for the Gradle file is given below:Kotlin plugins { \nid 'com.android.application'\nid 'kotlin-android'\n} android { \ncompileSdkVersion 30\nbuildToolsVersion \"30.0.2\"defaultConfig { \napplicationId \"com.gtappdevelopers.desugaring\"\nminSdkVersion 19\nmultiDexEnabled true\ntargetSdkVersion 30\nversionCode 1\nversionName \"1.0\"testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n} buildTypes { \nrelease { \nminifyEnabled false\nproguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n} \n} \ncompileOptions { \nsourceCompatibility JavaVersion.VERSION_1_8 \ntargetCompatibility JavaVersion.VERSION_1_8 \ncoreLibraryDesugaringEnabled true\n} \nkotlinOptions { \njvmTarget = '1.8'\n} \n} dependencies { implementation \"org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version\"\nimplementation 'androidx.core:core-ktx:1.3.2'\ncoreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.9'\nimplementation 'androidx.appcompat:appcompat:1.2.0'\nimplementation 'com.google.android.material:material:1.2.1'\nimplementation 'androidx.constraintlayout:constraintlayout:2.0.4'\ntestImplementation 'junit:junit:4.+'\nandroidTestImplementation 'androidx.test.ext:junit:1.1.2'\nandroidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'\n}What\u2019s Happening Under the Hood?\nSo what is happening here and how the java classes which were missing suddenly appear here. This is because of D8 and R8 tools. Previously for converting your app\u2019s code in dex code we have to use Proguard but to reduce compile-time and to reduce app size the new R8 tool was introduced. This R8 tool provides the support of missing Java classes. When this tool converts your app\u2019s code into dex code it also adds dex code of new java libraries which are then added in the APK. You can get a clear idea about this process from the below diagram.In this way, Desugaring works and it provides backward compatibility for new Java libraries in the devices with lower API levels. "}, {"text": "\nSlider Date Picker in Android\n\nSlider Date Picker is one of the most popular features that we see in most apps. We can get to see this Slider date picker in most of the travel planning applications, Ticket booking services, and many more. Using Slider date Picker makes it efficient to pick the date. In this article, we are going to see how to implement Slider Date Picker in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Applications of Slider Date PickerThe most common application of this Slider date picker is it is used in most travel planning apps.\nThis Date Picker can also be seen in Ticket Booking services.\nYou can get to see this Slider Date Picker in the exam form filling application.Attributes of Slider Date PickerAttributesDescription.setStartDate()\nTo set the starting Date of the Calendar..setEndDate()\nTo set the ending Date of the Calendar..setThemeColor()\nTo set the theme Color..setHeaderTextColor()\nTo set the header text Color..setHeaderDateFormat()\nTo set the Date Format..setShowYear()\nTo show the current year..setCancelText()\nTo cancel text..setConfirmText()\nTo confirm text..setPreselectedDate()\nTo select today\u2019s date.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add dependency and JitPack Repository\nNavigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation \u2018com.github.niwattep:material-slide-date-picker:v2.0.0\u2019Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.allprojects {\nrepositories {\n \u2026\n maven { url \u201chttps://jitpack.io\u201d }\n }\n}After adding this dependency sync your project and now we will move towards its implementation. \nStep 3: Create a new Slider Date Picker in your activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n\n \n Step 4: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import com.niwattep.materialslidedatepicker.SlideDatePickerDialog;\nimport com.niwattep.materialslidedatepicker.SlideDatePickerDialogCallback;import java.text.SimpleDateFormat;\nimport java.util.Calendar;\nimport java.util.Locale;public class MainActivity extends AppCompatActivity implements SlideDatePickerDialogCallback {// Initialize textview and button\nButton button;\nTextView textView;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// button and text view called using id\nbutton = findViewById(R.id.button);\ntextView = findViewById(R.id.textView);button.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View view) {\nCalendar endDate = Calendar.getInstance();\nendDate.set(Calendar.YEAR, 2100);\nSlideDatePickerDialog.Builder builder = new SlideDatePickerDialog.Builder();\nbuilder.setEndDate(endDate);\nSlideDatePickerDialog dialog = builder.build();\ndialog.show(getSupportFragmentManager(), \"Dialog\");\n}\n});\n}// date picker\n@Override\npublic void onPositiveClick(int date, int month, int year, Calendar calendar) {\nSimpleDateFormat format = new SimpleDateFormat(\"EEEE, MMM dd, yyyy\", Locale.getDefault());\ntextView.setText(format.format(calendar.getTime()));\n}\n}Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210120095139/Screenrecorder-2021-01-20-09-49-15-998.mp4"}, {"text": "\nHow to Install and Uninstall Plugins in Android Studio?\n\nAndroid Studio provides a platform where one can build apps for Android phones, tablets, Android Wear, Android TV, and Android Auto. Android Studio is the official IDE for Android application development, and it is based on the IntelliJ IDEA. One can develop Android Applications using Kotlin or Java as the Backend Language and it provides XML for developing Frontend Screens.In computing, a plug-in is a software component that adds a particular characteristic to an existing computer program. When a program supports plug-ins, it enables customization. Plugins are a great way to increase productivity and overall programming experience.\u2063\u2063Some tasks are boring and not fun to do, by using plugins in the android studio you can get more done in less time. Below is the list of some very useful plugins in the table that are highly recommendable for an android developer.PluginsDescriptionKey Promoter X\nKey Promoter X helps to get the necessary shortcuts while working on android projects. When the developers use the mouse on a button inside the IDE, the Key Promoter X shows the keyboard shortcut that you should have used instead.Json To Kotlin Class\nJson to Kotlin Class is a plugin to generate Kotlin data class from JSON string, in another word, a plugin that converts JSON string to Kotlin data class. With this, you can generate a Kotlin data class from the JSON string programmatically.Rainbow Brackets\nRainbow Brackets adds rainbow brackets and rainbows parentheses to the code. Color coding the brackets makes it simpler to obtain paired brackets so that the developers don\u2019t get lost in a sea of identical brackets. This is a very helpful tool and saves the confusion of selecting which bracket needs to be closed.CodeGlance\nCodeglance plugin illustrates a zoomed-out overview or minimap similar to the one found in Sublime into the editor pane. The minimap enables fast scrolling letting you jump straight to sections of code.ADB Idea\nADB Idea is a plugin for Android Studio and Intellij IDEA that speeds up the regular android development. It allows shortcuts for different emulator functionalities that are usually very time consuming, like resetting our app data, uninstalling our app, or starting the debugger.Step by Step Process to Install and Uninstall Plugins in Android Studio\nStep 1: Open the Android Studio and go to File > Settings as shown in the below image.Step 2: After hitting on the Settings button a pop-up screen will arise like the following. Here select Plugins in the left panel. Make sure you are on the Marketplace tab. Then search for the required plugins as per the developer\u2019s requirements. After selecting the required plugins then click on the green colors Install button at the right and at last click on the OK button below.Note: There might be a need to Restart the Android Studio. For example, you may refer to How to Install Genymotion Plugin to Android Studio.After these brief steps, you have your plugin installed and functional on Android Studio. Similarly if one wants to disable or uninstall the installed plugins then follow the last step.\nStep 3: To disable or uninstall a plugin this time go to the Installed tab. And here you can find the all installed plugins in your android studio. Just click on that plugin which one you want to disable or uninstall. Then select the Disable or Uninstall button at the right as shown in the below image. At last click on the OK button and you are done.Note: There might be a need to Restart the Android Studio."}, {"text": "\nDatePicker in Kotlin\n\nAndroid DatePicker is a user interface control which is used to select the date by day, month and year in our android application. DatePicker is used to ensure that the users will select a valid date.In android DatePicker having two modes, first one to show the complete calendar and second one shows the dates in spinner view.We can create a DatePicker control in two ways either manually in XML file or create it in Activity file programmatically.First we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Android DatePicker with Calendar mode\nWe can use android:datePickerMode to show only calendar view. In the below example, we are using the DatePicker in Calendar mode.XML The above code of DatePicker can be seen in android application like thisAndroid DatePicker with Spinner mode\nWe can also show the DatePicker in spinner format like selecting the day, month and year separately, by using android:datePickerMode attribute and set android:calendarViewShown=\u201dfalse\u201d, otherwise both spinner and calendar can be seen simultaneously.XML The above code of DatePicker can be seen in android application like thisDifferent attributes of DatePicker control \u2013XML Attributes\nDescriptionandroid:id\nUsed to uniquely identify the control.android:datePickerMode\nUsed to specify the mode of datepicker(spinner or calendar)android:calendarTextColor\nUsed to specify the color of the text.android:calendarViewShown\nUsed to specify whether view of the calendar is shown or not.android:background\nUsed to set background color of the Text View.android:padding\nUsed to set the padding from left, right, top and bottom.To use Calendar DatePicker in activity_main.xml\nIn this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file.XML \n To use Spinner DatePicker in activity_main.xml\nIn this file, we will add the DatePicker and Button widget and set their attributes so that it can be accessed in the kotlin file.XML \n Modify the strings.xml file to add the string-array\nHere, we will specify the name of the activity.XML \nDatePickerInKotlin \n Access the DatePicker in MainActivity.kt file\nFirst of all, we declare a variable datePicker to access the DatePicker widget from the XML layout.\nval datePicker = findViewById(R.id.date_Picker)\nthen, we declare another variable today to get the current get like this.\nval today = Calendar.getInstance()\n datePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH),\n today.get(Calendar.DAY_OF_MONTH)\nTo display the selected date from the calendar we will use\n { view, year, month, day ->\n val month = month + 1\n val msg = \"You Selected: $day/$month/$year\"\n Toast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show()\n }\nWe are familiar with further activities in previous articles like accessing button and set OnClickListener etc.Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.widget.* \nimport java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) val datePicker = findViewById(R.id.date_Picker) \nval today = Calendar.getInstance() \ndatePicker.init(today.get(Calendar.YEAR), today.get(Calendar.MONTH), \ntoday.get(Calendar.DAY_OF_MONTH) ) { view, year, month, day -> \nval month = month + 1\nval msg = \"You Selected: $day/$month/$year\"\nToast.makeText(this@MainActivity, msg, Toast.LENGTH_SHORT).show() \n} \n} \n} AndroidManifest.xml fileXML \n \n \n \n \n \n \n Run as Emulator:"}, {"text": "\nHow to Add WaveLineView in Android?\n\nIn this article, WaveLineView is implemented in android. WaveLineView provides us with a very beautiful UI. It can be used when the user has to wait for some time. WaveLineView makes our layout very attractive and hence enhancing the user experience of the app. WaveLineView provide two methods startAnim() and stopAnim(). WaveLineView can be used wherever the developer wants the user to wait for some time. Also, Progress Bar can be used instead of this but because of its unique UI, it will attract users and hence users wait for enough time. It also provides full control to Developers as they can customize it according to the requirements.\nStep By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Add the Required Dependencies\nNavigate to the Gradle Scripts > build.gradle(Module:app) and Add the Below Dependency in the Dependencies section.\nimplementation 'com.github.Jay-Goo:WaveLineView:v1.0.4'\nAdd the Support Library in your settings.gradle File. This library Jitpack is a novel package repository. It is made for JVM so that any library which is present in Github and Bitbucket can be directly used in the application.\ndependencyResolutionManagement {\n repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n repositories {\n google()\n mavenCentral()\n \n // add the following\n maven { url \"https://jitpack.io\" }\n }\n}\nAfter adding this Dependency, Sync the Project and now we will move towards its implementation.\nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail. In this file, we add WaveLineView to the layout.XML \n \n Step 4: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. WaveLineView provide us two method startAnim() and stopAnim(). startAnim() start the animation and stopAnim() stops it.Java import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport jaygoo.widget.wlv.WaveLineView;public class MainActivity extends AppCompatActivity {WaveLineView waveLineView;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);waveLineView = findViewById(R.id.waveLineView);\nwaveLineView.startAnim();\n}\n}Kotlin import android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport jaygoo.widget.wlv.WaveLineViewclass MainActivity : AppCompatActivity() {private lateinit var waveLineView: WaveLineViewoverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)waveLineView = findViewById(R.id.waveLineView)\nwaveLineView.startAnim()\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200709215403/Record_2020-07-09-21-49-10_6a33b8dc17ce0e45bec163fe538b18f01.mp4"}, {"text": "\nHow to Implement YoutubePlayerView Library in Android?\n\nIf you are looking to display YouTube videos inside your app without redirecting your user from your app to YouTube then this library is very helpful for you to use. With the help of this library, you can simply play videos from YouTube with the help of a video id inside your app itself without redirecting your user to YouTube. Now we will see the implementation of this library in our Android App. We are going toimplement this project using both Java and Kotlin Programming Language for Android.\nStep by Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Add the JAR File inside the Libs Folder in Android Studio\nDownload the JAR file from this link. To add this file open your android project in \u201cProject\u201d mode as shown in the below image.Then go to Your Project Name > app > libs and right-click on it and paste the downloaded JAR files. You may also refer to the below image.Note: You may also refer to this article How to Import External JAR Files in Android Studio?Step 3: Adding Dependency to the build.gradle File\nGo to Module build.gradle file and add this dependency.\nimplementation 'com.pierfrancescosoffritti.androidyoutubeplayer:core:10.0.3'\nNow click on the \u201csync now\u201d option which you will get to see in the top right corner after adding this library. After that, we are ready for integrating the YouTube video player into the app.\nStep 4: Working with the activity_main.xml File\nNow change the project tab in the top left corner to Android. After that navigate to the app > res > layout > activity_main.xml. Inside this, we will create a simple button that will redirect to a new activity where we will play our YouTube video. Below is the XML code snippet for the activity_main.xml file.XML \n \n \n Step 5: Create a New Empty Activity\nNow we will create a new activity where we will display our YouTube video player. To create a new activity navigate to the app > java > your app\u2019s package name and right-click on it > New > Activity > Empty Activity > Give a name to your activity and select Java/Kotlin as its language. Now your new activity has been created. (Here we have given the activity name as VideoPlayerActivity).\nStep 6: Implement YoutubePlayerView inside the New Activity\nBelow is the code for the activity_video_player.xml file.XML \n \n \n \n Step 7: Working with the VideoPlayerActivity File\nBefore working with the VideoPlayerActivity file let\u2019s have a look at how to get the video id of any YouTube video.Open YouTube and search for any video which you want to play inside your app. Play that video inside your browser. In the top section of your browser, there will be an address bar where you can get to see the URL for that video. For example, here we have taken the below URL.\nhttps://www.youtube.com/watch?v=vG2PNdI8axo\nInside the above URL, the video ID is present in the extreme left part i.e after the v = sign is your video id. In the above example, the video ID will be\nvG2PNdI8axo \nIn this way, we can get the URL for any video. Now go to the VideoPlayerActivity file and refer to the following code. Below is the code for the VideoPlayerActivity file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.Window; \nimport android.view.WindowManager; \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener; \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView; public class VideoPlayerActivity extends AppCompatActivity { // id of the video which we are playing. \nString video_id = \"vG2PNdI8axo\"; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); // below two lines are used to set our screen orientation in landscape mode. \nrequestWindowFeature(Window.FEATURE_NO_TITLE); \ngetWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_video_player); // below line of code is to hide our action bar. \ngetSupportActionBar().hide(); // declaring variable for youtubePlayer view \nfinal YouTubePlayerView youTubePlayerView = findViewById(R.id.videoPlayer); // below line is to place your youtube player in a full screen mode (i.e landscape mode) \nyouTubePlayerView.enterFullScreen(); \nyouTubePlayerView.toggleFullScreen(); // here we are adding observer to our youtubeplayerview. \ngetLifecycle().addObserver(youTubePlayerView); // below method will provides us the youtube player ui controller such \n// as to play and pause a video to forward a video and many more features. \nyouTubePlayerView.getPlayerUiController(); // below line is to enter full screen mode. \nyouTubePlayerView.enterFullScreen(); \nyouTubePlayerView.toggleFullScreen(); // adding listener for our youtube player view. \nyouTubePlayerView.addYouTubePlayerListener(new AbstractYouTubePlayerListener() { \n@Override\npublic void onReady(@NonNull YouTubePlayer youTubePlayer) { \n// loading the selected video into the YouTube Player \nyouTubePlayer.loadVideo(video_id, 0); \n} @Override\npublic void onStateChange(@NonNull YouTubePlayer youTubePlayer, @NonNull PlayerConstants.PlayerState state) { \n// this method is called if video has ended, \nsuper.onStateChange(youTubePlayer, state); \n} \n}); \n} \n}Kotlin import android.os.Bundle \nimport android.view.Window \nimport android.view.WindowManager \nimport androidx.appcompat.app.AppCompatActivity \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.PlayerConstants \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener \nimport com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView class VideoPlayerActivity : AppCompatActivity() { // id of the video which we are playing. \nvar video_id = \"vG2PNdI8axo\"override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) // below two lines are used to set our screen orientation in landscape mode. \nrequestWindowFeature(Window.FEATURE_NO_TITLE) \nwindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) setContentView(R.layout.activity_video_player) // below line of code is to hide our action bar. \nsupportActionBar?.hide() // declaring variable for youtubePlayer view \nval youTubePlayerView: YouTubePlayerView = findViewById(R.id.videoPlayer) // below line is to place your youtube player in a full screen mode (i.e landscape mode) \nyouTubePlayerView.enterFullScreen() \nyouTubePlayerView.toggleFullScreen() // here we are adding observer to our youtubeplayerview. \nlifecycle.addObserver(youTubePlayerView) // below method will provides us the youtube player ui controller such \n// as to play and pause a video to forward a video and many more features. \nyouTubePlayerView.getPlayerUiController() // below line is to enter full screen mode. \nyouTubePlayerView.enterFullScreen() \nyouTubePlayerView.toggleFullScreen() // adding listener for our youtube player view. \nyouTubePlayerView.addYouTubePlayerListener(object : AbstractYouTubePlayerListener() { \nfun onReady(youTubePlayer: YouTubePlayer) { \n// loading the selected video into the YouTube Player \nyouTubePlayer.loadVideo(video_id, 0) \n} fun onStateChange(youTubePlayer: YouTubePlayer, state: PlayerConstants.PlayerState) { \n// this method is called if video has ended, \nsuper.onStateChange(youTubePlayer, state) \n} \n}) \n} \n}Step 8: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.content.Intent; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // variable for our button \nButton playBtn; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Initialize our Button \nplayBtn = findViewById(R.id.idBtnPlayVideo); // we have set onclick listener for our button \nplayBtn.setOnClickListener(v -> { \n// we have declared an intent to open new activity. \nIntent i = new Intent(MainActivity.this, VideoPlayerActivity.class); \nstartActivity(i); \n}); \n} \n}Kotlin import android.content.Intent \nimport android.os.Bundle \nimport android.widget.Button \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // variable for our button \nlateinit var playBtn: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Initialize our Button \nplayBtn = findViewById(R.id.idBtnPlayVideo) // we have set onclick listener for our button \nplayBtn.setOnClickListener { \n// we have declared an intent to open new activity. \nval i = Intent(this, VideoPlayerActivity::class.java) \nstartActivity(i) \n} \n} \n}Step 9: Adding Permissions to the AndroidManifest.xml File\nIn AndroidManifest.xml, one needs to include the below permission, in order to access the internet. Navigate to the app > AndroidManifest.xml file there you have to add the below permissions.\n \n \n\nAlong with this, you will get to see an activity section inside your application tag. Inside that, add your video player\u2019s activity screen orientation to landscape mode.\n\n\n \nBelow is the code for the complete AndroidManifest.xml file:XML \n \n \n \n \n \n \n \n \n \n \n Output: Run the App on a Physical Devicehttps://media.geeksforgeeks.org/wp-content/uploads/20201214160612/Screenrecorder-2020-12-14-15-53-30-976.mp4\nCheck out the project on the below GitHub link: https://github.com/ChaitanyaMunje/YoutubePlayerView"}, {"text": "\nHow to create a Stopwatch App using Android Studio\n\nIn this article, an Android app is created to display a basic Stopwatch.\nThe layout for Stopwatch includes:A TextView: showing how much time has passed\nThree Buttons:Start: To start the stopwatch\nStop: To stop the stopwatch\nReset: To reset the stopwatch to 00:00:00Steps to create the Stopwatch:Create a new project for Stopwatch App\nAdd String resources\nUpdate the Stopwatch layout code\nUpdate the code for activityBelow are the steps one by one in detail:Create a new project for Stopwatch AppCreate a new Android project for an application named \u201cStopwatch\u201d with a company domain of \u201cgeeksforgeeks.org\u201d, making the package name org.geeksforgeeks.stopwatch.\nCreate a New project and select Empty Activity\nConfigure the projectThe minimum SDK should be API 14 so it can run on almost all devices.\nAn empty activity called \u201cStopwatchActivity\u201d and a layout called \u201cactivity_stopwatch\u201d will be created.\nFirst opening screenAdd String resources\nWe are going to use three String values in our stopwatch layout, one for the text value of each button. These values are String resources, so they need to be added to strings.xml. Add the String values below to your version of strings.xml:Strings.xml \nGFG|Stopwatch \nStart \nStop \nReset \n Update the Stopwatch layout code\nHere is the XML for the layout. It describes a single text view that\u2019s used to display the timer, and three buttons to control the stopwatch. Replace the XML currently in activity_stopwatch.xml with the XML shown here:activity_stopwatch.xml \n\nandroid:background=\"#0F9D58\" \nandroid:padding=\"16dp\" \ntools:context=\"org.geeksforgeeks.stopwatch.StopwatchActivity\"> \n\nandroid:id=\"@+id/time_view\" \nandroid:layout_width=\"wrap_content\" \nandroid:layout_height=\"wrap_content\" \nandroid:layout_gravity=\"center_horizontal\" \n\nandroid:textAppearance=\"@android:style/TextAppearance.Large\" \nandroid:textSize=\"56sp\" /> \n\nandroid:onClick=\"onClickStart\" \nandroid:text=\"@string/start\" /> \n\nandroid:id=\"@+id/stop_button\" \nandroid:layout_width=\"wrap_content\" \nandroid:layout_height=\"wrap_content\" \nandroid:layout_gravity=\"center_horizontal\" \nandroid:layout_marginTop=\"8dp\" \n\nandroid:onClick=\"onClickStop\" \nandroid:text=\"@string/stop\" /> \n\nandroid:id=\"@+id/reset_button\" \nandroid:layout_width=\"wrap_content\" \nandroid:layout_height=\"wrap_content\" \nandroid:layout_gravity=\"center_horizontal\" \nandroid:layout_marginTop=\"8dp\" \n\nandroid:onClick=\"onClickReset\" \nandroid:text=\"@string/reset\" /> \n How the activity code will work\nThe layout defines three buttons that we will use to control the stopwatch. Each button uses its onClick attribute to specify which method in the activity should run when the button is clicked. When the Start button is clicked, the onClickStart() method gets called, when the Stop button is clicked the onClickStop() method gets called, and when the Reset button is clicked the onClickReset() method gets called. We will use these methods to start, stop and reset the stopwatch.\nWe will update the stopwatch using a method we will create called runTimer(). The runTimer() method will run code every second to check whether the stopwatch is running, and, if it is, increment the number of seconds and display the number of seconds in the text view.\nTo help us with this, we will use two private variables to record the state of the stopwatch. We will use an int called seconds to track how many seconds have passed since the stopwatch started running, and a boolean called running to record whether the stopwatch is currently running.\nWe will start by writing the code for the buttons, and then we will look at the runTimer() method.Add code for the buttons When the user clicks on the Start button, we will set the running variable to true so that the stopwatch will start. When the user clicks on the Stop button, we will set running to false so that the stopwatch stops running. If the user clicks on the Reset button, we will set running to false and seconds to 0 so that the stopwatch is reset and stops running.The runTimer() method The next thing we need to do is to create the runTimer() method. This method will get a reference to the text view in the layout; format the contents of the seconds variable into hours, minutes, and seconds; and then display the results in the text view. If the running variable is set to true, it will increment the seconds variable.Handlers allow you to schedule code A Handler is an Android class you can use to schedule code that should be run at some point in the future. You can also use it to post code that needs to run on a different thread than the main Android thread. In our case, we are going to use a Handler to schedule the stopwatch code to run every second.\nTo use the Handler, you wrap the code you wish to schedule in a Runnable object, and then use the Handle post() and postDelayed() methods to specify when you want the code to run.The post() method The post() method posts code that needs to be run as soon as possible(which is usually immediately). This method takes one parameter, an object of type Runnable. A Runnable object in Androidville is just like a Runnable in plain old Java: a job you want to run. You put the code you want to run in the Runnable\u2019s run() method, and the Handler will make sure the code is run as soon as possible.The postDelayed() method The postDelayed() method works in a similar way to the post() method except that you use it to post code that should be run in the future. The postDelayed() method takes two parameters: a Runnable and a long. The Runnable contains the code you want to run in its run() method, and the long specifies the number of milliseconds you wish to delay the code by. The code will run as soon as possible after the delay.Below is the following code to StopwatchActivity.java:StopwatchActivity.java package org.geeksforgeeks.stopwatch; import android.app.Activity; \nimport android.os.Handler; \nimport android.view.View; \nimport android.os.Bundle; \nimport java.util.Locale; \nimport android.widget.TextView; public class StopwatchActivity extends Activity { // Use seconds, running and wasRunning respectively \n// to record the number of seconds passed, \n// whether the stopwatch is running and \n// whether the stopwatch was running \n// before the activity was paused. // Number of seconds displayed \n// on the stopwatch. \nprivate int seconds = 0; // Is the stopwatch running? \nprivate boolean running; private boolean wasRunning; @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_stopwatch); \nif (savedInstanceState != null) { // Get the previous state of the stopwatch \n// if the activity has been \n// destroyed and recreated. \nseconds \n= savedInstanceState \n.getInt(\"seconds\"); \nrunning \n= savedInstanceState \n.getBoolean(\"running\"); \nwasRunning \n= savedInstanceState \n.getBoolean(\"wasRunning\"); \n} \nrunTimer(); \n} // Save the state of the stopwatch \n// if it's about to be destroyed. \n@Override\npublic void onSaveInstanceState( \nBundle savedInstanceState) \n{ \nsavedInstanceState \n.putInt(\"seconds\", seconds); \nsavedInstanceState \n.putBoolean(\"running\", running); \nsavedInstanceState \n.putBoolean(\"wasRunning\", wasRunning); \n} // If the activity is paused, \n// stop the stopwatch. \n@Override\nprotected void onPause() \n{ \nsuper.onPause(); \nwasRunning = running; \nrunning = false; \n} // If the activity is resumed, \n// start the stopwatch \n// again if it was running previously. \n@Override\nprotected void onResume() \n{ \nsuper.onResume(); \nif (wasRunning) { \nrunning = true; \n} \n} // Start the stopwatch running \n// when the Start button is clicked. \n// Below method gets called \n// when the Start button is clicked. \npublic void onClickStart(View view) \n{ \nrunning = true; \n} // Stop the stopwatch running \n// when the Stop button is clicked. \n// Below method gets called \n// when the Stop button is clicked. \npublic void onClickStop(View view) \n{ \nrunning = false; \n} // Reset the stopwatch when \n// the Reset button is clicked. \n// Below method gets called \n// when the Reset button is clicked. \npublic void onClickReset(View view) \n{ \nrunning = false; \nseconds = 0; \n} // Sets the NUmber of seconds on the timer. \n// The runTimer() method uses a Handler \n// to increment the seconds and \n// update the text view. \nprivate void runTimer() \n{ // Get the text view. \nfinal TextView timeView \n= (TextView)findViewById( \nR.id.time_view); // Creates a new Handler \nfinal Handler handler \n= new Handler(); // Call the post() method, \n// passing in a new Runnable. \n// The post() method processes \n// code without a delay, \n// so the code in the Runnable \n// will run almost immediately. \nhandler.post(new Runnable() { \n@Overridepublic void run() \n{ \nint hours = seconds / 3600; \nint minutes = (seconds % 3600) / 60; \nint secs = seconds % 60; // Format the seconds into hours, minutes, \n// and seconds. \nString time \n= String \n.format(Locale.getDefault(), \n\"%d:%02d:%02d\", hours, \nminutes, secs); // Set the text view text. \ntimeView.setText(time); // If running is true, increment the \n// seconds variable. \nif (running) { \nseconds++; \n} // Post the code again \n// with a delay of 1 second. \nhandler.postDelayed(this, 1000); \n} \n}); \n} \n} Output:\nOutput of Stopwatch App."}, {"text": "\nAndroid App Development Fundamentals for Beginners\n\nAndroid is an operating system that is built basically for Mobile phones. It is based on the Linux Kernel and other open-source software and is developed by Google. It is used for touchscreen mobile devices such as smartphones and tablets. But nowadays these are used in Android Auto cars, TV, watches, camera, etc. It has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. Various applications (apps) like games, music player, camera, etc. are built for these smartphones for running on Android. Google Play store features more than 3.3 million apps. The app is developed on an application known as Android Studio. These executable apps are installed through a bundle or package called APK(Android Package Kit).\nAndroid Fundamentals\n1. Android Programming Languages\nIn Android, basically, programming is done in two languages JAVA or C++ and XML(Extension Markup Language). Nowadays KOTLIN is also preferred. The XML file deals with the design, presentation, layouts, blueprint, etc (as a front-end) while the JAVA or KOTLIN deals with the working of buttons, variables, storing, etc (as a back-end).\n2. Android Components\nThe App components are the building blocks of Android. Each component has its own role and life cycles i.e from launching of an app till the end. Some of these components depend upon others also. Each component has a definite purpose. The four major app components are:Activities\nServices\nBroadcast Receivers:\nContent Provider:Activities: It deals with the UI and the user interactions to the screen. In other words, it is a User Interface that contains activities. These can be one or more depending upon the App. It starts when the application is launched. At least one activity is always present which is known as MainActivity. The activity is implemented through the following. \nSyntax:\npublic class MainActivity extends Activity{\n // processes\n}\nTo know more Activities please refer to this article: Introduction to Activities in Android\nServices: Services are the background actions performed by the app, these might be long-running operations like a user playing music while surfing the Internet. A service might need other sub-services so as to perform specific tasks. The main purpose of the Services is to provide non-stop working of the app without breaking any interaction with the user.\nSyntax:\npublic class MyServices extends Services{\n // code for the services\n}\nTo know more Services please refer to this article:Services in Android with Example\nBroadcast Receivers: A Broadcast is used to respond to messages from other applications or from the System. For example, when the battery of the phone is low, then the Android OS fires a Broadcasting message to launch the Battery Saver function or app, after receiving the message the appropriate action is taken by the app. Broadcast Receiver is the subclass of BroadcastReceiver class and each object is represented by Intent objects.\nSyntax: \npublic class MyReceiver extends BroadcastReceiver{\n public void onReceive(context,intent){\n }\nTo know more Broadcast Receivers please refer to this article:Broadcast Receiver in Android With Example\nContent Provider: Content Provider is used to transferring the data from one application to the others at the request of the other application. These are handled by the class ContentResolver class. This class implements a set of APIs(Application Programming Interface) that enables the other applications to perform the transactions. Any Content Provider must implement the Parent Class of ContentProvider class.\nSyntax:\npublic class MyContentProvider extends ContentProvider{\n public void onCreate()\n {}\n}\nTo know more Content Provider please refer to this article:Content Providers in Android with Example\n3. Structural Layout Of Android Studio\nThe basic structural layout of Android Studio is given below:The above figure represents the various structure of an app.\nManifest Folder: Android Manifest is an XML file that is the root of the project source set. It describes the essential information about the app and the Android build tools, the Android Operating System, and Google Play. It contains the permission that an app might need in order to perform a specific task. It also contains the Hardware and the Software features of the app, which determines the compatibility of an app on the Play Store. It also includes special activities like services, broadcast receiver, content providers, package name, etc.\nJava Folder: The JAVA folder consists of the java files that are required to perform the background task of the app. It consists of the functionality of the buttons, calculation, storing, variables, toast(small popup message), programming function, etc. The number of these files depends upon the type of activities created.\nResource Folder: The res or Resource folder consists of the various resources that are used in the app. This consists of sub-folders like drawable, layout, mipmap, raw, and values. The drawable consists of the images. The layout consists of the XML files that define the user interface layout. These are stored in res.layout and are accessed as R.layout class. The raw consists of the Resources files like audio files or music files, etc. These are accessed through R.raw.filename. values are used to store the hardcoded strings(considered safe to store string values) values, integers, and colors. It consists of various other directories like:R.array :arrays.xml for resource arrays\nR.integer : integers.xml for resource integers\nR.bool : bools.xml for resource boolean\nR.color :colors.xml for color values\nR.string : strings.xml for string values\nR.dimen : dimens.xml for dimension values\nR.style : styles.xml for stylesGradle Files: Gradle is an advanced toolkit, which is used to manage the build process, that allows defining the flexible custom build configurations. Each build configuration can define its own set of code and resources while reusing the parts common to all versions of your app. The Android plugin for Gradle works with the build toolkit to provide processes and configurable settings that are specific to building and testing Android applications. Gradle and the Android plugin run independently of Android Studio. This means that you can build your Android apps from within Android Studio. The flexibility of the Android build system enables you to perform custom build configurations without modifying your app\u2019s core source files.\nBasic Layout Can be defined in a tree structure as:\nProject/\n app/\n manifest/\n AndroidManifest.xml\n java/\n MyActivity.java \n res/\n drawable/ \n icon.png\n background.png\n drawable-hdpi/ \n icon.png\n background.png \n layout/ \n activity_main.xml\n info.xml\n values/ \n strings.xml \n4. Lifecycle of Activity in Android App\nThe Lifecycle of Activity in Android App can be shown through this diagram:States of Android Lifecycle:OnCreate: This is called when activity is first created.\nOnStart: This is called when the activity becomes visible to the user.\nOnResume: This is called when the activity starts to interact with the user.\nOnPause: This is called when activity is not visible to the user.\nOnStop: This is called when activity is no longer visible.\nOnRestart: This is called when activity is stopped, and restarted again.\nOnDestroy: This is called when activity is to be closed or destroyed.To know more about Activity Lifecycle in Android Please refer to this article: Activity Lifecycle in Android with Demo App\nTo begin your journey in Android you may refer to these tutorials:Android Tutorial\nKotlin Android Tutorial\nAndroid Studio Tutorial\nAndroid Projects \u2013 From Basic to Advanced Level"}, {"text": "\nDynamic Switch in Kotlin\n\nAndroid Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF.The Switch element is useful when only two states require for activity either choose ON or OFF. We can add a Switch to our application layout by using the Switch object. By default, the state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = \u201ctrue\u201d in our XML layout file.In android, we can create Switch control in two ways either by using Switch in XML layout file or creating it in Kotlin file dynamically.First, we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.LinearLayout in activity_main.xml file\nIn this file, we use the LinearLayout and can not add the switch widget manually because it will be created dynamically in Kotlin file.XML \n Add application name in strings.xml fileHere, we can put all the strings which can be used in the application in any file. So, we update the app_name which can be seen at the top of the activity.XML \nDynamicSwitchInKotlin \n Creating switches programmatically in MainActivity.kt file\nHere, we initialize and define two switches and add dynamically by calling on the linearLayout.\nlinearLayout?.addView(switch1)\nlinearLayout?.addView(switch2)\nthen, set OnClickListener on both the switches for functioning like toggle of button and Toast message like this.\nswitch1.setOnCheckedChangeListener { buttonView, isChecked ->\n val msg = if (isChecked) \"SW1:ON\" else \"SW1:OFF\"\n Toast.makeText(this@MainActivity, msg,\n Toast.LENGTH_SHORT).show()\n }\nComplete code for the Kotlin file is below.Kotlin package com.geeksforgeeks.myfirstkotlinapp\nimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.view.ViewGroup\nimport android.widget.LinearLayout\nimport android.widget.Switch\nimport android.widget.Toastclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// Creating switch1 and switch2 programmatically\nval switch1 = Switch(this)\nval layoutParams = LinearLayout.LayoutParams(ViewGroup.\nLayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)\nswitch1.layoutParams = layoutParams\nswitch1.text = \"Switch1\"val switch2 = Switch(this)\nval layoutParams2 = LinearLayout.LayoutParams(ViewGroup.\nLayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)\nswitch2.layoutParams = layoutParams2\nswitch2.text = \"Switch2\"val linearLayout = findViewById(R.id.rootContainer)\n// Adding Switches to LinearLayout\nlinearLayout?.addView(switch1)\nlinearLayout?.addView(switch2)switch1.setOnCheckedChangeListener { buttonView, isChecked ->\nval msg = if (isChecked) \"SW1:ON\" else \"SW1:OFF\"\nToast.makeText(this@MainActivity, msg,\nToast.LENGTH_SHORT).show()\n}switch2.setOnCheckedChangeListener { buttonView, isChecked ->\nval msg = if (isChecked) \"SW2:ON\" else \"SW2:OFF\"\nToast.makeText(this@MainActivity, msg,\nToast.LENGTH_SHORT).show()\n}\n}\n}AndroidManifest.xml fileXML \n\n\n\n \n \n \n Run as emulator for Output:"}, {"text": "\nWelcome to The Modern Android App Development\n\nWith the spread of smartphones, smartphone technology improved exponentially and thus smartphones occupied a huge part of the market. To meet the requirement of the user and seeing the wide-open market there came different operating systems like Android, iOS, etc but for the sake of this article, we gonna talk specifically about how Android Development changed and what it looks like today. Today for making an Android App you don\u2019t need to learn any programming language. Little strange, right!. Yes, but, indeed, you don\u2019t need to learn programming language but you just need to have problem-solving skills. I know that learning programming language teaches that but when we say you don\u2019t need programming language it means you don\u2019t need to learn syntax and semantics and the process is too visual that it doesn\u2019t feel like coding when in reality you are doing exactly \u201ccoding\u201d. And Yes we will learn to create a simple Android App from this article itself, so enjoy reading!\nHow Modern Android App Development Looks Like\nBlocky is the modern way of creating android apps. Instead of traditionally coding in an IDE in Blocky represent coding concepts in form of interlocking blocksThese interlocking blocks make it easier to visualize and help in capturing the flow of the program. Blocky is an open-source library that helps us in visualizing the blocks and using blocky there are several platforms that let us create android apps. MIT App Inventor is an open-source platform that let\u2019s use blocky for creating the android app. In this modern way, developers develop the app in two sections:Designer: The designer creates the User Interface (UI) with several pre-existing components by drag and drop.\nBlocks: Blocks do all the logic work and are used to change several properties of components used in the designer.Let\u2019s Build a Simple Hello World App\nRequirements\nAs blocky is a javascript library this helps us to create android apps directly from your web browser and thus you need:Browser\nInternet ConnectionNote: Offline mode also exists.Step by Step Implementation\nStep 1: Go to MIT App Inventor\u2019s creator and log in your using google account and click \u201cstart new project\u201cStep 2: Enter your project name and click \u201cOK\u201cStep 3: Your empty project will look like this.Step 4:Now drag and drop the \u201cButton\u201d and \u201cLabel\u201d components from Palette.Step 5:Click on the \u201cButton\u201d component which we dragged and then from right from \u201cproperties\u201d change \u201cButton Text\u201d to \u201cClick Me\u201d similarly select \u201clabel\u201d and change \u201clabel Text\u201d to an empty string.Note: Label disappears because we changed its text to an empty string.Step 6:That is enough for the Designer view now to switch to \u201cBlock\u201d from the top right corner. Click on a component to access respective blocks and drag and drop the required one.We will use simple logic. When the user clicks on the button app must change the label text to \u201cHello World!\u201dOur app is ready now we just need to export in. From the menu click \u201cBuild\u201d and select whether you want to apk to be downloaded to the computer or generate a downloadable QR code with a link. Now simply install it on your device.\nOutput:Conclusion\nModern Android app development is a very fast and efficient way of developing apps without learning any language. However, it isn\u2019t the complete replacement of native development and code. It is great for the time you need visualization and also good for introducing kids to how the program works and can be really useful for them to build their own logic and algorithms and see them working in reality.\n"}, {"text": "\nArrayAdapter in Android with Example\n\nThe Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When you have a list of single type items which are stored in an array you can use ArrayAdapter. Likewise, if you have a list of phone numbers, names, or cities. ArrayAdapter has a layout with a single TextView. If you want to have a more complex layout instead of ArrayAdapter use CustomArrayAdapter. The basic syntax for ArrayAdapter is given as:public ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)ParametersParametersDescriptioncontext\nThe current context. This value can not be null.resource\nThe resource ID for the layout file containing a layout to use when instantiating views.textViewResourceId\nThe id of the TextView within the layout resource to be populated.objects\nThe objects to represent in the ListView. This value cannot be null.context: It is used to pass the reference of the current class. Here \u2018this\u2019 keyword is used to pass the current class reference. Instead of \u2018this\u2019 we could also use the getApplicationContext() method which is used for the Activity and the getApplication() method which is used for Fragments.public ArrayAdapter(this, int resource, int textViewResourceId, T[] objects)resource: It is used to set the layout file(.xml files) for the list items.public ArrayAdapter(this, R.layout.itemListView, int textViewResourceId, T[] objects)textViewResourceId: It is used to set the TextView where you want to display the text data.public ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, T[] objects)objects: These are the array object which is used to set the array element into the TextView.String courseList[] = {\u201cC-Programming\u201d, \u201cData Structure\u201d, \u201cDatabase\u201d, \u201cPython\u201d,\n \u201cJava\u201d, \u201cOperating System\u201d,\u201dCompiler Design\u201d, \u201cAndroid Development\u201d};\nArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.itemListView, R.id.itemTextView, courseList[]);Example\nIn this example, the list of courses is displayed using a simple array adapter. Note that we are going toimplement this project using theJavalanguage.\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Working with the activity_main.xml file\nGo to the layout folder and in activity_main.xml file change the ConstraintLayout to RelativeLayout and insert a ListView with id simpleListView. Below is the code for theactivity_main.xml file.XML \n Step 3: Create a new layout file\nGo to app > res > layout > right-click > New > Layout Resource File and create a new layout file and name this file as item_view.xml and make the root element as a LinearLayout. This will contain a TextView that is used to display the array objects as output.XML \n Step 4: Working with the MainActivity.java file\nNow go to the java folder and in MainActivity.java and provide the implementation to the ArrayAdapter. Below is the code for theMainActivity.java file.Java import android.os.Bundle; \nimport android.widget.ArrayAdapter; \nimport android.widget.ListView; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { ListView simpleListView; // array objects \nString courseList[] = {\"C-Programming\", \"Data Structure\", \"Database\", \"Python\", \n\"Java\", \"Operating System\", \"Compiler Design\", \"Android Development\"}; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); simpleListView = (ListView) findViewById(R.id.simpleListView); ArrayAdapter arrayAdapter = new ArrayAdapter(this, \nR.layout.item_view, R.id.itemTextView, courseList); \nsimpleListView.setAdapter(arrayAdapter); \n} \n}Output: Run on Emulator"}, {"text": "\nNavigation Drawer in Android\n\nThe navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel that shows your app\u2019s main navigation menu. It is also one of the important UI elements, which provides actions preferable to the users, for example changing user profile, changing settings of the application, etc. In this article, it has been discussed step by step to implement the navigation drawer in android. The code has been given in both Java and Kotlin Programming Language for Android.The navigation drawer slides in from the left and contains the navigation destinations for the app.The user can view the navigation drawer when the user swipes a finger from the left edge of the activity. They can also find it from the home activity by tapping the app icon in the action bar. The drawer icon is displayed on all top-level destinations that use a DrawerLayout. Have a look at the following image to get an idea about the Navigation drawer.Steps to Implement Navigation Drawer in Android\nStep 1: Create a New Android Studio Project\nCreate an empty activity android studio project. Refer to Android | How to Create/Start a New Project in Android Studio? on how to create an empty activity android studio project.\nStep 2: Adding a dependency to the project\nIn this discussion, we are going to use the Material Design Navigation drawer. So add the following Material design dependency to the app-level Gradle file.\nimplementation 'com.google.android.material:material:1.3.0-alpha03'\nRefer to the following image if unable to locate the app-level Gradle file that invokes the dependency (under project hierarchy view). After invoking the dependency click on the \u201cSync Now\u201d button. Make sure the system is connected to the network so that Android Studio downloads the required files.Step 3: Creating a menu in the menu folder\nCreate the menu folder under the res folder. To implement the menu. Refer to the following video to create the layout to implement the menu.https://media.geeksforgeeks.org/wp-content/uploads/20201114124319/Untitled-Project.mp4\nInvoke the following code in the navigation_menu.xmlXML \n Step 4: Working with the activity_main.xml File\nInvoke the following code in the activity_main.xml to set up the basic things required for the Navigation Drawer.XML \n \n\n Output UI:One thing to be noticed is that the menu drawer icon is still not appeared on the action bar. We need to set the icon and its open-close functionality programmatically.\nStep 5: Include the Open Close strings in the string.xml\nInvoke the following code in the app/res/values/strings.xml file.XML \nNavigation Drawer \n\nOpen \nClose \n Step 6: Working with the MainActivity FileInvoke the following code in the MainActivity file to show the menu icon on the action bar and implement the open-close functionality of the navigation drawer.\nComments are added inside the code for better understanding.Java import androidx.annotation.NonNull; \nimport androidx.appcompat.app.ActionBarDrawerToggle; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.drawerlayout.widget.DrawerLayout; \nimport android.os.Bundle; \nimport android.view.MenuItem; public class MainActivity extends AppCompatActivity { public DrawerLayout drawerLayout; \npublic ActionBarDrawerToggle actionBarDrawerToggle; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // drawer layout instance to toggle the menu icon to open \n// drawer and back button to close drawer \ndrawerLayout = findViewById(R.id.my_drawer_layout); \nactionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close); // pass the Open and Close toggle for the drawer layout listener \n// to toggle the button \ndrawerLayout.addDrawerListener(actionBarDrawerToggle); \nactionBarDrawerToggle.syncState(); // to make the Navigation drawer icon always appear on the action bar \ngetSupportActionBar().setDisplayHomeAsUpEnabled(true); \n} // override the onOptionsItemSelected() \n// function to implement \n// the item click listener callback \n// to open and close the navigation \n// drawer when the icon is clicked \n@Override\npublic boolean onOptionsItemSelected(@NonNull MenuItem item) { if (actionBarDrawerToggle.onOptionsItemSelected(item)) { \nreturn true; \n} \nreturn super.onOptionsItemSelected(item); \n} \n}Kotlin import android.os.Bundle \nimport android.view.MenuItem \nimport androidx.appcompat.app.ActionBarDrawerToggle \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.drawerlayout.widget.DrawerLayout class MainActivity : AppCompatActivity() { \nlateinit var drawerLayout: DrawerLayout \nlateinit var actionBarDrawerToggle: ActionBarDrawerToggle override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // drawer layout instance to toggle the menu icon to open \n// drawer and back button to close drawer \ndrawerLayout = findViewById(R.id.my_drawer_layout) \nactionBarDrawerToggle = ActionBarDrawerToggle(this, drawerLayout, R.string.nav_open, R.string.nav_close) // pass the Open and Close toggle for the drawer layout listener \n// to toggle the button \ndrawerLayout.addDrawerListener(actionBarDrawerToggle) \nactionBarDrawerToggle.syncState() // to make the Navigation drawer icon always appear on the action bar \nsupportActionBar?.setDisplayHomeAsUpEnabled(true) \n} // override the onOptionsItemSelected() \n// function to implement \n// the item click listener callback \n// to open and close the navigation \n// drawer when the icon is clicked \noverride fun onOptionsItemSelected(item: MenuItem): Boolean { \nreturn if (actionBarDrawerToggle.onOptionsItemSelected(item)) { \ntrue\n} else super.onOptionsItemSelected(item) \n} \n}Output: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201114130020/Untitled-Project.mp4"}, {"text": "\nHow to Add Mask to an EditText in Android?\n\nEditText is an android widget. It is a User Interface element used for entering and modifying data. It returns data in String format. Masking refers to the process of putting something in place of something else. Therefore by Masking an EditText, the blank space is replaced with some default text, known as Mask. This mask gets removed as soon as the user enters any character as input, and reappears when the text has been removed from the EditText. In this article, the masking is done with the help of JitPack Library, because it can be customized easily according to the need to implement various fields like phone number, date, etc. The code has been given in both Java and Kotlin Programming Language for Android.Approach:\nAdd the support Library in your settings.gradle File. This library Jitpack is a novel package repository. It is made for JVM so that any library which is present in Github and Bitbucket can be directly used in the application.\ndependencyResolutionManagement {\n repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n repositories {\n google()\n mavenCentral()\n \n // add the following\n maven { url \"https://jitpack.io\" }\n }\n}\nAdd the below dependency in the dependencies section of your App/Module build.gradle File. It is a simple Android EditText with custom mask support. Mask EditText is directly imported and is customized according to the use.\ndependencies {\n implementation 'ru.egslava:MaskedEditText:1.0.5'\n}\nNow add the following code in the activity_main.xml file. It will create three mask EditTexts and one button in activity_main.xml.XML \n \n \n \n \n Now add the following code in the MainActivity File. All the three mask EditTexts and a button are defined. An onClickListener() is added on the button which creates a toast and shows all the data entered in the mask EditTexts.Java import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport br.com.sapereaude.maskedEditText.MaskedEditText;public class MainActivity extends AppCompatActivity {MaskedEditText creditCardText,phoneNumText,dateText;\nButton show;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);creditCardText = findViewById(R.id.card);\nphoneNumText = findViewById(R.id.phone);\ndateText = findViewById(R.id.Date);\nshow = findViewById(R.id.showButton);show.setOnClickListener(v -> {\n// Display the information from the EditText with help of Toasts\nToast.makeText(MainActivity.this, \"Credit Card Number \" + creditCardText.getText() + \"\\n Phone Number \"\n+ phoneNumText.getText() + \"\\n Date \" + dateText.getText(), Toast.LENGTH_LONG).show();\n});\n}\n}Kotlin import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.Toast\nimport br.com.sapereaude.maskedEditText.MaskedEditTextclass MainActivity : AppCompatActivity() {lateinit var creditCardText: MaskedEditText\nlateinit var phoneNumText: MaskedEditText\nlateinit var dateText: MaskedEditText\nlateinit var show: Buttonoverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)creditCardText = findViewById(R.id.card)\nphoneNumText = findViewById(R.id.phone)\ndateText = findViewById(R.id.Date)\nshow = findViewById(R.id.showButton)show.setOnClickListener {\n// Display the information from the EditText with help of Toasts\nToast.makeText(this, (\"Credit Card Number \" + creditCardText.getText()) + \"\\n Phone Number \"\n+ phoneNumText.getText().toString() + \"\\n Date \" + dateText.getText(), Toast.LENGTH_LONG\n).show()\n}\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200505162724/Record_2020-05-05-16-09-23_b64b62a768fef9e79b7cc5e52be67d20.mp4"}, {"text": "\nProgressBar in Android using Jetpack Compose\n\nProgressBar is a material UI component in Android which is used to indicate the progress of any process such as for showing any downloading procedure, as a placeholder screen, and many more. In this article, we will take a look at the implementation of ProressBar in Android using Jetpack Compose.AttributesUsesmodifier\nto add padding to our progress Bar.color\nto add color to our progress Bar.strokeWidth\nthis attribute is used to give the width of the circular line of the progress Bar.progress\nto indicate the progress of your circular progress Bar.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.\nStep 2: Working with the MainActivity.kt file\nNavigate to the app > java > your app\u2019s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.Kotlin import android.graphics.drawable.shapes.Shape\nimport android.media.Image\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.compose.foundation.*\nimport androidx.compose.foundation.Text\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.shape.CircleShape\nimport androidx.compose.foundation.shape.RoundedCornerShape\nimport androidx.compose.foundation.text.KeyboardOptions\nimport androidx.compose.material.*\nimport androidx.compose.material.Icon\nimport androidx.compose.material.icons.Icons\nimport androidx.compose.material.icons.filled.AccountCircle\nimport androidx.compose.material.icons.filled.Info\nimport androidx.compose.material.icons.filled.Menu\nimport androidx.compose.material.icons.filled.Phone\nimport androidx.compose.runtime.*\nimport androidx.compose.runtime.savedinstancestate.savedInstanceState\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.layout.ContentScale\nimport androidx.compose.ui.platform.setContent\nimport androidx.compose.ui.res.imageResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport androidx.compose.ui.unit.dp\nimport com.example.gfgapp.ui.GFGAppTheme\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.draw.clip\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.graphics.SolidColor\nimport androidx.compose.ui.platform.ContextAmbient\nimport androidx.compose.ui.platform.testTag\nimport androidx.compose.ui.res.colorResource\nimport androidx.compose.ui.semantics.SemanticsProperties.ToggleableState\nimport androidx.compose.ui.text.TextStyle\nimport androidx.compose.ui.text.font.FontFamily\nimport androidx.compose.ui.text.input.*\nimport androidx.compose.ui.unit.Dp\nimport androidx.compose.ui.unit.TextUnitclass MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContent {\nColumn {\n// in below line we are calling \n// a progress bar method.\nSimpleCircularProgressComponent()\n}\n}\n}\n}@Preview(showBackground = true)\n@Composable\nfun DefaultPreview() {\nGFGAppTheme {\nSimpleCircularProgressComponent();\n}\n}@Composable\nfun SimpleCircularProgressComponent() {\n// CircularProgressIndicator is generally used\n// at the loading screen and it indicates that\n// some progress is going on so please wait.\nColumn(\n// we are using column to align our\n// imageview to center of the screen.\nmodifier = Modifier.fillMaxWidth().fillMaxHeight(),// below line is used for specifying\n// vertical arrangement.\nverticalArrangement = Arrangement.Center,// below line is used for specifying\n// horizontal arrangement.\nhorizontalAlignment = Alignment.CenterHorizontally,) {\n// below line is use to display \n// a circular progress bar.\nCircularProgressIndicator(\n// below line is use to add padding\n// to our progress bar.\nmodifier = Modifier.padding(16.dp),// below line is use to add color \n// to our progress bar.\ncolor = colorResource(id = R.color.purple_200),// below line is use to add stroke \n// width to our progress bar.\nstrokeWidth = Dp(value = 4F)\n)\n}\n}Now run your app and see the output of the app.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210118220656/Screenrecorder-2021-01-18-22-05-28-34.mp4"}, {"text": "\nDispatchers in Kotlin Coroutines\n\nPrerequisite: Kotlin Coroutines on Android\nIt is known that coroutines are always started in a specific context, and that context describes in which threads the coroutine will be started in. In general, we can start the coroutine using GlobalScope without passing any parameters to it, this is done when we are not specifying the thread in which the coroutine should be launch. This method does not give us much control over it, as our coroutine can be launched in any thread available, due to which it is not possible to predict the thread in which our coroutines have been launched.Kotlin class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // coroutine launched in GlobalScope \nGlobalScope.launch() { \nLog.i(\"Inside Global Scope \",Thread.currentThread().name.toString()) \n// getting the name of thread in \n// which our coroutine has been launched \n} Log.i(\"Main Activity \",Thread.currentThread().name.toString()) \n} \n}log output is shown below:We can see that the thread in which the coroutine is launched cannot be predicted, sometimes it is DefaultDispatcher-worker-1, or DefaultDispatcher-worker-2 or DefaultDispatcher-worker-3.\nHow Dispatchers solve the above problem?\nDispatchers help coroutines in deciding the thread on which the work has to be done. Dispatchers are passed as the arguments to the GlobalScope by mentioning which type of dispatchers we can use depending on the work that we want the coroutine to do.\nTypes of Dispatchers\nThere are majorly 4 types of Dispatchers.Main Dispatcher\nIO Dispatcher\nDefault Dispatcher\nUnconfined DispatcherMain Dispatcher:\nIt starts the coroutine in the main thread. It is mostly used when we need to perform the UI operations within the coroutine, as UI can only be changed from the main thread(also called the UI thread).Kotlin GlobalScope.launch(Dispatchers.Main) { \nLog.i(\"Inside Global Scope \",Thread.currentThread().name.toString()) \n// getting the name of thread in which \n// our coroutine has been launched \n} \nLog.i(\"Main Activity \",Thread.currentThread().name.toString())IO Dispatcher:\nIt starts the coroutine in the IO thread, it is used to perform all the data operations such as networking, reading, or writing from the database, reading, or writing to the files eg: Fetching data from the database is an IO operation, which is done on the IO thread.Kotlin GlobalScope.launch(Dispatchers.IO) { \nLog.i(\"Inside IO dispatcher \",Thread.currentThread().name.toString()) \n// getting the name of thread in which \n// our coroutine has been launched \n} \nLog.i(\"Main Activity \",Thread.currentThread().name.toString())Default Dispatcher:\nIt starts the coroutine in the Default Thread. We should choose this when we are planning to do Complex and long-running calculations, which can block the main thread and freeze the UI eg: Suppose we need to do the 10,000 calculations and we are doing all these calculations on the UI thread ie main thread, and if we wait for the result or 10,000 calculations, till that time our main thread would be blocked, and our UI will be frozen, leading to poor user experience. So in this case we need to use the Default Thread. The default dispatcher that is used when coroutines are launched in GlobalScope is represented by Dispatchers. Default and uses a shared background pool of threads, so launch(Dispatchers.Default) { \u2026 } uses the same dispatcher as GlobalScope.launch { \u2026 }.Kotlin GlobalScope.launch(Dispatchers.Default) { \nLog.i(\"Inside Default dispatcher \",Thread.currentThread().name.toString()) \n// getting the name of thread in which \n// our coroutine has been launched \n} \nLog.i(\"Main Activity \",Thread.currentThread().name.toString())Unconfined Dispatcher:\nAs the name suggests unconfined dispatcher is not confined to any specific thread. It executes the initial continuation of a coroutine in the current call-frame and lets the coroutine resume in whatever thread that is used by the corresponding suspending function, without mandating any specific threading policy."}, {"text": "\nCircular ImageView in Android using Jetpack Compose\n\nCircular ImageView is used in many of the apps. These types of images are generally used to represent the profile picture of the user and many more images. We have seen the implementation of ImageView in Android using Jetpack Compose. In this article, we will take a look at the implementation of Circle ImageView in Android using Jetpack Compose. \nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.\nStep 2: Add an Image to the drawable folder\nAfter creating a new project we have to add an image inside our drawable folder for displaying that image inside our ImageView. Copy your image from your folder\u2019s location and go inside our project. Inside our project Navigate to the app > res > drawable > Right-click on the drawable folder and paste your image there. \nStep 3: Working with the MainActivity.kt file\nAfter adding this image navigates to the app > java > MainActivity.kt and add the below code to it. Comments are added inside the code to understand the code in more detail.Kotlin import android.graphics.drawable.shapes.Shape \nimport android.media.Image \nimport android.os.Bundle \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.compose.foundation.BorderStroke \nimport androidx.compose.foundation.Image \nimport androidx.compose.foundation.InteractionState \nimport androidx.compose.foundation.Text \nimport androidx.compose.foundation.layout.* \nimport androidx.compose.foundation.shape.CircleShape \nimport androidx.compose.foundation.shape.RoundedCornerShape \nimport androidx.compose.foundation.text.KeyboardOptions \nimport androidx.compose.material.* \nimport androidx.compose.material.icons.Icons \nimport androidx.compose.material.icons.filled.AccountCircle \nimport androidx.compose.material.icons.filled.Info \nimport androidx.compose.material.icons.filled.Phone \nimport androidx.compose.runtime.* \nimport androidx.compose.runtime.savedinstancestate.savedInstanceState \nimport androidx.compose.ui.Alignment \nimport androidx.compose.ui.layout.ContentScale \nimport androidx.compose.ui.platform.setContent \nimport androidx.compose.ui.res.imageResource \nimport androidx.compose.ui.tooling.preview.Preview \nimport androidx.compose.ui.unit.dp \nimport com.example.gfgapp.ui.GFGAppTheme \nimport androidx.compose.ui.Modifier \nimport androidx.compose.ui.draw.clip \nimport androidx.compose.ui.graphics.Color \nimport androidx.compose.ui.graphics.SolidColor \nimport androidx.compose.ui.platform.ContextAmbient \nimport androidx.compose.ui.platform.testTag \nimport androidx.compose.ui.res.colorResource \nimport androidx.compose.ui.text.TextStyle \nimport androidx.compose.ui.text.font.FontFamily \nimport androidx.compose.ui.text.input.* \nimport androidx.compose.ui.unit.Dp \nimport androidx.compose.ui.unit.TextUnit class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContent { \nGFGAppTheme { \n// A surface container using the 'background' color from the theme \nSurface(color = MaterialTheme.colors.background) { \n// at below line we are calling \n// our function for button. \nCircleImg(); \n} \n} \n} \n} \n} @Preview(showBackground = true) \n@Composable\nfun DefaultPreview() { \nGFGAppTheme { \nCircleImg(); \n} \n} @Composable\nfun CircleImg() { Column( // we are using column to align our imageview \n// to center of the screen. \nmodifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying \n// vertical arrangement. \nverticalArrangement = Arrangement.Center, // below line is used for specifying \n// horizontal arrangement. \nhorizontalAlignment = Alignment.CenterHorizontally, ) { \n// creating a card for creating a circle image view. \nCard( \n// below line is use to add size to our image view and \n// test tag is use to add tag to our image. \nmodifier = Modifier.preferredSize(100.dp).testTag(tag = \"circle\"), // below line is use to \n// add shape to our image view. \nshape = CircleShape, // below line is use to add \n// elevation to our image view. \nelevation = 12.dp \n) { \n// below line we are creating a new image. \nImage( \n// in below line we are providing image \n// resource from drawable folder. \nimageResource(id = R.drawable.gfgimage), // below line is use to give scaling \n// to our image view. \ncontentScale = ContentScale.Crop, // below line is use to add modifier \n// to our image view. \nmodifier = Modifier.fillMaxSize() \n) \n} \n} \n}Now run your app and see the output of the app.\nOutput:"}, {"text": "\nImageSwitcher in Kotlin\n\nAndroid ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view.\nImageSwitcher is subclass of View Switcher which is used to animates one image and displays next one.Generally, we use ImageSwitcher in two ways manually in XML layout and programmatically in Kotlin file.\nWe should define an XML component, to use ImageSwitcher in our android application.XML \n First we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Different attributes of ImageSwitcher widgetXML attributes\nDescriptionandroid:id\nUsed to specify the id of the view.android:onClick\nUsed to specify the action when this view is clicked.android:background\nUsed to set the background of the view.android:padding\nUsed to set the padding of the view.android:visibility\nUsed to set the visibility of the view.android:inAnimation\nUsed to define the animation to use when view is shown.android:outAnimation\nUsed to define the animation to use when view is hidden.android:animateFirstView\nUsed to define whether to animate the current view when the view animation is first displayed.Modify activity_main.xml file\nIn this file, we use constraint layout with ImageSwitcher and Buttons.XML \n Update strings.xml file\nHere, we update the name of the application using the string tag.XML \nImageSwitcherInKotlin \nNext \nPrev \n Different methods of ImageSwitcher widgetMethods\nDescriptionsetImageDrawable\nIt is used to set a new drawable on the next ImageView in the switcher.setImageResource\nIt is used to set a new image on the ImageSwitcher with the given resource id.setImageURI\nIt is used to set a new image on the ImageSwitcher with the given URI.Access ImageSwitcher in MainActivity.kt file\nFirst, we declare an array flowers which contains the resource of the images used for the ImageView.\nprivate val flowers = intArrayOf(R.drawable.flower1,\n R.drawable.flower2, R.drawable.flower4)\nthen, we access the ImageSwitcher from the XML layout and set ImageView to display the image.\nval imgSwitcher = findViewById(R.id.imgSw)\nimgSwitcher?.setFactory({\n val imgView = ImageView(applicationContext)\n imgView.scaleType = ImageView.ScaleType.FIT_CENTER\n imgView.setPadding(8, 8, 8, 8)\n imgView\n })\nAlso, we will use one of the above method for ImageSwitcher.\nimgSwitcher?.setImageResource(flowers[index])Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle \nimport android.view.animation.AnimationUtils \nimport android.widget.Button \nimport android.widget.ImageSwitcher \nimport android.widget.ImageView class MainActivity : AppCompatActivity() { private val flowers = intArrayOf(R.drawable.flower1, \nR.drawable.flower2, R.drawable.flower4) \nprivate var index = 0override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // access the ImageSwitcher \nval imgSwitcher = findViewById(R.id.imgSw) imgSwitcher?.setFactory({ \nval imgView = ImageView(applicationContext) \nimgView.scaleType = ImageView.ScaleType.FIT_CENTER \nimgView.setPadding(8, 8, 8, 8) \nimgView \n}) // set the method and pass array as a parameter \nimgSwitcher?.setImageResource(flowers[index]) val imgIn = AnimationUtils.loadAnimation( \nthis, android.R.anim.slide_in_left) \nimgSwitcher?.inAnimation = imgIn val imgOut = AnimationUtils.loadAnimation( \nthis, android.R.anim.slide_out_right) \nimgSwitcher?.outAnimation = imgOut // previous button functionality \nval prev = findViewById(R.id.prev) \nprev.setOnClickListener { \nindex = if (index - 1 >= 0) index - 1 else 2\nimgSwitcher?.setImageResource(flowers[index]) \n} \n// next button functionality \nval next = findViewById(R.id.next) \nnext.setOnClickListener { \nindex = if (index + 1 < flowers.size) index +1 else 0\nimgSwitcher?.setImageResource(flowers[index]) \n} \n} \n} AndroidManifest.xml fileXML \n \n \n \n \n \n \n Run as Emulator:\nClick next button then we get the other animated image in the View."}, {"text": "\nDependency Injection with Dagger 2 in Android\n\nIf there are two classes, class A and class B and class A depends on class B then class B is called dependent for class A.So, Every time we want to access class B in class A we need to create an instance of class B in Class A or use static factory methods to access class A. But this will make our code tight coupled, difficult to manage, and test. In order to remove these problems, we use dependency injection. Dependency Injection is a design pattern that removes the dependency from the programming code and makes the application easy to manage and test. It also makes programming code loosely coupled.\nDependency Injection in Android\nLet us assume, we want to store some data in SharedPreferences. In order to save or retrieve shared preferences data, we need the instance of shared preference in our Activity\u2019s boilerplate code. And it may lead to problems in testing, managing, etc. if our codebase is large. This is where Android Dependency Injection helps. Here, SharedPreferences acts as a dependency for our Activity so, we don\u2019t create its instance in our activity rather we inject it from some other class. Below is an illustration of the situation.Dagger 2\nDagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are:@Module This annotation is used over the class which is used to construct objects and provide the dependencies.\n@Provides This is used over the method in the module class that will return the object.\n@Inject This is used over the fields, constructor, or method and indicate that dependencies are requested.\n@Component This is used over a component interface which acts as a bridge between @Module and @Inject. (Module class doesn\u2019t provide dependency directly to requesting class, it uses component interface)\n@Singleton This is used to indicate only a single instance of dependency object is created.Example\nIn this example, we will add some data to shared preferences and then retrieve it from there using the dagger 2 library. Below is the picture of what we are going to do in this example. Note that we are going to implement this project using the Java language.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Adding Dependencies\nIn order to use dependency injection with the help of dagger 2 libraries, we need to add it\u2019s dependency. Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now.dependencies {\n implementation \u201ccom.google.dagger:hilt-core:2.29-alpha\u201d\n annotationProcessor \u201ccom.google.dagger:hilt-compiler:2.29-alpha\u201d\n}Before moving further let\u2019s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML \n#0F9D58 \n#16E37F \n#03DAC5 \n Step 3: Working with the activity_main.xml file\nIn this step, we will create a layout file for the application. We have used EditText for taking the input from the user and a TextView for presenting the output and save and show buttons respectively. Below is the code snippet for the activity_main.xml file.XML \n \n \n Step 4: Creating Module Class\nNow, we will create a Module class which is used to construct the object and provide the dependencies. @Module annotations are used over the module class. This class contains a constructor that will initialize the context and a method that will return the dependent object for which @Provides annotation is used. Here, provideSharedPreferences() method will return the dependent object. In general, the method that returns the dependent object will be followed by the word provide. Go to the app > java > package > right-click and create a new java class and name it as SharedPreferenceModule. Below is the code snippet for the SharedPreferenceModule.java file.Java import android.content.Context; \nimport android.content.SharedPreferences; \nimport android.preference.PreferenceManager; \nimport javax.inject.Singleton; \nimport dagger.Module; \nimport dagger.Provides; // @Module annotation is used over the class that \n// creates construct object and provides dependencies \n@Module\npublic class SharedPreferenceModule { \nprivate Context context; // Context gets initialize from the constructor itself \npublic SharedPreferenceModule(Context context) { \nthis.context = context; \n} @Singleton\n@Provides\npublic Context provideContext() { \nreturn context; \n} // @Singleton indicates that only single instance \n// of dependency object is created \n// @Provide annotations used over the methods that \n// will provides the object of module class \n// This method will return the dependent object \n@Singleton\n@Provides\npublic SharedPreferences provideSharedPreferences(Context context) { \nreturn PreferenceManager.getDefaultSharedPreferences(context); \n} \n}Step 5: Creating a Component Interface\nIn this step, we will create an Interface. Go to the app > java > package > right-click and create an interface and name it as SharedPreferenceComponent. We use @Component annotation in order to mention all the modules.@Component(modules={SharedPreferenceModule})The Activities, Fragments, or Services that may request the dependencies declared by modules must be declared in this interface with the individual inject() method. Below is the code snippet for the SharedPreferenceComponent.java Interface.Java import javax.inject.Singleton; \nimport dagger.Component; // All the modules are mentioned under \n// the @Component annotation \n@Singleton\n@Component(modules = {SharedPreferenceModule.class}) \npublic interface SharedPreferenceComponent { \nvoid inject(MainActivity mainActivity); \n}Step 6: Working With the MainActivity.java File\nIn this step, we will first initialize our Views and then bind Dagger to our application. For which component-interface is followed by the Dagger keyword.sharedPreferenceComponent = DaggerSharedPreferenceComponent.builder().sharedPreferenceModule(new SharedPreferenceModule(this)).build();\nsharedPreferenceComponent.inject(this);Below is the code snippet for the MainActivity.java file.Note: When you will use Dagger as a prefix with Component(here, SharedPreferenceComponent) sometimes you may get an error or warning this is because DaggerSharedPreferenceComponent is generated after compilation.Java import android.content.SharedPreferences; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.EditText; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport javax.inject.Inject; public class MainActivity extends AppCompatActivity implements View.OnClickListener { EditText editText; \nTextView textView; \nButton saveBtn, getBtn; \nprivate SharedPreferenceComponent sharedPreferenceComponent; // @Inject is used to tell which activity, \n// fragment or service is allowed to request \n// dependencies declared in Module class \n@Inject\nSharedPreferences sharedPreferences; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Referencing the EditText, TextView and Buttons \neditText = (EditText) findViewById(R.id.inputField); \ntextView = (TextView) findViewById(R.id.outputField); \nsaveBtn = (Button) findViewById(R.id.saveBtn); \ngetBtn = (Button) findViewById(R.id.getBtn); // Setting onClickListener behavior on button to reference \n// to the current activity(this MainActivity) \nsaveBtn.setOnClickListener(this); \ngetBtn.setOnClickListener(this); // Here we are binding dagger to our application \n// Dagger keyword will be prefix to the component name \nsharedPreferenceComponent = DaggerSharedPreferenceComponent.builder().sharedPreferenceModule( \nnew SharedPreferenceModule(this)).build(); // we are injecting the shared preference dependent object \nsharedPreferenceComponent.inject(this); \n} @Override\npublic void onClick(View view) { \nswitch (view.getId()) { \ncase R.id.saveBtn: \n// Saving data to shared preference \n// inputField acts as key and editText data as value to that key \nSharedPreferences.Editor editor = sharedPreferences.edit(); \neditor.putString(\"inputField\", editText.getText().toString().trim()); \neditor.apply(); \nbreak; \ncase R.id.getBtn: \n// getting shared preferences data and set it to textview \n// s1: is the default string, You can write any thing there or leave it \ntextView.setText(sharedPreferences.getString(\"inputField\", \"\")); \nbreak; \n} \n} \n}Output: Run On Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201122224243/Dependency-Injection-with-Dagger-2-in-Android.mp4"}, {"text": "\nHow to Publish Your Android App on Google Play Store?\n\nNowadays smartphones are among the most essential gadgets for users. Over 60% of people sleep with their phones by their side and check it first thing in the morning. Almost all businesses, including retail stores, have mobile apps to keep their audience engaged. Various applications like games, music player, camera, etc. are built for these smartphones for running on Android. Google Play store features quite 3.3 million apps.Building a dream app that reflects your idea, but, what next? Building a mobile app simply means you\u2019re half done. But one must concern about the launch of the application. It\u2019s very confusing because as a beginner, they are not friendly with the google play store guidelines. So let\u2019s understand step by step process to publish your android app on google play store.Note that the sections which are marked with * are mandatory and other than that all are optional things. So make sure you have provided all the things in the section marked with *.Step 1: Make a Developer Account\nA developer account is must be needed to upload an app on the Google Play Store, and the process is very simple. Just go through Google Play Store and do as instructed.The account can be created in four simple steps:Sign-In with Your Google Account\nAccept Terms\nPay Registration Fee of $25.\nComplete Your Account DetailsStep 2: After you completed step 1 you will be redirected to this page where you have to click on the CREATE APPLICATION button.Once you click on it a pop up will be shown like this where you have to choose your Default language and Title of your app. Then click on the CREATE button.Step 3: Store listing\nAfter you completed step 2 you will be redirected to this page where you have to provide the Short description and Full description of your App.Then you scroll down the page and now you have to add the Hi-res icon of your app.Then you have to provide the Screenshots of your app.Ant next thing you have to provide is the Feature Graphic of your app. Note that this graphic is then used everywhere your app is featured on Google Play.Then come to Categorization part where you have to provide your Application type and Category of your app.Then come to Contact details part where you have to provide your Website(if any), email, and Phone of yours.And finally when you click on SAVE DRAFT button you can see that Store listing tab is now become turned to green and you are done for Store listing.Step 4: App release\nAfter completing step 3 go to App releases then scroll down to Production track and click on MANAGE button.After redirecting to the next page click on the CREATE RELEASE button.After that on the next page, you have to upload your APK file in Android App Bundles and APKs to add section.After that simply click on the SAVE button.Step 5: Content rating\nNow after completing step 4 go to Content rating and click on CONTINUE button.After that fill your email address as well as confirm the email address.And then Select your app category.After selecting your app category make sure that you read all of these and answer them correctly.And after answering them correctly don\u2019t forget to click on SAVE QUESTIONNAIRE button.Once you saved all those things then click on CALCULATE RATING button.When you redirected to another page scroll down and click on APPLY RATING button. And you are done for Content rating section. Don\u2019t forget to notice that Content rating section is now become turned to green.Step 6: Pricing & distribution\nThen go to the Pricing & distribution section. Then select the country in which you want to available your app.Then go down and down and check out the Content guidelines and US export laws section by marking them tick mark. And click on the SAVE DRAFT button. Don\u2019t forget to notice that Pricing & distribution section is now become turned to green tick.Step 7: App content\nThen come to the App content section. And in the Privacy policy section click on the Start button.And then provide a valid Privacy policy URL. Note that google will check this.Then go back and continue further steps by clicking start button in Ads section.Then select does your app contain ads or not? And click on SAVE button.Then again go back and continue further steps by clicking start button in Target audience and content section.In the next page select the Target age group and scroll down and click on the Next button.Then check the Appeal to children section. And click on the Next button.On the next page click on the Save button and you are done for App content section.Step 8: App releases\nAgain go back to the App releases section. And in the Production track click on the EDIT RELEASE button.Then on the next page go down and down and click on the REVIEW button.And finally, on the next page click on the START ROLLOUT TO PRODUCTION button to send your app to review. And you are finally done.After usually 4 to 5 days they will review your app and let you know to either approve or reject your app."}, {"text": "\nAndroid Listview in Java with Example\n\nA ListView is a type of AdapterView that displays a vertical list of scroll-able views and each view is placed one below the other. Using adapter, items are inserted into the list from an array or database. For displaying the items in the list method setAdaptor() is used. setAdaptor() method conjoins an adapter with the list.\nAndroid ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list.\nThe main purpose of the adapter is to fetch data from an array or database and insert each item that placed into the list for the desired result. So, it is the main source to pull data from strings.xml file which contains all the required strings in Java or XML files.\nXML Attributes of ListViewAttributeDescriptionandroid:divider\nA color or drawable to separate list items.android:dividerHeight\nDivider\u2019s height.android:entries\nReference to an array resource that will populate the ListView.android:footerDividersEnabled\nWhen set to false, the ListView will not draw the divider before each footer view.android:headerDividersEnabled\nWhen set to false, the ListView will not draw the divider before each header view.How to add a ListView in an Android App\nNow let\u2019s understand how to use a listview in an android application with an example. In the example, let\u2019s create an android application that will display a list of tutorials available in GeeksforGeeks portal.\nStep 1: Create a new projectClick on File, then New => New Project.\nChoose \u201cEmpty Activity\u201d for the project template.\nSelect language as Java.\nSelect the minimum SDK as per your need.Step 2: Modify activity_main.xml file\nAdd a ListView in the activity_main.xml file.activity_main.xml \n \n Step 3: Modify MainActivity.java file\nIn this section, let\u2019s design the backend of the application. Go to MainActivity.java. Now in the java file create a string array and store the values you want to display in the list. Also, create an object of ListView class. In onCreate() method find Listview by id using findViewById() method. Create an object of ArrayAdapter using a new keyword followed by a constructor call. The ArrayAdaptor public constructor description is below:\npublic ArrayAdapter (Context context, int Resource, T[ ] objects)ParameterDescriptioncontext\ncurrent contextResource\nthe resource ID for a layout fileobjects\nobjects to display in the ListViewAccording to this pass the argument in ArrayAdapter Constructor and create an object. At last, conjoin the adapter with the list using setAdapter() method.MainActivity.java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.widget.AdapterView; \nimport android.widget.ArrayAdapter; \nimport android.widget.ListView; public class MainActivity extends AppCompatActivity { ListView l; \nString tutorials[] \n= { \"Algorithms\", \"Data Structures\", \n\"Languages\", \"Interview Corner\", \n\"GATE\", \"ISRO CS\", \n\"UGC NET CS\", \"CS Subjects\", \n\"Web Technologies\" }; @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \nl = findViewById(R.id.list); \nArrayAdapter arr; \narr \n= new ArrayAdapter( \nthis, \nR.layout.support_simple_spinner_dropdown_item, \ntutorials); \nl.setAdapter(arr); \n} \n} Output"}, {"text": "\nHow to Check if the Android Device is in Dock State?\n\nA docking station is a device that is competent in communicating with the Android kernel to fire docking-related events and revise the docking file state. A docking station can make the system and apps do anything that is programmed. One example is showing a different layout on the docked state. It may also open a music player app, play music automatically on desk mode if it is programmed as such, open a map/navigation app in car mode, etc. Dock Mode is different on different phones, but it often turns your phone into a desk clock, photo slideshow viewer, or music player. You can also set it as a speakerphone when you receive calls. The dock is built into self-amplified speakers or music boxes, or it is a stand-alone unit that connects via USB to a computer, charger, or home theater equipment. Some docks use USB for charging and Bluetooth for playing music. This mode is a feature that can be detected on some phones, including many of the Samsung phones, but is not a feature detect on every phone or every version of a phone. For example, Samsung Galaxy S2, S3, and S4 have a dock mode, but the S5 does not. Please check your phone features to make sure your phone is equipped with dock mode. So in this article let\u2019s discuss how to check if the Android device is in dock state or not or anything else. Note that we are going toimplement this project using theKotlinlanguage.\nSteps to Check if the Android Device is in Dock State\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.\nStep 2: Working with the activity_main.xml file\nGo to the activity_main.xml file, which represents the UI of the application. Create a Button, which on click provides the docking state of the device. Below is the code for theactivity_main.xml file.XML \n \n Step 3: Working with the MainActivity.kt file\nBelow is the code for theMainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.content.Intent \nimport android.content.Intent.EXTRA_DOCK_STATE \nimport android.content.IntentFilter \nimport android.os.Bundle \nimport android.widget.Button \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Button which onclick gives dock info in the form of a Toast \nval btn = findViewById(R.id.btnCheck) \nbtn.setOnClickListener { // The dock-state details are included as an extra in a sticky broadcast of \n// the ACTION_DOCK_EVENT action. Because it's sticky, you can simply call \n// registerReceiver(), passing in null as the broadcast receiver. \nval dockStatus: Intent? = IntentFilter(Intent.ACTION_DOCK_EVENT) \n.let { ifilter -> \napplicationContext.registerReceiver(null, ifilter) \n} // dockState is an Integer value received when intent is passed \nval dockState: Int = dockStatus?.getIntExtra(EXTRA_DOCK_STATE, -1) ?: -1// isDocked is a Boolean value which if true indicates the device is in dock \n// state and vice-versa \nval isDocked: Boolean = dockState != Intent.EXTRA_DOCK_STATE_UNDOCKED // Finally depending upon the isDocked value display the Toasts \nif (isDocked) { \nToast.makeText(applicationContext, \"Docked\", Toast.LENGTH_SHORT).show() \n} else { \nToast.makeText(applicationContext, \"Not Docked\", Toast.LENGTH_SHORT).show() \n} \n} \n} \n}Output\nDepending upon the state, the application shows Toast messages, \u201cDocked\u201d when the device is docked, or \u201cNot Docked\u201d otherwise. The output is not available but this is the standard version of extracting the dock state in Android. Note that Android devices can be docked into several kinds of docks. These include car or home docks and digital versus analog docks. The dock-state is typically closely linked to the charging state as many docks provide power to docked devices."}, {"text": "\nHow to Use COIL Image Loader Library in Android Apps?\n\nCOIL is an acronym for Coroutine Image Loader. COIL is one of the famous image loading libraries from URLs in Android. It is a modern library for loading images from the server. This library is used to load images from servers, assets folder as well as from the drawable folder in Android project. The important feature of this library is that it is fast, lightweight, and easy to use. In this article, we will see How to Use this Image Loader Library in Android Apps.\nWhy We Should use COIL for Loading Images?\nCOIL Image loading library is provided by Kotlin Coroutines which is used for loading images in Android. This library is specially designed for loading images in Kotlin. It is modern, easy to use, lightweight, and fast for loading images from the server. This is the new library and provides new optimization for loading images from the server very efficiently. As Kotlin is now been officially announced as the preferred language for Android development, that\u2019s why for loading images we should prefer using COIL for loading images in Android.\nWhat are the Advantages of using COIL over Picasso, Glide, and UIL?Google has officially announced Kotlin as a preferred language for Android development and COIL is the library that is better optimized with Kotlin. So the optimization of this library with Kotlin makes it easier to load images from the server.\nCOIL loads images very faster with the number of optimizations which includes memory, disk caching, reusing of bitmaps, and down spacing the image in memory which makes it faster in comparison with other image loading libraries.\nCOIL adds ~2000 methods to your APK which are very less in number in comparison with Picasso, Glide, and UIL. This makes this library very lightweight and easy to use.\nCOIL is the first image loading library which is completely introduced in Kotlin and it uses some modern libraries of Android such as Okio, OkHttp, and AndroidX lifecycles.Step by Step Implementation of COIL Image Loading Library\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.\nStep 2: Add dependency of Coil Image Loading library in build.gradle file\nNavigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.implementation(\u201cio.coil-kt:coil:1.1.0\u201d)After adding dependency click on the \u201csync now\u201d option on the top right corner to sync the project.\nStep 3: Adding internet permission in the AndroidManifest.xml file\nNavigate to the app > Manifest to open the Manifest file. In the manifest file, we are adding internet permission to load images from the internet. Add the following lines in your manifest file.\n \n Step 4: Create a new ImageView in your activity_main.xml.\nNavigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file.XML \n \n Step 5: Working with the MainActivity.kt file\nGo to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.widget.ImageView \nimport coil.load class MainActivity : AppCompatActivity() { // image url that we will load in our image view. \nval imgurl = \"https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200-1.png\"override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // val created for our imageview and \n// initializing it with image id. \nval img = findViewById(R.id.imageView) // below line is for loading \n// image url inside imageview. \nimg.load(imgurl) { \n// placeholder image is the image used \n// when our image url fails to load. \nplaceholder(R.drawable.ic_launcher_background) \n} \n} \n}Output:"}, {"text": "\nBottom Navigation Bar in Android\n\nWe all have come across apps that have a Bottom Navigation Bar. Some popular examples include Instagram, WhatsApp, etc. In this article, let\u2019s learn how to implement such a functional Bottom Navigation Bar in the Android app. Below is the preview of a sample Bottom Navigation Bar:Why do we need a Bottom Navigation Bar?It allows the user to switch to different activities/fragments easily.\nIt makes the user aware of the different screens available in the app.\nThe user is able to check which screen are they on at the moment.The following is an anatomy diagram for the Bottom Navigation Bar:Steps for Creating Bottom Navigation Bar\nStep 1: Create a new Android Studio project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.\nStep 2: Adding the dependency to the build.gradle(:app) file\nWe will be using Android\u2019s Material Design Library so we need to import it in the build.gradle(:app) file. Here\u2019s the dependency we need to add:implementation \u2018com.google.android.material:material:1.2.0\u2019Step 3: Working with activity_main.xml file\nFor this example, create a basic app with a FrameLayout and a Bottom Navigation Bar. The FrameLayout will contain Fragments which will change as the user click on the items in the Bottom Navigation Bar. This is how the activity_main.xml looks like:XML \n Step 4: Creating a menu for the Bottom Navigation Bar\nThe Navigation Bar needs to have some items which will create using Menu. To create a Menu, first, create a Menu Directory by clicking on the app -> res(right-click) -> New -> Android Resource Directory and select Menu in the Resource Type.To create a Menu Resource File , click on the app -> res -> menu(right-click) -> New -> Menu Resource File and name it bottom_nav_menu.Now the user can create as many items as he wants in the bottom_nav_menu.xml file. The user also needs to create an icon for each of these items. To create an icon, click on the app -> res -> drawable(right-click) -> New -> Image Asset.In the window that opens, the user can name the icon whatever he wants but it should not comprise any uppercase letter. The user can select the icon he wants by searching it and when the user is done, click Next-> Finish.Now add these items in the bottom_nav_menu.xml. This is how the bottom_nav_menu.xml file looks like after adding the items:XML \n\n \n \n \n Step 5: Changing the Action Bar style\nSince we are using Google\u2019s Material Design Library, we need to change the action bar\u2019s style to use the same library otherwise the Bottom Navigation Bar will be black and its items will be invisible. To change it, navigate to styles.xml by clicking on the app -> res -> values -> styles.xml and change the style opening tag as:Step 6: Creating Fragments to display\nNow that we have our Bottom Navigation Bar, we would want it to be functional by taking us to a different fragment/activity when an item is clicked. In this example, create a fragment for each item and navigate to them whenever a corresponding item is clicked. Since we created three items in the Bottom Navigation Bar, we will be creating three Fragments. To create a Fragment, click on the app(right-click) -> New -> Fragment -> Fragment (Blank). Name the fragment as FirstFragment and the corresponding XML file as fragment_first. To keep things simple, all three of the fragments will just contain a TextView. However, we can tweak this as we want it to be in the app. This is how the fragment_first.xml looks like after adding a TextView:XML \n Next, code the FirstFragment to display the fragment_first.xml. For this, delete all the previously written code in FirstFragment and replace it with the below code. The below code just takes the layout we created for our fragment and inflates it.Note: If we want our fragment to have any logic or perform any task, we will add that code in our FirstFragment.Kotlin import androidx.fragment.app.Fragmentclass FirstFragment:Fragment(R.layout.fragment_first) {\n}Java import java.io.*;\nimport androidx.fragment.app.Fragmentpublic class FirstFragment extends Fragment {public FirstFragment(){\n// require a empty public constructor\n}@Override\npublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n// Inflate the layout for this fragment\nreturn inflater.inflate(R.layout.fragment_first, container, false);\n}\n}Similarly, create two more fragments for the remaining two items.\nBelow are the fragment_second.xml, SecondFragment, fragment_third.xml, and ThirdFragment files respectively.XML \n Kotlin import androidx.fragment.app.Fragmentclass SecondFragment:Fragment(R.layout.fragment_second) {\n}Java import androidx.fragment.app.Fragment;\nimport java.io.*;public class SecondFragment extends Fragment {public SecondFragment(){\n// require a empty public constructor\n}@Override\npublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_second, container, false);\n}\n}XML \n Kotlin import androidx.fragment.app.Fragmentclass ThirdFragment:Fragment(R.layout.fragment_third) {\n}Java import androidx.fragment.app.Fragment;\nimport java.io.*;public class ThirdFragment extends Fragment {public ThirdFragment(){\n// require a empty public constructor\n}@Override\npublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_third, container, false);\n}\n}Step 7: Working with the MainActivity file\nNow we have everything that we need and lastly, we just need to code the MainActivity to connect everything to the application. Here, first, create a function called setCurrentFragment() that takes a Fragment as an argument and sets it in our FrameLayout of activity_main.xml file. Add a click listener to the items of the Bottom Navigation Bar so that we display the corresponding Fragment when an item is clicked. After adding all these codes, the MainActivity looks like this:Kotlin import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport androidx.fragment.app.Fragment\nimport kotlinx.android.synthetic.main.activity_main.*class MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)val firstFragment=FirstFragment()\nval secondFragment=SecondFragment()\nval thirdFragment=ThirdFragment()setCurrentFragment(firstFragment)bottomNavigationView.setOnNavigationItemSelectedListener {\nwhen(it.itemId){\nR.id.home->setCurrentFragment(firstFragment)\nR.id.person->setCurrentFragment(secondFragment)\nR.id.settings->setCurrentFragment(thirdFragment)}\ntrue\n}}private fun setCurrentFragment(fragment:Fragment)=\nsupportFragmentManager.beginTransaction().apply {\nreplace(R.id.flFragment,fragment)\ncommit()\n}}Java import android.os.Bundle;\nimport android.view.MenuItem;\nimport androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport com.example.Fragment.*;\nimport com.google.android.material.bottomnavigation.BottomNavigationView;\nimport java.io.*;public class MainActivity extends AppCompatActivity\nimplements BottomNavigationView\n.OnNavigationItemSelectedListener {BottomNavigationView bottomNavigationView;@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);bottomNavigationView\n= findViewById(R.id.bottomNavigationView);bottomNavigationView\n.setOnNavigationItemSelectedListener(this);\nbottomNavigationView.setSelectedItemId(R.id.person);\n}\nFirstFragment firstFragment = new FirstFragment();\nSecondFragment secondFragment = new SecondFragment();\nThirdFragment thirdFragment = new ThirdFragment();@Override\npublic boolean\nonNavigationItemSelected(@NonNull MenuItem item)\n{switch (item.getItemId()) {\ncase R.id.person:\ngetSupportFragmentManager()\n.beginTransaction()\n.replace(R.id.flFragment, firstFragment)\n.commit();\nreturn true;case R.id.home:\ngetSupportFragmentManager()\n.beginTransaction()\n.replace(R.id.flFragment, secondFragment)\n.commit();\nreturn true;case R.id.settings:\ngetSupportFragmentManager()\n.beginTransaction()\n.replace(R.id.flFragment, thirdFragment)\n.commit();\nreturn true;\n}\nreturn false;\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200904124438/Android-Emulator---Pixel_2_API_29_5554-2020-09-04-12-41-54_Trim.mp4"}, {"text": "\nWhat is Context in Android?\n\nAndroid Applications are popular for a long time and it is evolving to a greater level as users\u2019 expectations are that they need to view the data that they want in an easier smoother view. Hence, the android developers must know the important terminologies before developing the app. In Android Programming we generally come across the word Context. So what exactly is this Context and why is it so important? To answer this question let\u2019s first see what the literal meaning of Context is:The Circumstances that form the setting for an Event, Statement, or Idea, and in terms of which it can be fully understood.Looking at this definition we come across two things:The Context tells us about the surrounding information.\nIt is very important to understand the environment which we want to understand.Similarly when we talk about Android Programming Context can be understood as something which gives us the Context of the current state of our application. We can break the Context and its use into three major points:It allows us to access resources.\nIt allows us to interact with other Android components by sending messages.\nIt gives you information about your app environment.The code has been given in both Java and Kotlin Programming Language for Android.\nUnderstanding Context by a Real World Example\nLet\u2019s a person visit a hotel. He needs breakfast, lunch, and dinner at a suitable time. Except for these things there are also many other things, he wants to do during his time of stay. So how does he get these things? He will ask the room-service person to bring these things for him. Right? So here the room-service person is the Context considering you are the single activity and the hotel to be your app, finally, the breakfast, lunch & dinner have to be the resources.\nHow Does this Work?\n1. It is the Context of the current/active state of the application.\nUsually, the app got multiple screens like display/inquiry/add/delete screens(A general requirement of a basic app). So when the user is searching for something, the Context is an inquiry screen in this case.\n2. It is used to get information about the activity and application.\nThe inquiry screen\u2019s Context specifies that the user is in inquiry activity, and he/she can submit queries related to the app\n3. It is used to get access to resources, databases, shared preferences, etc.\nVia Rest services, API calls can be consumed in android apps. Rest Services usually hold database data and provide the output in JSON format to the android app. The Context for the respective screen helps to get hold of database data and the shared data across screens\n4. Both the Activity and Application classes extend the Context class.\nIn android, Context is the main important concept and the wrong usage of it leads to memory leakage. Activity refers to an individual screen and Application refers to the whole app and both extend the Context class.\nTypes of Context in Android\nThere are mainly two types of Context that are available in Android.Application Context and\nActivity ContextThe Overall view of the App hierarchy looks like the following:It can be seen in the above image that in \u201cSample Application\u201d, the nearest Context is Application Context. In \u201cActivity1\u201d and \u201cActivity2\u201d, both Activity Context (Here it is Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application Context.The nearest Context to both is their Activity Context only.\nApplication Context\nThis Context is tied to the Lifecycle of an Application. Mainly it is an instance that is a singleton and can be accessed via getApplicationContext(). Some use cases of Application Context are:If it is necessary to create a singleton object\nDuring the necessity of a library in an activitygetApplicationContext():\nIt is used to return the Context which is linked to the Application which holds all activities running inside it. When we call a method or a constructor, we often have to pass a Context and often we use \u201cthis\u201d to pass the activity Context or \u201cgetApplicationContext\u201d to pass the application Context. This method is generally used for the application level and can be used to refer to all the activities. For example, if we want to access a variable throughout the android app, one has to use it via getApplicationContext().\nExample:Java import android.app.Application; public class GlobalExampleClass extends Application { \nprivate String globalName; \nprivate String globalEmail; public String getName() { \nreturn globalName; \n} public void setName(String aName) { \nglobalName = aName; \n} public String getEmail() { \nreturn globalEmail; \n} public void setEmail(String aEmail) { \nglobalEmail = aEmail; \n} \n}Kotlin import android.app.Application class GlobalExampleClass : Application() { \nprivate var globalName: String? = null\nprivate var globalEmail: String? = nullfun getName(): String? { \nreturn globalName \n} fun setName(aName: String?) { \nglobalName = aName \n} fun getEmail(): String? { \nreturn globalEmail \n} fun setEmail(aEmail: String?) { \nglobalEmail = aEmail \n} \n}Inside the activity class, set the name and email of GlobalExampleClass, which can be accessed from another activity. Let us see via the below steps.\nSyntax:\n// Activity 1\npublic class extends Activity {\n ........\n ........\n private globarVar;\n ........\n @Override\n public void onCreate(Bundle savedInstanceState) {\n .......\n final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext();\n \n // In this activity set name and email and can reuse in other activities\n globalExampleVariable.setName(\"getApplicationContext example\");\n globalExampleVariable.setEmail(\"xxxxxx@gmail.com\");\n \n .......\n}\n \n// Activity 2 \npublic class extends Activity {\n ........\n ........\n private globarVar;\n .......\n @Override\n public void onCreate(Bundle savedInstanceState) {\n .......\n final GlobalExampleClass globalExampleVariable = (GlobalExampleClass) getApplicationContext();\n \n // As in activity1, name and email is set, we can retrieve it here\n final String globalName = globalExampleVariable.getName();\n final String globalEmail = globalExampleVariable.getEmail();\n \n .......\n}\nSo, whenever the variable scope is required throughout the application, we can get it by means of getApplicationContext(). Following is a list of functionalities of Application Context.\nList of functionalities of Application Context:Load Resource Values\nStart a Service\nBind to a Service\nSend a Broadcast\nRegister BroadcastReceiverActivity Context\nIt is the activity Context meaning each and every screen got an activity. For example, EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity only. It is tied to the life cycle of activity. It is used for the current Context. The method of invoking the Activity Context is getContext().\nSome use cases of Activity Context are:The user is creating an object whose lifecycle is attached to an activity.\nWhenever inside an activity for UI related kind of operations like toast, dialogue, etc.,getContext():\nIt returns the Context which is linked to the Activity from which it is called. This is useful when we want to call the Context from only the current running activity.\nExample:Java @Override\npublic void onItemClick(AdapterView> parent, View view, int pos, long id) { \n// view.getContext() refers to the current activity view \n// Here it is used to start the activity \nIntent intent = new Intent(view.getContext(), ::class.java); \nintent.putExtra(pid, ID); \nview.getContext().startActivity(intent); \n}Kotlin fun onItemClick(parent: AdapterView<*>?, view: View, pos: Int, id: Long) { \n// view.getContext() refers to the current activity view \n// Here it is used to start the activity \nval intent = Intent(view.context, ::class.java) \nintent.putExtra(pid, ID) \nview.context.startActivity(intent) \n}List of Functionalities of Activity Context:Load Resource Values\nLayout Inflation\nStart an Activity\nShow a Dialog\nStart a Service\nBind to a Service\nSend a Broadcast\nRegister BroadcastReceiverFrom the functionalities of both Application and Activity, we can see that the difference is that the Application Context is not related to UI. It should be used only to start a service or load resource values etc. Apart from getApplicationContext() and getContext(), getBaseContext() or this are the different terminologies used throughout the app development. Let us see with an example\ngetBaseContext():\nThe base Context is set by the constructor or setBaseContext().This method is only valid if we have a ContextWrapper. Android provides a ContextWrapper class that is created around an existing Context using:\nContextWrapper wrapper = new ContextWrapper(context);\nThe benefit of using a ContextWrapper is that it lets you \u201cmodify behavior without changing the original Context\u201d.\nSyntax:\npublic (Context ctx) {\n // if the context is instanceof ContextWrapper\n while (ctx instanceof ContextWrapper) {\n // use getBaseContext()\n final Context baseContext = ((ContextWrapper)context).getBaseContext();\n if (baseContext == null) {\n break;\n }\n // And then we can assign to context and reuse that\n ctx = baseContext;\n }\n}\nthis:\n\u201cthis\u201d argument is of a type \u201cContext\u201d. To explain this Context let\u2019s take an example to show a Toast Message using \u201cthis\u201d.\nExample:Java import android.os.Bundle; \nimport android.widget.Toast; \nimport androidx.appcompat.app.AppCompatActivity; // Show a simple toast message, that can be done after doing some activities \n// Toast.makeText(this, \"Action got completed\", Toast.LENGTH_SHORT).show(); public class ExampleActivity extends AppCompatActivity { \n@Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main_example); // Displaying Toast with Hello Javatpoint message \nToast.makeText(this,\"Action done\",Toast.LENGTH_SHORT).show(); \n} \n}Kotlin import android.os.Bundle \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity // Show a simple toast message, that can be done after doing some activities \n// Toast.makeText(this, \"Action got completed\", Toast.LENGTH_SHORT).show(); class ExampleActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main_example) // Displaying Toast with Hello Javatpoint message \nToast.makeText(this, \"Action done\", Toast.LENGTH_SHORT).show() \n} \n}Another example to start the activity using \u201cthis\u201d:Java import androidx.appcompat.app.AppCompatActivity; \nimport android.content.Intent; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.EditText; public class FirstActivity extends AppCompatActivity { public static final String newMessage = \"Your message to go for next screen\"; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_first); \n} // There must be some button and on click of \n// that below method can be invoked \npublic void sendMessageToNextScreen(View view) { \n// Here it is used with \"this\" \nIntent intent = new Intent(this, SecondActivity.class); \nEditText editText = (EditText) findViewById(R.id.editText); \nString message = editText.getText().toString(); \nintent.putExtra(newMessage, message); // Start the SecondActivity \nstartActivity(intent); \n} \n}Kotlin import android.content.Intent \nimport android.os.Bundle \nimport android.view.View \nimport android.widget.EditText \nimport androidx.appcompat.app.AppCompatActivity class FirstActivity : AppCompatActivity() { private var newMessage = \"Your message to go for next screen\"override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_first) \n} // There must be some button and on click of \n// that below method can be invoked \nfun sendMessageToNextScreen(view: View?) { \n// Here it is used with \"this\" \nval intent = Intent(this, SecondActivity::class.java) \nval editText: EditText = findViewById(R.id.editText) \nval message = editText.text.toString() \nintent.putExtra(newMessage, message) // Start the SecondActivity \nstartActivity(intent) \n} \n}"}, {"text": "\nHow to build a simple Calculator app using Android Studio?\n\nPre-requisites:Android App Development Fundamentals for Beginners\nGuide to Install and Set up Android Studio\nAndroid | Starting with first app/android project\nAndroid | Running your first Android appCreate a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication, or division depending upon the user input. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210629133649/build-a-simple-Calculator-app-using-Android-Studio.mp4\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n\n \n \n \n \n \n After using this code the UI will be like as follows:Step 3: Working with the MainActivity.java file\nOpen the MainActivity.java file there within the class, and make a method named doSum(View v).In this method, first of all, we have to link two EditText with variables so that we can use them for our input.So link those edit box with variables we have written\n\"EditText e1=(EditText )findViewById(R.id.num1);\"\nHere num1 is id for the textbox and we are just giving a variable name \u2018e1\u2019 to text box with id \u2018num1\u2019.Similarly, we have to use the same statement for the second textbox with the variable name \u2018e2\u2019.For the third text box, we have used\n\"TextView t1=(TextView) findViewById(R.id.result);\"\nHere we have used TextView because we only have to display text avoiding it being user-changeable.Now we have to input numbers in form of string using the getText() function.The input statement will be\n\"String s11=e1.getText().toString();\"\nHere s11 stores the number entered in textbox 1. We have to do the same with another Textbox(e2). Now store the number in int form and apply addition. store the added value in another variable. To display stored in sum we have to use setText() as follows:\nresult.setText(final_sum.toString())\nfinal_sum stores the sum and it\u2019s necessary to convert it to string(.toString()). Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.\nFile: MainActivity.javaJava package com.example.calculator2;import android.os.Bundle;import com.google.android.material.snackbar.Snackbar;import androidx.appcompat.app.AppCompatActivity;import android.text.TextUtils;\nimport android.view.View;import androidx.navigation.NavController;\nimport androidx.navigation.Navigation;\nimport androidx.navigation.ui.AppBarConfiguration;\nimport androidx.navigation.ui.NavigationUI;import com.example.calculator2.databinding.ActivityMainBinding;import android.view.Menu;\nimport android.view.MenuItem;import android.os.Bundle;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private AppBarConfiguration appBarConfiguration;\nprivate ActivityMainBinding binding;\npublic EditText e1, e2;\nTextView t1;\nint num1, num2;public boolean getNumbers() {//checkAndClear();\n// defining the edit text 1 to e1\ne1 = (EditText) findViewById(R.id.num1);// defining the edit text 2 to e2\ne2 = (EditText) findViewById(R.id.num2);// defining the text view to t1\nt1 = (TextView) findViewById(R.id.result);// taking input from text box 1\nString s1 = e1.getText().toString();// taking input from text box 2\nString s2 = e2.getText().toString();if(s1.equals(\"Please enter value 1\") && s2.equals(null))\n{\nString result = \"Please enter value 2\";\ne2.setText(result);\nreturn false;\n}\nif(s1.equals(null) && s2.equals(\"Please enter value 2\"))\n{\nString result = \"Please enter value 1\";\ne1.setText(result);\nreturn false;\n}\nif(s1.equals(\"Please enter value 1\") || s2.equals(\"Please enter value 2\"))\n{\nreturn false;\n}if((!s1.equals(null) && s2.equals(null))|| (!s1.equals(\"\") && s2.equals(\"\")) ){String result = \"Please enter value 2\";e2.setText(result);\nreturn false;\n}\nif((s1.equals(null) && !s2.equals(null))|| (s1.equals(\"\") && !s2.equals(\"\")) ){\n//checkAndClear();\nString result = \"Please enter value 1\";\ne1.setText(result);\nreturn false;\n}\nif((s1.equals(null) && s2.equals(null))|| (s1.equals(\"\") && s2.equals(\"\")) ){\n//checkAndClear();\nString result1 = \"Please enter value 1\";\ne1.setText(result1);\nString result2 = \"Please enter value 2\";\ne2.setText(result2);\nreturn false;\n}else {\n// converting string to int.\nnum1 = Integer.parseInt(s1);// converting string to int.\nnum2 = Integer.parseInt(s2);}return true;\n}public void doSum(View v) {// get the input numbers\nif (getNumbers()) {\nint sum = num1 + num2;\nt1.setText(Integer.toString(sum));\n}\nelse\n{\nt1.setText(\"Error Please enter Required Values\");\n}}\npublic void clearTextNum1(View v) {// get the input numbers\ne1.getText().clear();\n}\npublic void clearTextNum2(View v) {// get the input numbers\ne2.getText().clear();\n}\npublic void doPow(View v) {//checkAndClear();\n// get the input numbers\nif (getNumbers()) {\ndouble sum = Math.pow(num1, num2);\nt1.setText(Double.toString(sum));\n}\nelse\n{\nt1.setText(\"Error Please enter Required Values\");\n}\n}// a public method to perform subtraction\npublic void doSub(View v) {\n//checkAndClear();\n// get the input numbers\nif (getNumbers()) {\nint sum = num1 - num2;\nt1.setText(Integer.toString(sum));\n}\nelse\n{\nt1.setText(\"Error Please enter Required Values\");\n}\n}// a public method to perform multiplication\npublic void doMul(View v) {\n//checkAndClear();\n// get the input numbers\nif (getNumbers()) {\nint sum = num1 * num2;\nt1.setText(Integer.toString(sum));\n}\nelse\n{\nt1.setText(\"Error Please enter Required Values\");\n}\n}// a public method to perform Division\npublic void doDiv(View v) {\n//checkAndClear();\n// get the input numbers\nif (getNumbers()) {// displaying the text in text view assigned as t1\ndouble sum = num1 / (num2 * 1.0);\nt1.setText(Double.toString(sum));\n}\nelse\n{\nt1.setText(\"Error Please enter Required Values\");\n}\n}// a public method to perform modulus function\npublic void doMod(View v) {\n//checkAndClear();\n// get the input numbers\nif (getNumbers()) {\ndouble sum = num1 % num2;\nt1.setText(Double.toString(sum));\n}\nelse\n{\nt1.setText(\"Error Please enter Required Values\");\n}\n}@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);\ne1 = (EditText) findViewById(R.id.num1);\n// defining the edit text 2 to e2\ne2 = (EditText) findViewById(R.id.num2);\n}@Override\npublic boolean onCreateOptionsMenu(Menu menu) {\n// Inflate the menu; this adds items to the action bar if it is present.\ngetMenuInflater().inflate(R.menu.menu_main, menu);\nreturn true;\n}@Override\npublic boolean onOptionsItemSelected(MenuItem item) {\n// Handle action bar item clicks here. The action bar will\n// automatically handle clicks on the Home/Up button, so long\n// as you specify a parent activity in AndroidManifest.xml.\nint id = item.getItemId();//noinspection SimplifiableIfStatement\nif (id == R.id.action_settings) {\nreturn true;\n}return super.onOptionsItemSelected(item);\n}@Override\npublic boolean onSupportNavigateUp() {\nNavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);\nreturn NavigationUI.navigateUp(navController, appBarConfiguration)\n|| super.onSupportNavigateUp();\n}\n}Output:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210629133649/build-a-simple-Calculator-app-using-Android-Studio.mp4"}, {"text": "\nEditText in Android using Jetpack Compose\n\nEditText is one of the most important widget which is seen in most of the apps. This widget is generally use to get the data from users. Users can directly communicate with the app using this widget. This widget is used to get the data from user in the form of numbers, text or any other text. In this article we will take a look at the implementation of the EditText widget in Android using Jetpack Compose.\nAttributes of EditText WidgetAttributesDescriptionvalue\nvalue is use to get the entered value from the user in the text field.placeholderif the text field is empty we are displaying a hint to the user what he\nhas to enter in the text field.keyboardOptionskeyboardOptions is used to add capitalization in the data which is entered by\nuser in text field, we can also specify auto correction option in this. We can specify\nthe type of keyboard which we have to display such as (phone, text) and to display\nactions which can be performed from the keyboard itself.textStyle\nto add styling to the text entered by user. It is used to add font family, font size and styling to our text.maxLines\nto add maximum lines for our text input field.activeColoractive color is use to when user has click on edit text or the text field is focused and\nentering some data in the text field.singleLine\nIn this we have to specify a boolean value to avoid moving user input into multiple lines.inactiveColor\nInactive color is specified when user is not being focused on our Text Input Field.backgroundColor\nto specify background color for our text input field.leadingIconThis method is use to add leading icon to our text input field. With this method\nwe can also specify color(tint) for our icon.trailingIconThis method is use to add trailing icon to our text input field. With this method\nwe can also specify color(tint) for our icon.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.\nStep 2: Adding EditText in MainActivity.kt file\nNavigate to the app > java > your app\u2019s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.Kotlin package com.example.gfgappimport android.graphics.drawable.shapes.Shape\nimport android.media.Image\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.compose.foundation.BorderStroke\nimport androidx.compose.foundation.Image\nimport androidx.compose.foundation.Text\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.shape.RoundedCornerShape\nimport androidx.compose.foundation.text.KeyboardOptions\nimport androidx.compose.material.*\nimport androidx.compose.material.icons.Icons\nimport androidx.compose.material.icons.filled.AccountCircle\nimport androidx.compose.material.icons.filled.Info\nimport androidx.compose.material.icons.filled.Phone\nimport androidx.compose.runtime.*\nimport androidx.compose.runtime.savedinstancestate.savedInstanceState\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.layout.ContentScale\nimport androidx.compose.ui.platform.setContent\nimport androidx.compose.ui.res.imageResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport androidx.compose.ui.unit.dp\nimport com.example.gfgapp.ui.GFGAppTheme\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.draw.clip\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.graphics.SolidColor\nimport androidx.compose.ui.platform.ContextAmbient\nimport androidx.compose.ui.res.colorResource\nimport androidx.compose.ui.text.TextStyle\nimport androidx.compose.ui.text.font.FontFamily\nimport androidx.compose.ui.text.input.*\nimport androidx.compose.ui.unit.Dp\nimport androidx.compose.ui.unit.TextUnitclass MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContent {\nGFGAppTheme {\n// A surface container using the \n// 'background' color from the theme\nSurface(color = MaterialTheme.colors.background) {\n// at below line we are calling \n// our function for text field.\nTxtField();\n}\n}\n}\n}\n}@Composable\nfun TxtField() {\n// we are creating a variable for\n// getting a value of our text field.\nval inputvalue = remember { mutableStateOf(TextFieldValue()) }\nColumn(\n// we are using column to align our \n// imageview to center of the screen.\nmodifier = Modifier.fillMaxWidth().fillMaxHeight(),// below line is used for specifying\n// vertical arrangement.\nverticalArrangement = Arrangement.Center,// below line is used for specifying \n// horizontal arrangement.\nhorizontalAlignment = Alignment.CenterHorizontally,\n)\n{\nTextField(\n// below line is used to get \n// value of text field,\nvalue = inputvalue.value,// below line is used to get value in text field\n// on value change in text field.\nonValueChange = { inputvalue.value = it },// below line is used to add placeholder \n// for our text field.\nplaceholder = { Text(text = \"Enter user name\") },// modifier is use to add padding \n// to our text field.\nmodifier = Modifier.padding(all = 16.dp).fillMaxWidth(),// keyboard options is used to modify \n// the keyboard for text field.\nkeyboardOptions = KeyboardOptions(\n// below line is use for capitalization \n// inside our text field.\ncapitalization = KeyboardCapitalization.None,// below line is to enable auto \n// correct in our keyboard.\nautoCorrect = true,// below line is used to specify our \n// type of keyboard such as text, number, phone.\nkeyboardType = KeyboardType.Text,\n),// below line is use to specify \n// styling for our text field value.\ntextStyle = TextStyle(color = Color.Black,\n// below line is used to add font \n// size for our text field\nfontSize = TextUnit.Companion.Sp(value = 15),// below line is use to change font family.\nfontFamily = FontFamily.SansSerif),// below line is use to give\n// max lines for our text field.\nmaxLines = 2,// active color is use to change \n// color when text field is focused.\nactiveColor = colorResource(id = R.color.purple_200),// single line boolean is use to avoid \n// textfield entering in multiple lines.\nsingleLine = true,// inactive color is use to change \n// color when text field is not focused.\ninactiveColor = Color.Gray,// below line is use to specify background\n// color for our text field.\nbackgroundColor = Color.LightGray,// leading icon is use to add icon \n// at the start of text field.\nleadingIcon = {\n// In this method we are specifying \n// our leading icon and its color.\nIcon(Icons.Filled.AccountCircle, tint = colorResource(id = R.color.purple_200))\n},\n// trailing icons is use to add \n// icon to the end of text field.\ntrailingIcon = {\nIcon(Icons.Filled.Info, tint = colorResource(id = R.color.purple_200))\n},\n)\n}\n}// @Preview function is use to see preview\n// for our composable function in preview section\n@Preview(showBackground = true)\n@Composable\nfun DefaultPreview() {\nGFGAppTheme {\nTxtField()\n}\n}Output:"}, {"text": "\nAndroid | Creating a Calendar View app\n\nThis article shows how to create an android application for displaying the Calendar using CalendarView. It also provides the selection of the current date and displaying the date. The setOnDateChangeListener Interface is used which provide onSelectedDayChange method.onSelectedDayChange: In this method, we get the values of days, months, and years that are selected by the user.Below are the steps for creating the Android Application of the Calendar.Step 1: Create a new project and you will have a layout XML file and java file. Your screen will look like the image below.\nStep 2: Open your xml file and add CalendarView and TextView. And assign id to TextView and CalendarView. After completing this process, the xml file screen looks like given below.\nStep 3: Now, open up the activity java file and define the CalendarView and TextView type variable, and also use findViewById() to get the Calendarview and textview.\nStep 4: Now, add setOnDateChangeListener interface in object of CalendarView which provides setOnDateChangeListener method. In this method, we get the Dates(days, months, years) and set the dates in TextView for Display.\nStep 5: Now run the app and set the current date which will be shown on the top of the screen.Complete code of MainActivity.java or activity_main.xml of Calendar is given below.activity_main.xml \n \n \n \n MainActivity.java package org.geeksforgeeks.navedmalik.calendar; import android.support.annotation.NonNull; \nimport android.support.v7.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport android.widget.CalendarView; \nimport android.widget.TextView; public class MainActivity extends AppCompatActivity { // Define the variable of CalendarView type \n// and TextView type; \nCalendarView calendar; \nTextView date_view; \n@Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // By ID we can use each component \n// which id is assign in xml file \n// use findViewById() to get the \n// CalendarView and TextView \ncalendar = (CalendarView) \nfindViewById(R.id.calendar); \ndate_view = (TextView) \nfindViewById(R.id.date_view); // Add Listener in calendar \ncalendar \n.setOnDateChangeListener( \nnew CalendarView \n.OnDateChangeListener() { \n@Override// In this Listener have one method \n// and in this method we will \n// get the value of DAYS, MONTH, YEARS \npublic void onSelectedDayChange( \n@NonNull CalendarView view, \nint year, \nint month, \nint dayOfMonth) \n{ // Store the value of date with \n// format in String type Variable \n// Add 1 in month because month \n// index is start with 0 \nString Date \n= dayOfMonth + \"-\"\n+ (month + 1) + \"-\" + year; // set this date in TextView for Display \ndate_view.setText(Date); \n} \n}); \n} \n} Output:"}, {"text": "\nAndroid Slide Up/Down in Kotlin\n\nIn Android Animations are the visuals that are added to make the user interface more interactive, clear and good looking.\nIn this article we will be discussing how to create a Slide Up/Down animation in Kotlin.XML Attributes\nDescriptionandroid:duration\nIt is used to specify the duration of animation android:fromYDelta\nIt is the change in Y coordinate to be applied at the start of the animationandroid:toYDelta\nIt is the change in Y coordinate to be applied at the end of the animationandroid:id\nSets unique id of the viewFirst step is to create a new Project in Android Studio. For this follow these steps:Click on File, then New and then New Project and give name whatever you like\nThen, select Kotlin language Support and click next button.\nSelect minimum SDK, whatever you need\nSelect Empty activity and then click finish.After that, we need to design our layout. For that we need to work with the XML file. Go to app > res > layout and paste the following code:\nModify activity_main.xml file \n \n Add anim folder\nIn this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right click and then select, Android Resource Directory and name it as anim.\nAgain right click this anim folder and select Animation resource file and name it as slide_up. Similarly, also create slide_down.xml and paste the following code.\nslide_up.xml \n \n \n slide_down.xml \n \n \n Modify MainActivity.kt file\nOpen app/src/main/java/yourPackageName/MainActivity.kt and do the following changes: package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.view.animation.AnimationUtils \nimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) //setting buttons onClickListener \nslide_down.setOnClickListener { \n//adding our custom made animation xml file \nval animation = AnimationUtils.loadAnimation( \nthis, R.anim.fade_out) \n//appending animation to textView \ntextView.startAnimation(animation) \n} \nslide_up.setOnClickListener { \nval animation = AnimationUtils.loadAnimation( \nthis, R.anim.fade_in) \ntextView.startAnimation(animation) \n} \n} \n} AndroidManifest.xml file \n \n \n \n \n \n \n Run as emulator: https://media.geeksforgeeks.org/wp-content/uploads/20191124123100/slideUp.mp4"}, {"text": "\n8 Best Android Libraries That Every Android Developer Should Know\n\nAndroid is an operating system which is built basically for Mobile phones. It is used for touchscreen mobile devices like smartphones and tablets. But nowadays these are utilized in Android Auto cars, TV, watches, camera, etc. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. Today, Android remains to dominate on a global scale. It is an operating system that has a huge market for apps.Developing an Android application without Android libraries\u2019 magic is always a wearying job. Libraries help to lessen the time, effort, and money required for the creation of an Android app. Here are some of the best libraries that every developer should know.\n1. Dagger 2\nDagger 2 is one of the best Android libraries and it mainly relies on using Java annotation processors that include compiling time in order to calculate and identify dependencies. The main benefit of Dagger 2 over other dependency injection frameworks is that its strictly designed implementation means that it can be utilized in Android applications. But, there are still some factors to be made when using Dagger within Android applications. The basic dilemma of creating an Android application using Dagger is that several Android framework classes are instantiated by the OS itself, like Activity and Fragment, but Dagger works great if it can generate all the injected objects. Alternatively, the developers have to perform members\u2019 injection in a lifecycle method.\n2. Retrofit\nRetrofit is a type-safe REST client build by square for Android and Java which intends to make it simpler to expand RESTful web services. Retrofit uses OkHttp as the systems administration layer and is based on it. Retrofit naturally serializes the JSON reaction utilizing a POJO (PlainOldJavaObject) which must be characterized in cutting edge for the JSON Structure. To serialize JSON we require a converter to change over it into Gson first. Retrofit is much simpler than other libraries we don\u2019t have to parse our JSON it directly returns objects but there is one disadvantage also it doesn\u2019t provide support to load images from the server but we can use Picasso for the same.\n3. Picasso\nPicasso is an open-source and one of the widely used image downloaders libraries in Android. It is created and maintained by Square. It is one of the powerful image downloads and caching library in Android. Picasso simplifies the process of loading images from external URLs and displays on the application. For example, downloading an image from the server is one of the most common tasks in any application. And it needs quite a larger amount of code to achieve this via android networking APIs. By using Picasso, one can achieve this with a few lines of code.\n4. Glide\nGlide is similar to Picasso and can load and display images from many sources, while also taking care of caching and keeping a low memory impact when doing image manipulations. Official Google apps are also using Glide. Glide is an Image Loader Library in Android developed by bumptech and is a library that is backed by Google. It has been utilized in many Google open source projects including Google I/O 2014 official application. It renders animated GIF support and handles image loading/caching.\n5. Zxing\nZXing stands for \u201czebra crossing\u201d. It is a barcode image processing library implemented in Java, with ports to other languages. It has support for the 1D product, 1D industrial, and 2D barcodes. Google uses ZXing by web search to obtain millions of barcodes on the web indexable. It also creates the foundation of Android\u2019s Barcode Scanner app and is combined into Google Product and Book Search.\n6. CAMView\nCAMView is an android camera easy access library and installed QR scanner, based on ZXing. It is an android library with simple yet compelling components for using the device camera in the apps. The library comprises a set of components (views), ready to be set to the layout files in order to provide developer instant access to the following features:Immediately display the live preview video feed from the device camera\nScan barcodes using built-in ZXing decoding engine\nPerform your own camera live data processingCAMView takes and hides all the messy jobs and mangles for handling the low-level methods, like camera initialization, configuration, streaming, orientation changes, device and cameras compatibility, threading, etc. Just set the proper view component to the layout and the app is camera-ready.\n7. Stetho\nStetho is a sophisticated debug bridge for Android applications. When enabled, developers have a path to the Chrome Developer Tools feature natively part of the Chrome desktop browser. Developers can also prefer to allow the optional dumpapp tool which allows a powerful command-line interface to application internals. Without limiting its functionality to just network inspection, JavaScript console, database inspection, etc.\n8. ButterKnife\nButterKnife is one of the best android libraries that bind android views and callbacks to fields and methods. But unfortunately, this tool is now deprecated. Developers are switching to View Binding. View binding is a feature that enables you to more efficiently write code that interacts with views. Once view binding is allowed in a module, it forms a binding class for each XML layout file available in that module. An example of a binding class contains direct references to all views that have an ID in the corresponding layout. In most cases, view binding replaces findViewById."}, {"text": "\nHow to Build a Simple Flashlight/TorchLight Android App?\n\nAll the beginners who are into the android development world should build a simple android application that can turn on/off the flashlight or torchlight by clicking a Button. So at the end of this article, one will be able to build their own android flashlight application with a simple layout. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.Steps for Building a Simple Flashlight/TorchLight Android App\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Working with the activity_main.xmlThis layout contains a simple TextView, View (as divider), and one ToggleButton to toggle the Flashlight unit.\nPlease refer to How to add Toggle Button in an Android Application, to implement, and to see how the toggle button works.\nInvoke the following code in the activity_main.xml file or one can design custom widgets.XML \n \n \n The following output UI is produced:Step 3: Handling the Toggle Button widget to toggle ON or OFF inside the MainActivity.java file\nThe complete code for the MainActivity.java file is given below. Comments are added inside the code to understand the code in more detail.Java import android.content.Context;\nimport android.hardware.camera2.CameraAccessException;\nimport android.hardware.camera2.CameraManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Toast;\nimport android.widget.ToggleButton;\nimport androidx.annotation.RequiresApi;\nimport androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {private ToggleButton toggleFlashLightOnOff;\nprivate CameraManager cameraManager;\nprivate String getCameraID;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// Register the ToggleButton with specific ID\ntoggleFlashLightOnOff = findViewById(R.id.toggle_flashlight);// cameraManager to interact with camera devices\ncameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);// Exception is handled, because to check whether\n// the camera resource is being used by another\n// service or not.\ntry {\n// O means back camera unit,\n// 1 means front camera unit\ngetCameraID = cameraManager.getCameraIdList()[0];\n} catch (CameraAccessException e) {\ne.printStackTrace();\n}\n}// RequiresApi is set because, the devices which are\n// below API level 10 don't have the flash unit with\n// camera.\n@RequiresApi(api = Build.VERSION_CODES.M)\npublic void toggleFlashLight(View view) {\nif (toggleFlashLightOnOff.isChecked()) {\n// Exception is handled, because to check\n// whether the camera resource is being used by\n// another service or not.\ntry {\n// true sets the torch in ON mode\ncameraManager.setTorchMode(getCameraID, true);// Inform the user about the flashlight\n// status using Toast message\nToast.makeText(MainActivity.this, \"Flashlight is turned ON\", Toast.LENGTH_SHORT).show();\n} catch (CameraAccessException e) {\n// prints stack trace on standard error\n// output error stream\ne.printStackTrace();\n}\n} else {\n// Exception is handled, because to check\n// whether the camera resource is being used by\n// another service or not.\ntry {\n// true sets the torch in OFF mode\ncameraManager.setTorchMode(getCameraID, false);// Inform the user about the flashlight\n// status using Toast message\nToast.makeText(MainActivity.this, \"Flashlight is turned OFF\", Toast.LENGTH_SHORT).show();\n} catch (CameraAccessException e) {\n// prints stack trace on standard error\n// output error stream\ne.printStackTrace();\n}\n}\n}\n// when you click on button and torch open and \n// you do not close the torch again this code \n// will off the torch automatically\n@RequiresApi(api = Build.VERSION_CODES.M)\n@Override\npublic void finish() {\nsuper.finish();\ntry {\n// true sets the torch in OFF mode\ncameraManager.setTorchMode(getCameraID, false);// Inform the user about the flashlight\n// status using Toast message\nToast.makeText(SlaphScreen.this, \"Flashlight is turned OFF\", Toast.LENGTH_SHORT).show();\n} catch (CameraAccessException e) {\n// prints stack trace on standard error\n// output error stream\ne.printStackTrace();\n}\n}\n}Kotlin import android.content.Context;\nimport android.hardware.camera2.CameraAccessException;\nimport android.hardware.camera2.CameraManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Toast;\nimport android.widget.ToggleButton;\nimport androidx.annotation.RequiresApi;\nimport androidx.appcompat.app.AppCompatActivity; \npublic class MainActivity extends AppCompatActivity {\nprivate var toggleFlashLightOnOff: ToggleButton? = null\nprivate var cameraManager: CameraManager? = null\nprivate var getCameraID: String? = nulloverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// Register the ToggleButton with specific ID\ntoggleFlashLightOnOff = findViewById(R.id.toggle_flashlight)// cameraManager to interact with camera devices\ncameraManager = getSystemService(Context.CAMERA_SERVICE) as CameraManager// Exception is handled, because to check whether\n// the camera resource is being used by another\n// service or not.\ntry {\n// O means back camera unit,\n// 1 means front camera unit\ngetCameraID = cameraManager!!.cameraIdList[0]\n} catch (e: CameraAccessException) {\ne.printStackTrace()\n}\n}// RequiresApi is set because, the devices which are\n// below API level 10 don't have the flash unit with\n// camera.\n@RequiresApi(api = Build.VERSION_CODES.M)\nfun toggleFlashLight(view: View?) {\nif (toggleFlashLightOnOff!!.isChecked) {\n// Exception is handled, because to check\n// whether the camera resource is being used by\n// another service or not.\ntry {\n// true sets the torch in ON mode\ncameraManager!!.setTorchMode(getCameraID!!, true)// Inform the user about the flashlight\n// status using Toast message\nToast.makeText(this@MainActivity, \"Flashlight is turned ON\", Toast.LENGTH_SHORT)\n.show()\n} catch (e: CameraAccessException) {\n// prints stack trace on standard error\n// output error stream\ne.printStackTrace()\n}\n} else {\n// Exception is handled, because to check\n// whether the camera resource is being used by\n// another service or not.\ntry {\n// true sets the torch in OFF mode\ncameraManager!!.setTorchMode(getCameraID!!, false)// Inform the user about the flashlight\n// status using Toast message\nToast.makeText(this@MainActivity, \"Flashlight is turned OFF\", Toast.LENGTH_SHORT)\n.show()\n} catch (e: CameraAccessException) {\n// prints stack trace on standard error\n// output error stream\ne.printStackTrace()\n}\n}\n}// when you click on button and torch open and\n// you do not close the tourch again this code\n// will off the tourch automatically\n@RequiresApi(api = Build.VERSION_CODES.M)\noverride fun finish() {\nsuper.finish()\ntry {\n// true sets the torch in OFF mode\ncameraManager!!.setTorchMode(getCameraID!!, false)// Inform the user about the flashlight\n// status using Toast message\nToast.makeText(this@SlaphScreen, \"Flashlight is turned OFF\", Toast.LENGTH_SHORT).show()\n} catch (e: CameraAccessException) {\n// prints stack trace on standard error\n// output error stream\ne.printStackTrace()\n}\n}\n}\n// This code is added by Ujjwal Kumar BhardwajRead about the printStackTrace() function here: Throwable printStackTrace() method in Java with Examples.\nAfter handling the ToggleButton one needs to test the application under a physical android device. Because if you run the application in the emulator which comes with android studio, the app is going to crash as soon as ToggleButton is clicked, because the emulator device wouldn\u2019t come with the camera flash unit.\nThis method of accessing the camera hardware doesn\u2019t require special permission from the user to access the camera unit. Because in this we are accessing the flash unit through only camera ID (whether it\u2019s a front camera or back camera).Output:https://media.geeksforgeeks.org/wp-content/uploads/20200921184957/GFG_frame_nexus_5.mp4"}, {"text": "\nUser authentication using Firebase in Android\n\nFirebase is a mobile and web application development platform. It provides services that a web application or mobile application might require. Firebase provides email and password authentication without any overhead of building backend for user authentication.\nSteps for firebase user authentication are:Step 1:\nCreate a new project on android studio or open an existing project in which you want to add authentication and add the firebase to that android application.Steps to add firebase are very well explained in following link : https://www.geeksforgeeks.org/adding-firebase-to-android-app/Step 2:\nGo to Firebase console (http://console.firebase.google.com/) navigate to your application, and under the authentication tab, enable email/pass authentication.Step 3: activity_registration.xml\nThis is your sign-up activity. It has two EditTexts, a TextView, a Button and a Progress Bar. All these views are contained in a Linear Layout with vertical orientation. EditTexts are used to get email and password from the user. Button is used for signup purpose after filling username and password.\nComplete xml code for registration activity(activity_registration) is:activity_registration.xml \n \n \n \n \n \n \n Step 4: RegistrationActivity.javaNow turn is of Java code for registration activity.In this, we have a one-click listener attached to the button. On button click, registerNewUser() is called.In this method, it is checked if any of the parameters that are email and password is not empty. If that\u2019s the case then an error message is displayed. If both Edit texts have data, then createUserWithEmailAndPassword() method is invoked.To register a new user createUserWithEmailAndPassword() function is used which intakes two-parameter that is email and password for which you want to register.Inside createUserWithEmailAndPassword() method, task success is checked. If the task is successful then the user is directed to MainActivity or dashboard else a Toast message with \u201cregistration failed\u201d is displayed.For user authentication we have to take reference to the FirebaseAuth.We can take reference using getInstance function.Code snippet is:\nFirebaseAuth mAuth = FirebaseAuth.getInstance();Java code for registration activity is:RegistrationActivity.java package com.geeksforgeeks.firebaseuserauthentication; import android.support.v7.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.content.Intent; \nimport android.view.View; \nimport android.widget.Toast; \nimport android.widget.EditText; \nimport android.widget.TextView; \nimport android.widget.Button; import com.google.firebase.auth.FirebaseAuth; \nimport com.google.firebase.auth.AuthResult; \nimport com.google.android.gms.tasks.OnCompleteListener; \nimport com.google.android.gms.tasks.Task; public class RegistrationActivity extends AppCompatActivity { private EditText emailTextView, passwordTextView; \nprivate Button Btn; \nprivate ProgressBar progressbar; \nprivate FirebaseAuth mAuth; @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_registration); // taking FirebaseAuth instance \nmAuth = FirebaseAuth.getInstance(); // initialising all views through id defined above \nemailTextView = findViewById(R.id.email); \npasswordTextView = findViewById(R.id.passwd); \nBtn = findViewById(R.id.btnregister); \nprogressbar = findViewById(R.id.progressbar); // Set on Click Listener on Registration button \nBtn.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) \n{ \nregisterNewUser(); \n} \n}); \n} private void registerNewUser() \n{ // show the visibility of progress bar to show loading \nprogressbar.setVisibility(View.VISIBLE); // Take the value of two edit texts in Strings \nString email, password; \nemail = emailTextView.getText().toString(); \npassword = passwordTextView.getText().toString(); // Validations for input email and password \nif (TextUtils.isEmpty(email)) { \nToast.makeText(getApplicationContext(), \n\"Please enter email!!\", \nToast.LENGTH_LONG) \n.show(); \nreturn; \n} \nif (TextUtils.isEmpty(password)) { \nToast.makeText(getApplicationContext(), \n\"Please enter password!!\", \nToast.LENGTH_LONG) \n.show(); \nreturn; \n} // create new user or register new user \nmAuth \n.createUserWithEmailAndPassword(email, password) \n.addOnCompleteListener(new OnCompleteListener() { @Override\npublic void onComplete(@NonNull Task task) \n{ \nif (task.isSuccessful()) { \nToast.makeText(getApplicationContext(), \n\"Registration successful!\", \nToast.LENGTH_LONG) \n.show(); // hide the progress bar \nprogressBar.setVisibility(View.GONE); // if the user created intent to login activity \nIntent intent \n= new Intent(RegistrationActivity.this, \nMainActivity.class); \nstartActivity(intent); \n} \nelse { // Registration failed \nToast.makeText( \ngetApplicationContext(), \n\"Registration failed!!\"\n+ \" Please try again later\", \nToast.LENGTH_LONG) \n.show(); // hide the progress bar \nprogressBar.setVisibility(View.GONE); \n} \n} \n}); \n} \n} "}, {"text": "\nAbsolute Layout in Android with Example\n\nAn Absolute Layout allows you to specify the exact location i.e. X and Y coordinates of its children with respect to the origin at the top left corner of the layout. The absolute layout is less flexible and harder to maintain for varying sizes of screens that\u2019s why it is not recommended. Although Absolute Layout is deprecated now.\nSome of the important Absolute Layout attributes are the following:\nandroid:id: It uniquely specifies the absolute layoutandroid:layout_x: It specifies X-Coordinate of the Views (Possible values of this is in density-pixel or pixel)android:layout_y: It specifies Y-Coordinate of the Views (Possible values of this is in dp or px)The Syntax for Absolute LayoutXML\n\n ExampleIn this example, we are going to create a basic application with Absolute Layout that is having two TextView. Note that we are going to implement this project using the Java language.\nStep by Step ImplementationStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Create the layout file\nFor this go to app > res > layout > activity_main.xml file and change the Constraint Layout to Absolute Layout and add TextViews. Below is the code snippet for the activity_main.xml file.XML\n \n Before moving further let\u2019s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML \n #0F9D58 \n #16E37F \n #03DAC5 \n Step 3: Working with the MainActivity.java file\nIn this step, we will initialize the TextViews in our MainActivity.java file.Javaimport android.os.Bundle;\nimport android.widget.TextView;\nimport androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity { TextView heading, subHeading; @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); // Referencing the TextViews\n heading = (TextView)findViewById(R.id.heading);\n subHeading\n = (TextView)findViewById(R.id.subHeading); // Setting text dynamically\n heading.setText(\"Computer Science Portal\");\n subHeading.setText(\"GeeksForGeeks\");\n }\n}Output: Run On EmulatorYou will see that TextViews are having fixed X and Y Coordinates."}, {"text": "\nState ProgressBar in Android\n\nState Progress Bar is one of the main features that we see in many applications. We can get to see this feature in ticket booking apps, educational apps. This progress bar helps to tell the user the steps to be carried out for performing a task. In this article, we are going to see how to implement State Progress Bar in Android. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Application of State Progress BarUsed in most of the service providing applications such as ticket booking, exam form filling, and many more.\nThis State Progress Bar helps the user\u2019s steps to be carried out for performing the task.\nUse in various exam form-filling applications.Attributes of State Progress BarAttributesDescriptionlayout_width\nUse for giving specific width.layout_height\nUse for giving specific height.spb_maxStateNumber\nUse to display the number of states used in the app.spb_currentStateNumber\nUse to display the current state.spb_stateBackgroundColor\nUse to display background color.spb_stateForegroundColor\nUse to display Foreground color.spb_animateToCurrentProgressState\nGives Animation to the current Progress state.spb_checkStateCompleted\nCheck whether the state is completed or not.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add dependency of State Progress Bar library in build.gradle file\nThen Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.implementation \u2018com.kofigyan.stateprogressbar:stateprogressbar:1.0.0\u2019Now click on Sync now it will sync your all files in build.gradle().\nStep 3: Create a new State Progress Bar in your activity_main.xml file\nNavigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file.XML \n \n \n Step 4: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import com.kofigyan.stateprogressbar.StateProgressBar; public class MainActivity extends AppCompatActivity { // steps on state progress bar \nString[] descriptionData = {\"Step One\", \"Step Two\", \"Step Three\", \"Step Four\"}; Button button; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); StateProgressBar stateProgressBar = (StateProgressBar) findViewById(R.id.your_state_progress_bar_id); \nstateProgressBar.setStateDescriptionData(descriptionData); // button given along with id \nbutton = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) { \nswitch (stateProgressBar.getCurrentStateNumber()) { \ncase 1: \nstateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.TWO); \nbreak; \ncase 2: \nstateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.THREE); \nbreak; \ncase 3: \nstateProgressBar.setCurrentStateNumber(StateProgressBar.StateNumber.FOUR); \nbreak; \ncase 4: \nstateProgressBar.setAllStatesCompleted(true); \nbreak; \n} \n} \n}); \n} \n}Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210115134220/Screenrecorder-2021-01-15-13-37-46-819.mp4"}, {"text": "\nHow to Create Dynamic Intro Slider in Android using Firebase Firestore?\n\nWe have seen creating a basic Intro Slider in Android which is used to inform our users regarding the features of our app and many more. In this article, we will take a look at the implementation of dynamic Intro Slider in our app with the help of Firebase. With the help of Firebase Firestore, we can change all the data dynamically from Firebase Console. Now let\u2019s move towards the implementation.\nWhat we are going to build in this project?We will be building a simple Intro Slider in which we will load all the data from the Firebase Console and display that data in our slider. With the help of Firebase, we can dynamically update our data according to our requirements. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step by Step Implementation Step 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Connect your app to Firebase\nAfter creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to app > Gradle Scripts inside that file check weather below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. \nimplementation \u2018com.google.firebase:firebase-firestore:22.0.1\u2019\nimplementation \u2018com.squareup.picasso:picasso:2.71828\u2019\nAfter adding this dependency sync your project and now we are ready for creating our app. if you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. As we are loading images from URL so we have to use Picasso.\nStep 3: Adding permissions for the Internet\nAs we will be loading images from the URL, so we have to add permissions for the internet in your AndroidManifest.xml file. For adding permissions. Navigate to the app > AndroidManifest.xml file and add the below permissions. XML\n \n Step 4: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML\n \n \n \n \n \n \n \n \n \n Step 5: Creating a layout file for our slider item\nNow we will create an item that we will be displaying in our slider. So for creating a new layout navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as slider_layout and add below code to it. XML\n \n \n \n \n \n \n \n Step 6: Creating a Modal class for storing all the data for Slider items\nFor creating a new Modal class navigate to the app > java > your app\u2019s package name > Right-click on it and click on New > Java class and name it as SliderModal. After creating this class add the below code to it. Javapublic class SliderModal { // string variable for storing title,\n // image url and description.\n private String title;\n private String heading;\n private String imgUrl; public SliderModal() {\n // empty constructor is required\n // when using firebase\n } // creating getter methods.\n public String getTitle() {\n return title;\n } public void setTitle(String title) {\n this.title = title;\n } public String getHeading() {\n return heading;\n } // creating setter methods\n public void setHeading(String heading) {\n this.heading = heading;\n } public String getImgUrl() {\n return imgUrl;\n } public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n \n // constructor for our modal class\n public SliderModal(String title, String heading, String imgUrl) {\n this.title = title;\n this.heading = heading;\n this.imgUrl = imgUrl;\n }\n}Step 7: Create an Adapter class for setting data to each view\nFor creating a new Adapter class. Navigate to the app > java > your app\u2019s package name > Right-click on it > New Java class > name it as SliderAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.Javaimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.RelativeLayout;\nimport android.widget.TextView;import androidx.annotation.NonNull;\nimport androidx.viewpager.widget.PagerAdapter;import com.squareup.picasso.Picasso;import java.util.ArrayList;public class SliderAdapter extends PagerAdapter { // creating variables for layout inflater,\n // context and array list.\n LayoutInflater layoutInflater;\n Context context;\n ArrayList sliderModalArrayList; // creating constructor.\n public SliderAdapter(Context context, ArrayList sliderModalArrayList) {\n this.context = context;\n this.sliderModalArrayList = sliderModalArrayList;\n } @Override\n public int getCount() {\n // inside get count method returning \n // the size of our array list.\n return sliderModalArrayList.size();\n }\n \n @Override\n public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {\n // inside isViewFromobject method we are \n // returning our Relative layout object.\n return view == (RelativeLayout) object;\n } @NonNull\n @Override\n public Object instantiateItem(@NonNull ViewGroup container, int position) {\n // in this method we will initialize all our layout items\n // and inflate our layout file as well.\n layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);\n \n // below line is use to inflate the layout file which we created.\n View view = layoutInflater.inflate(R.layout.slider_layout, container, false);\n \n // initializing our views.\n ImageView imageView = view.findViewById(R.id.idIV);\n TextView titleTV = view.findViewById(R.id.idTVtitle);\n TextView headingTV = view.findViewById(R.id.idTVheading); // setting data to our views.\n SliderModal modal = sliderModalArrayList.get(position);\n titleTV.setText(modal.getTitle());\n headingTV.setText(modal.getHeading());\n Picasso.get().load(modal.getImgUrl()).into(imageView); // after setting the data to our views we \n // are adding the view to our container.\n container.addView(view);\n \n // at last we are returning the view.\n return view;\n } @Override\n public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {\n // this is a destroy view method which\n // is use to remove a view.\n container.removeView((RelativeLayout) object);\n }\n}Step 8: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Javaimport android.os.Bundle;\nimport android.text.Html;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.viewpager.widget.ViewPager;import com.google.android.gms.tasks.OnFailureListener;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.firebase.firestore.DocumentSnapshot;\nimport com.google.firebase.firestore.FirebaseFirestore;\nimport com.google.firebase.firestore.QuerySnapshot;import java.util.ArrayList;\nimport java.util.List;public class MainActivity extends AppCompatActivity { // creating variables for view pager, \n // LinearLayout, adapter and our array list.\n private ViewPager viewPager;\n private LinearLayout dotsLL;\n SliderAdapter adapter;\n private ArrayList sliderModalArrayList;\n private TextView[] dots;\n int size;\n FirebaseFirestore db; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n db = FirebaseFirestore.getInstance();\n \n // initializing all our views.\n viewPager = findViewById(R.id.idViewPager);\n dotsLL = findViewById(R.id.idLLDots);\n \n // in below line we are creating a new array list.\n sliderModalArrayList = new ArrayList<>();\n loadDataFromFirebase(); // calling method to add dots indicator\n addDots(size, 0);\n \n // below line is use to call on page \n // change listener method.\n viewPager.addOnPageChangeListener(viewListener);\n } private void loadDataFromFirebase() { // below line is use to get data from Firebase\n // firestore using collection in android.\n db.collection(\"SliderData\").get()\n .addOnSuccessListener(new OnSuccessListener() {\n @Override\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) {\n // after getting the data we are calling on success method\n // and inside this method we are checking if the received\n // query snapshot is empty or not.\n if (!queryDocumentSnapshots.isEmpty()) {\n // if the snapshot is not empty we are hiding our\n // progress bar and adding our data in a list.\n List list = queryDocumentSnapshots.getDocuments();\n for (DocumentSnapshot d : list) {\n // after getting this list we are passing \n // that list to our object class.\n SliderModal sliderModal = d.toObject(SliderModal.class);\n \n // after getting data from Firebase we are\n // storing that data in our array list\n sliderModalArrayList.add(sliderModal);\n }\n // below line is use to add our array list to adapter class.\n adapter = new SliderAdapter(MainActivity.this, sliderModalArrayList);\n \n // below line is use to set our\n // adapter to our view pager.\n viewPager.setAdapter(adapter);\n \n // we are storing the size of our \n // array list in a variable.\n size = sliderModalArrayList.size();\n } else {\n // if the snapshot is empty we are displaying a toast message.\n Toast.makeText(MainActivity.this, \"No data found in Database\", Toast.LENGTH_SHORT).show();\n }\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n // we are displaying a toast message when\n // we get any error from Firebase.\n Toast.makeText(MainActivity.this, \"Fail to load data..\", Toast.LENGTH_SHORT).show();\n }\n });\n }\n \n private void addDots(int size, int pos) {\n // inside this method we are\n // creating a new text view.\n dots = new TextView[size];\n \n // below line is use to remove all \n // the views from the linear layout.\n dotsLL.removeAllViews();\n \n // running a for loop to add number\n // of dots to our slider.\n for (int i = 0; i < size; i++) {\n // below line is use to add the dots \n // and modify its color.\n dots[i] = new TextView(this);\n dots[i].setText(Html.fromHtml(\"\u2022\"));\n dots[i].setTextSize(35);\n \n // below line is called when the\n // dots are not selected.\n dots[i].setTextColor(getResources().getColor(R.color.white));\n dotsLL.addView(dots[i]);\n }\n if (dots.length > 0) {\n // this line is called when the dots \n // inside linear layout are selected\n dots[pos].setTextColor(getResources().getColor(R.color.purple_200));\n }\n } // creating a method for view pager for on page change listener.\n ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener() {\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override\n public void onPageSelected(int position) {\n // we are calling our dots method to \n // change the position of selected dots.\n addDots(size, position);\n } @Override\n public void onPageScrollStateChanged(int state) { }\n };\n}After adding the above code add the data to Firebase Firestore in Android. \nStep 9: Adding the data to Firebase Firestore in Android\nSearch for Firebase in your browser and go to that website and you will get to see the below screen. After clicking on Go to Console option. Click on your project which is shown below.After clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen. After clicking on Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console. \nYou have to click on Start Collection Option and give the collection name as SliderData. After creating a collection you have to click on Autoid option for creating the first document. Inside this create three fields as title, heading, and imgUrl and add values inside that fields. Add multiple documents in a similar way inside your Firebase Console. After that run your app and see the output of the app. After adding this data to Firebase run your app and see the output of the app.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210117233915/Screenrecorder-2021-01-17-23-37-46-620.mp4\n"}, {"text": "\nHow to Add SearchView in Google Maps in Android?\n\nWe have seen the implementation of Google Maps in Android along with markers on it. But many apps provide features so that users can specify the location on which they have to place markers. So in this article, we will implement a SearchView in our Android app so that we can search a location name and add a marker to that location.\nWhat we are going to build in this article?\nWe will be building a simple application in which we will be displaying a simple Google map and a SearchView. Inside that search view when users enter any location name then we will add a marker to that location on Google Maps. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210126163040/Screenrecorder-2021-01-26-16-21-59-991.mp4\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project.\nStep 2: Generating an API key for using Google Maps\nTo generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY.\nStep 3: Working with the activity_maps.xml file\nAs we are adding SearchView to our Google Maps for searching a location and adding a marker on that location. So we have to add a search view to our activity_maps.xml file. For adding SearchView, navigate to the app > res > layout > activity_maps.xml and add the below code to it. Comments are added in the code to get to know in more detail.XML \n \n \n Step 4: Working with the MapsActivity.java file\nGo to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.location.Address; \nimport android.location.Geocoder; \nimport android.os.Bundle; import androidx.appcompat.widget.SearchView; \nimport androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory; \nimport com.google.android.gms.maps.GoogleMap; \nimport com.google.android.gms.maps.OnMapReadyCallback; \nimport com.google.android.gms.maps.SupportMapFragment; \nimport com.google.android.gms.maps.model.LatLng; \nimport com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; \nimport java.util.List; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // creating a variable \n// for search view. \nSearchView searchView; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_maps); // initializing our search view. \nsearchView = findViewById(R.id.idSearchView); // Obtain the SupportMapFragment and get notified \n// when the map is ready to be used. \nSupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); // adding on query listener for our search view. \nsearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { \n@Override\npublic boolean onQueryTextSubmit(String query) { \n// on below line we are getting the \n// location name from search view. \nString location = searchView.getQuery().toString(); // below line is to create a list of address \n// where we will store the list of all address. \nList addressList = null; // checking if the entered location is null or not. \nif (location != null || location.equals(\"\")) { \n// on below line we are creating and initializing a geo coder. \nGeocoder geocoder = new Geocoder(MapsActivity.this); \ntry { \n// on below line we are getting location from the \n// location name and adding that location to address list. \naddressList = geocoder.getFromLocationName(location, 1); \n} catch (IOException e) { \ne.printStackTrace(); \n} \n// on below line we are getting the location \n// from our list a first position. \nAddress address = addressList.get(0); // on below line we are creating a variable for our location \n// where we will add our locations latitude and longitude. \nLatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); // on below line we are adding marker to that position. \nmMap.addMarker(new MarkerOptions().position(latLng).title(location)); // below line is to animate camera to that position. \nmMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10)); \n} \nreturn false; \n} @Override\npublic boolean onQueryTextChange(String newText) { \nreturn false; \n} \n}); \n// at last we calling our map fragment to update. \nmapFragment.getMapAsync(this); \n} @Override\npublic void onMapReady(GoogleMap googleMap) { \nmMap = googleMap; \n} \n}Now run your app and see the output of the app.\nOutput:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210126163040/Screenrecorder-2021-01-26-16-21-59-991.mp4"}, {"text": "\nHow to add Toggle Button in an Android Application\n\nToggleButton is basically a stop/play or on/off button with an indicator light indicating the current state of ToggleButton. ToggleButton is widely used, some examples are on/off audio, Bluetooth, WiFi, hot-spot etc. This is a subclass of Composite Button.\nhttps://media.geeksforgeeks.org/wp-content/uploads/20240603163054/Toggle_Button.mp4\nToggleButton allows users to change settings between two states from their phone\u2019s Settings menu such as turning their WiFi, Bluetooth, etc. on / off. Since the Android 4.0 version (API level 14), it has another type of toggle button called a switch which provides user slider control. \nNote: Programmatically, the isChecked() method is used to check the current state of the toggle button. This method returns a boolean value. If a toggle button is ON, this returns true otherwise it returns false. Below is an example in which the toggle button is used.\nSteps by Step Implementation of Toggle ButtonStep 1: Create a New Project To create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio.\nNote:SelectJavaas the programming language.\nStep 2: Creating a layout to display the ToggleButtonImportant Operations can be performed using XML Attributes:\nOperation\nXML Attribute\nandroid:textOn\nUsed to change the text to be displayed when the button is On. By default text is \u201cON\u201d\nandroid:textOff\nUsed to change the text to be displayed when the button is Off. By default text is \u201cOFF\u201d\nandroid:disabledAlpha\nThe alpha to apply to the indicator when disabled.\nNavigate res>layout>activity_main.xml:ges the state of the button\nIn this step, open the XML file and add the code to display the toggle button and a textview.acticity_main.xml\n Step 3: Using Methods Associated with the ToggleButtonWe will update the methods to test the full ability of out Togglebutton.\nMethod\nDescription\nCharSquence getTextOn()\nReturns the text when button is On\nCharSquence getTextOff()\nReturns the text when button is Off\nvoid setChecked(boolean checked)\nChanges the state of the button\nNavigate Open the app -> Java -> Package -> Mainactivity.java\nIn this step, open MainActivity and add the below code to initialize the toggle button and add onToggleClick method which will be invoked when the user clicks on the toggle button. This method changes the text in textview. MainActivity.javaimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.ToggleButton;\nimport androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity { ToggleButton togglebutton;\n TextView textview; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); // Initialize the toggle button and text view\n togglebutton = (ToggleButton) findViewById(R.id.toggleButton);\n textview = (TextView) findViewById(R.id.textView);\n } // Method is called when the toggle button is clicked\n public void onToggleClick(View view) {\n if (togglebutton.isChecked()) {\n textview.setText(\"Toggle is ON\");\n } else {\n textview.setText(\"Toggle is OFF\");\n }\n }\n}MainActivity.ktpackage com.gfg.toggle_buttonimport android.os.Bundle\nimport android.view.View\nimport android.widget.TextView\nimport android.widget.ToggleButton\nimport androidx.activity.enableEdgeToEdge\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.view.ViewCompat\nimport androidx.core.view.WindowInsetsCompatclass MainActivity : AppCompatActivity() {\n lateinit var toggleButton: ToggleButton\n lateinit var textView: TextView\n \n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) // Initialize the toggle button and text view\n toggleButton = findViewById(R.id.button_toggle)\n textView = findViewById(R.id.textView1) } // Method is called when the toggle button is clicked\n fun onToggleClick(view: View) {\n if (toggleButton.isChecked) {\n textView.text = \"Toggle is ON\"\n } else {\n textView.text = \"Toggle is OFF\"\n }\n }\n}Output:\nNow connect your device with USB cable and launch the application. You will see a toggle button. Click on the toggle button which will display the status of the toggle button.The Final Application Created Can be downloaded from this link \u2013GitHub Link for the Toggle Key in Android Application"}, {"text": "\nJSON Parsing in Android using Volley Library\n\nJSON is also known as (JavaScript Object Notation) is a format to exchange the data from the server. The data stored in JSON format is lightweight and easy to handle. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using Volley in Android.JSON Object: Json Object can be easily identified with \u201c{\u201d braces opening and \u201c}\u201d braces closing. We can fetch data from JSON objects with their key value. From that key, we can access the value of that key. What we are going to build in this article?\nWe will be building a simple application in which we will be displaying a simple CardView in which we will display a single course that is available on Geeks for Geeks. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210121214223/Screenrecorder-2021-01-21-21-39-44-445.mp4\nBelow is the JSON object from which we will be displaying the data in our Android App.{\n \u201ccourseName\u201d:\u201dFork CPP\u201d,\n \u201ccourseimg\u201d:\u201dhttps://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png\u201d,\n \u201ccourseMode\u201d:\u201dOnline Batch\u201d,\n \u201ccourseTracks\u201d:\u201d6 Tracks\u201d\n}Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add the below dependency in your build.gradle file\nBelow is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. // below line is used for volley library\nimplementation \u2018com.android.volley:volley:1.1.1\u2019\n// below line is used for image loading library\nimplementation \u2018com.squareup.picasso:picasso:2.71828\u2019After adding this dependency sync your project and now move towards the AndroidManifest.xml part. \nStep 3: Adding permissions to the internet in the AndroidManifest.xml file\nNavigate to the app > AndroidManifest.xml and add the below code to it.XML \nStep 4: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n Step 5: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.View; \nimport android.widget.ImageView; \nimport android.widget.ProgressBar; \nimport android.widget.TextView; \nimport android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; \nimport androidx.cardview.widget.CardView; import com.android.volley.Request; \nimport com.android.volley.RequestQueue; \nimport com.android.volley.Response; \nimport com.android.volley.VolleyError; \nimport com.android.volley.toolbox.JsonObjectRequest; \nimport com.android.volley.toolbox.Volley; \nimport com.squareup.picasso.Picasso; import org.json.JSONException; \nimport org.json.JSONObject; public class MainActivity extends AppCompatActivity { // creating variables for our textview, \n// imageview,cardview and progressbar. \nprivate TextView courseNameTV, courseTracksTV, courseBatchTV; \nprivate ImageView courseIV; \nprivate ProgressBar loadingPB; \nprivate CardView courseCV; // below line is the variable for url from \n// where we will be querying our data. \nString url = \"https://jsonkeeper.com/b/63OH\"; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // in below line we are initializing our all views. \nloadingPB = findViewById(R.id.idLoadingPB); \ncourseCV = findViewById(R.id.idCVCourse); \ncourseNameTV = findViewById(R.id.idTVCourseName); \ncourseTracksTV = findViewById(R.id.idTVTracks); \ncourseBatchTV = findViewById(R.id.idTVBatch); \ncourseIV = findViewById(R.id.idIVCourse); // creating a new variable for our request queue \nRequestQueue queue = Volley.newRequestQueue(MainActivity.this); // as our data is in json object format so we are using \n// json object request to make data request from our url. \n// in below line we are making a json object \n// request and creating a new json object request. \n// inside our json object request we are calling a \n// method to get the data, \"url\" from where we are \n// calling our data,\"null\" as we are not passing any data. \n// later on we are calling response listener method \n// to get the response from our API. \nJsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() { \n@Override\npublic void onResponse(JSONObject response) { \n// inside the on response method. \n// we are hiding our progress bar. \nloadingPB.setVisibility(View.GONE); // in below line we are making our card \n// view visible after we get all the data. \ncourseCV.setVisibility(View.VISIBLE); \ntry { \n// now we get our response from API in json object format. \n// in below line we are extracting a string with its key \n// value from our json object. \n// similarly we are extracting all the strings from our json object. \nString courseName = response.getString(\"courseName\"); \nString courseTracks = response.getString(\"courseTracks\"); \nString courseMode = response.getString(\"courseMode\"); \nString courseImageURL = response.getString(\"courseimg\"); // after extracting all the data we are \n// setting that data to all our views. \ncourseNameTV.setText(courseName); \ncourseTracksTV.setText(courseTracks); \ncourseBatchTV.setText(courseMode); // we are using picasso to load the image from url. \nPicasso.get().load(courseImageURL).into(courseIV); \n} catch (JSONException e) { \n// if we do not extract data from json object properly. \n// below line of code is use to handle json exception \ne.printStackTrace(); \n} \n} \n}, new Response.ErrorListener() { \n// this is the error listener method which \n// we will call if we get any error from API. \n@Override\npublic void onErrorResponse(VolleyError error) { \n// below line is use to display a toast message along with our error. \nToast.makeText(MainActivity.this, \"Fail to get data..\", Toast.LENGTH_SHORT).show(); \n} \n}); \n// at last we are adding our json \n// object request to our request \n// queue to fetch all the json data. \nqueue.add(jsonObjectRequest); \n} \n}Now run your app and see the output of the app.\nOutput:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210121214223/Screenrecorder-2021-01-21-21-39-44-445.mp4"}, {"text": "\nTextClock in Kotlin\n\nAndroid TextClock is a user interface control that is used to show the date/time in string format.\nIt provides time in two modes, the first one is to show the time in 24 Hour format and another one is to show the time in 12-hour format. We can easily use is24HourModeEnabled() method, to show the system using TextClock in 24 Hours or 12 Hours format.\nFirst, we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Different attributes for TextClock widgetXML attributes\nDescriptionandroid:id\nUsed to specify the id of the view.android:timeZone\nUsed to specify the zone for the time.android:format12Hour\nUsed for the 12 hour format.android:format24Hour\nUsed for the 24 hour format.android:text\nUsed to specify the text.android:textStyle\nUsed to specify the style of the text.android:textSize\nUsed to specify the size of the text.android:background\nUsed to set the background of the view.android:padding\nUsed to set the padding of the view.android:visibility\nUsed to set the visibility of the view.android:gravity\nUsed to specify the gravity of the view like center, top, bottom, etcModify activity_main.xml file\nIn this file, we use the TextClock, TextView, and Button and set attributes for all the widgets.XML \n \n Update strings.xml file\nHere, we update the name of the application using the string tag.XML \nTextClockInKotlin \n Access TextClock in MainActivity.kt file\nFirst, we declare two variables txtClock and txtView to access the widgets from the XML layout using the id.\nval txtClock = findViewById(R.id.txtClok)\n val txtView = findViewById(R.id.textview)\nthen, we access the button and set OnClickListener to display the time while clicking the button.\nval btn = findViewById(R.id.btn)\n btn?.setOnClickListener {\n txtView?.text = \"Time: \" + txtClock?.textKotlin package com.geeksforgeeks.myfirstKotlinappimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextClock\nimport android.widget.TextViewclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)val txtClock = findViewById(R.id.txtClok)\nval txtView = findViewById(R.id.textview)val btn = findViewById(R.id.btn)\nbtn?.setOnClickListener {\ntxtView?.text = \"Time: \" + txtClock?.text\n}\n}\n}AndroidManifest.xml fileKotlin \n\n\n\n \n \n \n Run as Emulator:"}, {"text": "\nGridView Using BaseAdapter in Android with Example\n\nHere, we are designing an android app to demonstrate the use of GridView layout. The GridView layout is a ViewGroup that groups view in a two-dimensional scrolling grid of rows and columns. Items in the grid view are inserted using a ListAdapter. The layout by default is scrollable and we don\u2019t need to use ScrollView. An example of GridView is your default Gallery.\nAttributes of a GridViewAttributesDescriptionid\nLike all other views, android uses the id element to uniquely identify an element.numColumns\nThe number of columns to display. It can be an integer or auto_fit which will display as many possible columns to fill the screen of the device. If they don\u2019t specify this attribute then the grid view will behave like a listview.horizontalSpacing\nhorizontalSpacing property is used to define the default horizontal spacing between columns. This could be in pixel(px), density pixel(dp), or scale-independent pixel(sp).verticalSpacing\nThe vertical spacing property is used to define the default vertical spacing between rows. This should be in px, dp or sp.GridView Example Using Different Adapters in Android\nAn Adapter is a connection between the UI components(TextView, ImageView) and the data source. An adapter helps fill the UI element with the appropriate data. In android commonly used adapters that fill data in GridView are:ArrayAdapter\nBaseAdapter\nCustom ArrayAdapterThis tutorial will be using the BaseAdapter, following is the structure of the class that extends the base adapter.Java public class MyAdapter extends BaseAdapter { \n@Override public int getCount() { \nreturn 0; \n} @Override public Object getItem(int i) { \nreturn null; \n} @Override public long getItemId(int i) { \nreturn 0; \n} @Override\npublic View getView(int i, View view, ViewGroup viewGroup) { \nreturn null; \n} \n}Method Description:getCount(): this method returns the count of the total elements to be displayed.\ngetItem(int i): this method takes in an index and returns an object.\ngetItemId(int i): this method takes in an index and returns the id of the item being displayed in the GridView.\ngetView(int I, View view, ViewGroup group): this is the most important method which returns a view that is displayed in the grid view. The int i is the index, the view can be (ImageView or TextView), and the view group is the container that hosts the View e.g LinearLayout, RelativeLayout, etc.Example\nA sample GIF is given below to get an idea about what we are going to do in this article.Note that we are going toimplement this application in both Java and Kotlin Programming Languages for Android.Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the activity_main.xml file\nOpen the activity_main.xml file and insert a GridView component in it.The Layout will look blank initially but will be inflated by the custom adapter class during runtime.XML \n \n Step 3: Creating a new layout XML file\nCreating a new file named grid_layout.xml in the same folder as the activity_main.xml file. This Custom View will host an ImageView. The main reason to use custom adapters is to display complex views in the GridView or ListView instead of some simple text. The custom view is named grid_layout.xml with the LinearLayout as its root and a simple ImageView.XML \n \n Step 4: Creating a Custom Adapter class\nWill name this class MyBaseAdapter which will extend BaseAdapter class and inherit the methods shown above. The main method we need to walk through is the getView method.\n@Override\npublic View getView(int i, View view, ViewGroup viewGroup)\n {\n if (view == null) {\n LayoutInflater inflater\n = (LayoutInflater)c.getSystemService(\nContext.LAYOUT_INFLATER_SERVICE);\n view = inflater.inflate(R.layout.grid_layout,\n viewGroup);\n }\n \n ImageView imageView = view.findViewById(R.id.imageView);\n imageView.setImageResource(items[i]);\n return view;\n}\nThe LayoutInflator is what is responsible for parsing our custom grid_layout.xml file. do note that this operation is expensive and should only be performed when needed. hence its place inside an if statement. Finally, we get a reference to the layout and store it in the view variable. then using that we can initialize the image view and set the image and return the view. In this example, the view shown is quite simple but we can have a more complete view like displaying the id of a person who can have a custom view of the Image, TextView, etc. The entire code of the MyBaseAdapter is given below.Java import android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.BaseAdapter; \nimport android.widget.ImageView; public class MyBaseAdapter extends BaseAdapter { \nContext c; \nint items[]; MyBaseAdapter(Context c, int arr[]) { \nthis.c = c; \nitems = arr; \n} @Override public int getCount() { return items.length; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override\npublic View getView(int i, View view,ViewGroup viewGroup) { \nif (view == null) { \nLayoutInflater inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); \nview = inflater.inflate(R.layout.grid_layout, null); \n} \nImageView imageView = view.findViewById(R.id.imageView); \nimageView.setImageResource(items[i]); \nreturn view; \n} \n}Kotlin import android.content.Context \nimport android.view.View \nimport android.view.ViewGroup \nimport android.widget.BaseAdapter \nimport android.widget.ImageView class MyBaseAdapter internal constructor(var c: Context, var items: IntArray) : \nBaseAdapter() { \noverride fun getCount(): Int { \nreturn items.size \n} override fun getItem(i: Int): Any? { \nreturn null\n} override fun getItemId(i: Int): Long { \nreturn 0\n} override fun getView(i: Int, view: View, viewGroup: ViewGroup): View { \nval view = view \nval imageView = view.findViewById(R.id.imageView) \nimageView.setImageResource(items[i]) \nreturn view \n} \n}Step 5: Working with the MainActivity file\nThe data will use using images of different android studio logos saved in the drawable folder.To use these images we need to store them in an array and pass it to the custom adapter.\nJava:\nint[] itemsarray = new int[] {\n R.drawable.android_1, R.drawable.android_2,\n R.drawable.android_3, R.drawable.android_4,\n R.drawable.android_5, R.drawable.android_1,\n R.drawable.android_2, R.drawable.android_3,\n R.drawable.android_4, R.drawable.android_5\n};Kotlin:\nvar itemsarray = intArrayOf(\n R.drawable.android_1, R.drawable.android_2,\n R.drawable.android_3, R.drawable.android_4,\n R.drawable.android_5, R.drawable.android_1,\n R.drawable.android_2, R.drawable.android_3,\n R.drawable.android_4, R.drawable.android_5\n)\nNotice that the same 5 images are repeated. Now setting up the custom base adapter in the MainActivity file.\nGridView gridView = findViewById(R.id.grid_view);// create a object of myBaseAdapter\nMyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray);\ngridView.setAdapter(baseAdapter);\nFirst, we get a reference of the grid layout from the XML file using the fineViewById() method, then we create the object of myBaseAdapter which takes two arguments Context, and the items array. Finally, we set the adapter. Below is the complete code for theMainActivity file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.widget.GridView; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { int[] itemsarray = new int[] { \nR.drawable.android_1, R.drawable.android_2, \nR.drawable.android_3, R.drawable.android_4, \nR.drawable.android_5, R.drawable.android_1, \nR.drawable.android_2, R.drawable.android_3, \nR.drawable.android_4, R.drawable.android_5 \n}; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); GridView gridView = findViewById(R.id.grid_view); // create a object of myBaseAdapter \nMyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray); \ngridView.setAdapter(baseAdapter); \n} \n}Kotlin import android.os.Bundle \nimport android.widget.GridView \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \nvar itemsarray = intArrayOf( \nR.drawable.android_1, R.drawable.android_2, \nR.drawable.android_3, R.drawable.android_4, \nR.drawable.android_5, R.drawable.android_1, \nR.drawable.android_2, R.drawable.android_3, \nR.drawable.android_4, R.drawable.android_5 \n) override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \nval gridView = findViewById(R.id.grid_view) // create a object of myBaseAdapter \nval baseAdapter = MyBaseAdapter(this, itemsarray) \ngridView.adapter = baseAdapter \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20201026151027/baseadapter.mp4"}, {"text": "\nFirebase RealTime Database with Operations in Android with Examples\n\nFirebase Realtime Database is a Cloud hosted database, i.e. it runs on a cloud and access to the user is provided as a service. It stores data in JSON (Javascript Object Notation) format, a format to store or transport data. All the users connected to it can get access to the data at Real Time.Features of Firebase Realtime Database?Real Time: Due to the Data synchronization used in Real Time, every update is received by the devices/clients in no time.No need of Application Server: As the database can be accessed directly from the mobile device or browser there is no need for an Application Server.Support by various languages and platforms:Splitting Data: The client can split the data across multiple database instances for the same project.Client-Side Code: The dynamic applications with the secured data can be accessed directly from the client-side code.Cross-Platform: It can be used for building a back-end for various platforms like Android, iOS, Web, iOS as well as JavaScript SDK.Structuring the Realtime Database:\nFirebase Realtime Database stores data as one large JSON tree. It stores simple data easily, but the unstructured hierarchical data is difficult to organize. Unlike SQL there are no tables here.What is JSON Tree Model?\nJSON Tree Model is inspired from JSON( JavaScript Object Notation) used to represent the JSON document which generally consists of key-value pair in memory .Why to structure the data (What are the advantages of doing it)?If data is stored in well formatted structure then it is easy to save as well as retrieve it easily.Querying becomes easy on the structured data.It becomes feasible to refer the data in structured format.Key points to remember while structuring the data:\nBefore writing and reading the data into the database, the main aim of the developer should be constructing the structure of the database.Consider the Nesting Limit:\nThe Nesting of the data should be done in a proper way such that it should be easy to read it using Listeners(Listeners are used to reading the data from the database). Avoid unnecessary nesting of levels in the database. Firebase also allows only 32 levels of Nesting.\nFor Example:// JSON Format Structuring Simple Example\n{\n\"userinfo\":\n {\n \"a\":\n {\n \"name\": \"GfG1\",\n \"address\":\"GeeksForGeeksOne\",\n \"order_details\":\n {\n \"p1\":\n {\n \"product_id\":\"1\",\n \"quantity\":\"5\",\n \"price\":\"500\",\n \"address_of_delivery\":\"xyz, abc, ...\"\n },\n \n \"p2\":\n {\n \"product_id\":\"2\",\n \"quantity\":\"10\",\n \"price\":\"1000\",\n \"address_of_delivery\":\"xyz2, abc, ...\"\n } }\n }, \"b\":\n {\n \"name\": \"GfG2\",\n \"address\":\"GeeksForGeeksTwo\",\n \"order_details\":\n {\n \"p1\":\n {\n \"product_id\":\"1\",\n \"quantity\":\"12\",\n \"price\":\"1500\",\n \"address_of_delivery\":\"pqr, abc, ...\"\n },\n \n \"p2\":\n {\n \"product_id\":\"2\",\n \"quantity\":\"18\",\n \"price\":\"1000\",\n \"address_of_delivery\":\"pqr2, abc, ...\"\n } }\n }\n }\n}In this example, retrieving the data of names of users is very difficult as we have to access the child nodes of users_info which downloads the data having several MB\u2019s sizes (in this case name, orders_details, address, etc gets downloaded). Design a Denormalized form of Data:\nThe Flattening of the data should be done correctly, means that data should be split into different parts without any ambiguity. This is generally referred to as denormalisation, where in order to improve read performance we develop redundancy in the data. \nFor Example: // JSON Format Example with Denormalized form for example in Point 1\n{\n \"user_info\":\n {\n \"a\": \n {\n \"name\": \"GfG1\",\n \"address\":\"GeeksForGeeksOne\" \n }, \"b\":\n {\n \"name\": \"GfG2\",\n \"address\":\"GeeksForGeeksTwo\"\n } \n },\n \"order_details\":\n {\n \"a\":\n {\n \"p1\":\n {\n \"product_id\":\"1\",\n \"quantity\":\"5\",\n \"price\":\"500\",\n \"address_of_delivery\":\"xyz, abc, ...\"\n }, \n \n \"p2\":\n {\n \"product_id\":\"2\",\n \"quantity\":\"10\",\n \"price\":\"1000\",\n \"address_of_delivery\":\"xyz2, abc, ...\"\n } \n },\n \"b\":\n {\n \"p1\":\n {\n \"product_id\":\"1\",\n \"quantity\":\"12\",\n \"price\":\"1500\",\n \"address_of_delivery\":\"pqr, abc, ...\"\n },\n \n \"p2\":\n {\n \"product_id\":\"2\",\n \"quantity\":\"18\",\n \"price\":\"1000\",\n \"address_of_delivery\":\"pqr2, abc, ...\"\n } } \n }}In this example, the data is split as user_info and order_deatils. Due to this, the accessibility of the data is faster and hence, no need to download the oversized unnecessary data. Here, Retrieving the data of names of users is very simple as we have to access the child nodes of users_info which downloads the data having a name and address details only and no details of orders are processed. Create a structure which is Dynamic in Nature:\nThe structuring of the data should be such that it should be scalable. Sometimes in order to have easy accessibility of the data, duplication needs to be implemented in the database.\nFor Example: // JSON Format Example explaining the Scaling property\n{\n \"student_info\":\n {\n \"1\":\n {\n \"name\":\"GfG1\",\n \"roll_no\":\"1\",\n \"exam_board\":\"abc\" \n }, \"2\":\n {\n \"name\":\"GfG2\",\n \"roll_no\":\"2\",\n \"exam_board\":\"pqr\" \n },\n \n \"3\":\n {\n \"name\":\"GfG3\",\n \"roll_no\":\"3\",\n \"exam_board\":\"abc\" \n }\n },\n \n \"board_info\":\n {\n \"abc\":\n { \n \"student_names\":\n {\n \"GfG1\":true,\n \"GfG2\":false,\n \"GfG3\":true \n } \n },\n \n \"pqr\":\n { \n \"student_names\":\n {\n \"GfG1\":false,\n \"GfG2\":true,\n \"GfG3\":false \n } \n }\n }}In the above example, in order to access the database easily, the name of the board is stored in every students information as well as the board information stores the name of the student and the board he is having. If we had not stored the data under board information, then it would be difficult to collect the names of students having a particular board.Writing/Inserting data into Firebase Realtime Database\nWriting the data to the Firebase is a very easy task. But before writing / inserting the data to the Realtime database the Structuring of the data should be done. Inserting or writing the data to the Firebase Realtime database is done in Android using the function setValue(). Inserting the data to the Firebase Realtime database can be considered as one of the CRUD operations.\nsetValue(): This function is used to: Replace the data at the referenced position \nIf no data present at the referenced position then it writes the data directly at that positionThe value/types that can be passed to it are:String\nMap\nList\nDouble\nBoolean\nLong\nUser-defined Object: Here, it should be considered that the user-defined object having default constructor can also be passed as the argument to the function. Steps for Writing/Inserting data into Firebase Realtime Database:\nConsider that we have to store the name of the user to the database Create a Database Reference:// Consider that we have to store\n// this in the databaseString name = \"GfG1\" ; Find the reference of the data where the value is to be stored using the child() function:// Create an object of Firebase Database ReferenceDatabaseReference reference;\nreference = FirebaseDatabase.getInstance().getReference(); Use the referenced object and setValue() function with the value to be stored as an argument to it in order to write the data://Inserts the data to the databasereference.child(\"user\").setValue(name); Output:Example 2: Let us consider another example to store the user-defined object to the database STEP 1:// Create a class Userclass User\n{\n String name;\n String address; User()\n {\n name = \"\";\n address = \"\";\n }\n \n User(String name, String address)\n {\n this.name = name;\n this.address = address;\n }} STEP 2:// Create a user-defined objectUser user1 = new User(\"GfG1\", \"GeeksForGeeks\");STEP 3:// Create an object of Firebase Database ReferenceDatabaseReference reference ;\nreference = FirebaseDatabase.getInstance().getReference(); // Insert the user-defined object to the database reference.child(\"user\").setValue(user1); Output:"}, {"text": "\nHow to Create Dynamic PDF Viewer in Android with Firebase?\n\nIf you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. For loading this PDF from the server we prefer to use PDF Viewer which will load the PDF from the URL in Android. Inside this, we add the URL for PDF inside our Apps code and load it from that URL. What if we want to change that PDF, so for that we need to change the URL of the PDF inside our code. But practically it will not be possible to change the URL for PDF files and update the app for users. So for handling this case we will use Firebase. By using Firebase we will dynamically load PDF from Firebase and update the PDF inside our app. Now we will move towards the implementation part.\nWhat we are going to build in this project?\nWe will be building an application in which we will be loading PDF from our Firebase Console and update that PDF in Realtime by changing the URL in our Firebase Console. For the implementation of this project, we will be using Firebase Realtime Database with which we will be updating our PDF in Realtime. Note that we are going toimplement this project using theJavalanguage.\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Connect your app to Firebase\nAfter creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After completing this process you will get to see the below screen. Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle file and make sure that the below dependency is added in your dependencies section.implementation \u2018com.google.firebase:firebase-database:19.6.0\u2019After adding this dependency add the dependency of PDF Viewer in your Gradle file.\nStep 3: Add the dependency for PDF Viewer in build.gradle file\nNavigate to the app > Gradle Scripts > build.gradle file and add below dependency in it.implementation \u2018com.github.barteksc:android-pdf-viewer:2.8.2\u2019After adding this dependency sync your project. Now we will move towards our XML part.\nStep 4: Add internet permission in your AndroidManifest.xml file\nAdd the permission for the internet in the AndroidManifest.xml file.XML \n Step 5: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n\n Step 6: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.AsyncTask;\nimport android.os.Bundle;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.github.barteksc.pdfviewer.PDFView;\nimport com.google.firebase.database.DataSnapshot;\nimport com.google.firebase.database.DatabaseError;\nimport com.google.firebase.database.DatabaseReference;\nimport com.google.firebase.database.FirebaseDatabase;\nimport com.google.firebase.database.ValueEventListener;import java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.HttpURLConnection;\nimport java.net.URL;public class MainActivity extends AppCompatActivity {// creating a variable for our Firebase Database.\nFirebaseDatabase firebaseDatabase;// creating a variable for our Database \n// Reference for Firebase.\nDatabaseReference databaseReference;// creating a variable for our pdfview\nprivate PDFView pdfView;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// initializing variable for pdf view.\npdfView = findViewById(R.id.pdfView);// below line is used to get the instance \n// of our Firebase database.\nfirebaseDatabase = FirebaseDatabase.getInstance();// below line is used to get reference for our database.\ndatabaseReference = firebaseDatabase.getReference(\"url\");// calling method to initialize\n// our PDF view.\ninitializePDFView();\n}private void initializePDFView() {// calling add value event listener method \n// for getting the values from database.\ndatabaseReference.addValueEventListener(new ValueEventListener() {\n@Override\npublic void onDataChange(@NonNull DataSnapshot snapshot) {\n// this method is call to get the realtime updates in the data.\n// this method is called when the data is changed in our Firebase console.\n// below line is for getting the data from snapshot of our database.\nString pdfUrl = snapshot.getValue(String.class);// after getting the value for our Pdf url we are \n// passing that value to our RetrievePdfFromFirebase\n// class which will load our PDF file.\nnew RetrievedPdffromFirebase().execute(pdfUrl);\n}@Override\npublic void onCancelled(@NonNull DatabaseError error) {\n// calling on cancelled method when we receive\n// any error or we are not able to get the data.\nToast.makeText(MainActivity.this, \"Fail to get PDF url.\", Toast.LENGTH_SHORT).show();\n}\n});\n}class RetrievedPdffromFirebase extends AsyncTask {\n// we are calling async task and performing \n// this task to load pdf in background.\n@Override\nprotected InputStream doInBackground(String... strings) {\n// below line is for declaring\n// our input stream.\nInputStream pdfStream = null;\ntry {\n// creating a new URL and passing \n// our string in it.\nURL url = new URL(strings[0]);// creating a new http url connection and calling open\n// connection method to open http url connection.\nHttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();\nif (httpURLConnection.getResponseCode() == 200) {\n// if the connection is successful then \n// we are getting response code as 200.\n// after the connection is successful \n// we are passing our pdf file from url\n// in our pdfstream.\npdfStream = new BufferedInputStream(httpURLConnection.getInputStream());\n}} catch (IOException e) {\n// this method is \n// called to handle errors.\nreturn null;\n}\n// returning our stream\n// of PDF file.\nreturn pdfStream;\n}@Override\nprotected void onPostExecute(InputStream inputStream) {\n// after loading stream we are setting \n// the pdf in your pdf view.\npdfView.fromStream(inputStream).load();\n}\n}\n}Step 7: Adding URL for PDF in your Firebase Console\nFor adding PDF URL in Firebase Console. Browse for Firebase in your browser and Click on Go to Console option in the top right corner as shown in the below screenshot.After clicking on Go to Console option you will get to see your project. Click on your project name from the available list of projects.After clicking on your project. Click on the Realtime Database option in the left window.After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen. In this project, we are adding our rules as true for read as well as a write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.\nStep 8: Adding URL for your PDF in Firebase Console\nInside Firebase Realtime Database. Navigate to the Data tab. Inside this tab Hover on database section inside that click on the \u201c+\u201d icon. After clicking on the \u201c+\u201d icon you will get to see two input fields which are the Name and Value fields. Inside the Name field, you have to add a reference for your PDF file which in our case is \u201curl\u201d. And in our value field, we have to add a URL for our PDF file. After adding the value in this field. Click on the Add button and your data will be added to Firebase Console.After adding this PDF URL now run your app and see the OUTPUT of your app.\nOutput:\nYou can change the URL of the PDF and the PDF inside your app will be updated in Realtime without loading your app again.https://media.geeksforgeeks.org/wp-content/uploads/20210101132859/Screenrecorder-2021-01-01-13-27-16-504.mp4"}, {"text": "\nHow to Create a New Project in Android Studio Canary Version with Jetpack Compose?\n\nJetpack Compose is a new toolkit provided by Google. This is useful for designing beautiful UI designs. After successful installation of the Android Studio Canary version, we are moving towards the creation of a new Project. In this article, we will take a look at How to create a new project in the Android Studio Canary Version using Jetpack Compose.\nCreate a New Project in Android Studio with Jetpack Compose\nAfter launching up your Android Studio Canary version for the first time you will get to see the below screen.\nStep 1: Click on the first option to start with New Project click on the Create New Project option after that you will get to see the below screen.Step 2: After clicking on Create New Project you will get to see the below screen.\nOn this screen make sure to select Phone and Tablet as a default selection and then click on Empty Compose Activity in the right section and then click on the Next option.Step 3: After selecting Empty Compose Activity you will get to see the below screen.\nAfter click on next, you will get to see the below screen. On this screen give a name to your application in the first text box which represents the Name of the project. Select your minimum SDK for Marshmallow (6.0). The 84.9% of devices indicates the % of devices on which our app will works. After giving the name and selecting the minimum SDK click on the Finish option to create a new project.After clicking on Finish the default application will be created and now you can start writing your code."}, {"text": "\nInclude and Merge Tags in Android with Example\n\nAndroid apps are growing and one important aspect of it is reusability. Sometimes, the complexity of app design will be more and during that time, Android providing very efficient reusable features by means of the and tags. Under tags, we can specify a part of the layout that has to come in the main layout. It is similar to the main layout having Button, TextView, etc., It can be specified in a meaningful android naming convention XML file. eg: custom_layout.xml. In the main layout, we can reuse custom_layout by using the tag. The main advantage is many app pages may need custom_layout contents and wherever necessary, there it can be included easily by using the tag. And also in case of modifications, it is a one place change and hence maximum rework is avoided/reduced. Generally used in the idea of customization, reusability of app contents by using and tags.\nInclude Tag\nThis is used to include the contents of reusable content. This is a very good idea of sharing the contents of another layout in the main layout.XML \n Merge TagThe tag helps us to eliminate redundant view groups in our view hierarchy when including one layout within another. Hence in our example, directly we have android elements like Button and ImageView as this is going to get included in the main view and it will take the layout specified in the main file i.e. activity_main.xml(main layout file).XML Note: We can find that and tags look similar to ViewStub but it is not.The ViewStub tag is a little bit different because it is not directly included, and will be loaded only when you actually need it, i.e when you set ViewStub\u2019s visibility to \u201ctrue\u201d.\nBut include and merge tags are directly included and loaded at the beginning itself and mainly helpful for splitting of layouts and reusing them wherever necessary.Attributes of IncludeAttributesDescriptionid\nTo uniquely identify an include taglayoutTo supply an identifier for the layout resource to\ninclude a custom layout in our main layout.Example\nStep 1: Create a New ProjectTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.Step 2: Working with the activity_main.xml fileGo to the activity_main.xml file and refer to the following code. Below is the code for theactivity_main.xml file.XML Step 3: Create a new Layout Resource FileGo to the app > res > layout > right-click > New > Layout Resource File and name the file as custom_layout. Below is the code for the custom_layout.xml and the file should be present with merge contents.XML Step 4: Working with the MainActivity.kt fileGo to the MainActivity.kt file and refer to the following code. Below is the code for theMainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport android.widget.ImageView\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {var customButton: Button? = null\nvar customImageView: ImageView? = nulloverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// As custom layout contents are included, we can refer them as normal way\n// Main advantage lies here only. even this custom_layout can be reused in different xml\n// and in corresponding activity file, they can be referred and there may be a \n// different functionality can be carried out.\n// get the reference of custom Layout's Button\ncustomButton = findViewById(R.id.ButtonToInclude) as Button// get the reference of custom Layout's ImageView\ncustomImageView = findViewById(R.id.imageViewToInclude) as ImageView// We have clicked on Custom layout button, though it is in separate xml\n// because of include tag, it is getting focus here and we can do\n// activities as we like\ncustomButton!!.setOnClickListener { \nToast.makeText(applicationContext, \"We have clicked on Custom layout button\", Toast.LENGTH_LONG).show()\n}\n}\n}Running the Code on the EmulatorWe can able to get the output as attached in the video. Apply and tag wherever necessary and enjoy the reusability feature of android apps.https://media.geeksforgeeks.org/wp-content/uploads/20201028155639/IncludeTagExample1.mp4"}, {"text": "\nHow to Build an Instagram Like Custom RecyclerView in Android?\n\nWe have seen implementing RecyclerView in Android with simple data inside our app. In this article, we will take a look at the implementation of Instagram like Custom RecyclerView in Android.\nWhat we are going to build in this article?\nWe will be building a simple application in which we will be displaying data from the Instagram profile, and we will be using an official Instagram API to load the data from user\u2019s Instagram profile and display that data in a custom RecyclerView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add the below dependency in your build.gradle file \nBelow is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. // dependency for loading data from json file.\nimplementation \u2018com.android.volley:volley:1.1.1\u2019\n// dependency for loading image from url.\nimplementation \u2018com.squareup.picasso:picasso:2.71828\u2019\n// dependency for creating a circle image. \nimplementation \u2018de.hdodenhof:circleimageview:3.1.0\u2019Step 3: Creating API for getting the data for generating API\nNow for creating a basic display API for Instagram posts we will be creating an API for displaying this data. You may refer to the How to Generate API URL for Public Instagram Feeds in Android? Now we have created the URL with the access token and we will use this URL to get the JSON data. \nStep 4: Adding permissions for the internet in the AndroidManifest.xml file\nAs we are loading data from the internet. For that, we will have to add the internet permissions to our AndroidManifest.xml file. Navigate to the app > AndroidManifest.xml file and add the below code to it.XML \n Step 5: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n \n \n Step 6: Creating a new layout file for displaying each item of our RecyclerView\nNavigate to the app > res > layout > Right-click on it > New > layout resource file and name the file as insta_feed_rv_item and add the below code to it.XML \n \n \n \n \n \n \n Step 7: Create a Modal Class to store data for our Feed\nNavigate to the app > java > your app\u2019s package name > Right-click on it > New > Java class and name your class as InstaModal.Java public class InstaModal { \n// variables for storing data \n// of our recycler view item \nprivate String id; \nprivate String media_type; \nprivate String permalink; \nprivate String media_url; \nprivate String username; \nprivate String caption; \nprivate String timestamp; public String getAuthor_url() { \nreturn author_url; \n} public void setAuthor_url(String author_url) { \nthis.author_url = author_url; \n} public int getLikesCount() { \nreturn likesCount; \n} public void setLikesCount(int likesCount) { \nthis.likesCount = likesCount; \n} private String author_url; \nprivate int likesCount; public String getId() { \nreturn id; \n} public void setId(String id) { \nthis.id = id; \n} public String getMedia_type() { \nreturn media_type; \n} public void setMedia_type(String media_type) { \nthis.media_type = media_type; \n} public String getPermalink() { \nreturn permalink; \n} public void setPermalink(String permalink) { \nthis.permalink = permalink; \n} public String getMedia_url() { \nreturn media_url; \n} public void setMedia_url(String media_url) { \nthis.media_url = media_url; \n} public String getUsername() { \nreturn username; \n} public void setUsername(String username) { \nthis.username = username; \n} public String getCaption() { \nreturn caption; \n} public void setCaption(String caption) { \nthis.caption = caption; \n} public String getTimestamp() { \nreturn timestamp; \n} public void setTimestamp(String timestamp) { \nthis.timestamp = timestamp; \n} public InstaModal(String id, String media_type, String permalink, String media_url, String username, \nString caption, String timestamp, String author_url, int likesCount) { \nthis.id = id; \nthis.media_type = media_type; \nthis.permalink = permalink; \nthis.media_url = media_url; \nthis.username = username; \nthis.caption = caption; \nthis.timestamp = timestamp; \nthis.author_url = author_url; \nthis.likesCount = likesCount; \n} \n}Step 8: Creating an Adapter class for setting this data to each item of our RecyclerView\nNavigate to the app > java > your app\u2019s package name > Right-click on it > New Java class and name it as InstagramFeedRVAdapter and add the below code to it.Java import android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.ImageView; \nimport android.widget.TextView; import androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; import de.hdodenhof.circleimageview.CircleImageView; public class InstagramFeedRVAdapter extends RecyclerView.Adapter { private ArrayList instaModalArrayList; \nprivate Context context; public InstagramFeedRVAdapter(ArrayList instaModalArrayList, Context context) { \nthis.instaModalArrayList = instaModalArrayList; \nthis.context = context; \n} @NonNull\n@Override\npublic InstagramFeedRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \n// inflating our layout for item of recycler view item. \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.insta_feed_rv_item, parent, false); \nreturn new InstagramFeedRVAdapter.ViewHolder(view); \n} @Override\npublic void onBindViewHolder(@NonNull InstagramFeedRVAdapter.ViewHolder holder, int position) { \nInstaModal modal = instaModalArrayList.get(position); \nholder.authorTV.setText(modal.getUsername()); \nif (modal.getMedia_type().equals(\"IMAGE\")) { \nPicasso.get().load(modal.getMedia_url()).into(holder.postIV); \n} \nholder.desctv.setText(modal.getCaption()); \nholder.likeTV.setText(\"\" + modal.getLikesCount() + \" likes\"); \nPicasso.get().load(modal.getAuthor_url()).into(holder.authorIV); \n} @Override\npublic int getItemCount() { \nreturn instaModalArrayList.size(); \n} public class ViewHolder extends RecyclerView.ViewHolder { CircleImageView authorIV; \nprivate TextView authorTV; \nprivate ImageView postIV; \nprivate TextView likeTV, desctv; public ViewHolder(@NonNull View itemView) { \nsuper(itemView); \nauthorIV = itemView.findViewById(R.id.idCVAuthor); \nauthorTV = itemView.findViewById(R.id.idTVAuthorName); \npostIV = itemView.findViewById(R.id.idIVPost); \nlikeTV = itemView.findViewById(R.id.idTVLikes); \ndesctv = itemView.findViewById(R.id.idTVPostDesc); \n} \n} \n}Step 9: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.View; \nimport android.widget.ProgressBar; \nimport android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request; \nimport com.android.volley.RequestQueue; \nimport com.android.volley.Response; \nimport com.android.volley.VolleyError; \nimport com.android.volley.toolbox.JsonObjectRequest; \nimport com.android.volley.toolbox.Volley; import org.json.JSONArray; \nimport org.json.JSONException; \nimport org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our requestqueue, \n// array list, progressbar, edittext, \n// image button and our recycler view. \nprivate RequestQueue mRequestQueue; \nprivate ArrayList instaModalArrayList; \nprivate ProgressBar progressBar; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // initializing our views. \nprogressBar = findViewById(R.id.idLoadingPB); \ninstaModalArrayList = new ArrayList<>(); // calling method to load \n// data in recycler view. \ngetInstagramData(); \n} private void getInstagramData() { \n// below line is use to initialize the variable for our request queue. \nmRequestQueue = Volley.newRequestQueue(MainActivity.this); // below line is use to clear cache this will \n// be use when our data is being updated. \nmRequestQueue.getCache().clear(); // below is the url for getting data \n// from API in json format. \nString url = \"Enter your URL\"; // below line we are creating a new request queue. \nRequestQueue queue = Volley.newRequestQueue(MainActivity.this); \nJsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() { \n@Override\npublic void onResponse(JSONObject response) { \nprogressBar.setVisibility(View.GONE); \ntry { \nJSONArray dataArray = response.getJSONArray(\"data\"); \nfor (int i = 0; i < dataArray.length(); i++) { \n// below line is to extract data from JSON file. \nJSONObject dataObj = dataArray.getJSONObject(i); \nString id = dataObj.getString(\"id\"); \nString media_type = dataObj.getString(\"media_type\"); \nString permalink = dataObj.getString(\"permalink\"); \nString media_url = dataObj.getString(\"media_url\"); \nString username = dataObj.getString(\"username\"); \nString caption = dataObj.getString(\"caption\"); \nString timestamp = dataObj.getString(\"timestamp\"); // below line is to add a constant author image URL to our recycler view. \nString author_url = \"https://instagram.fnag5-1.fna.fbcdn.net/v/t51.2885-19/s320x320/75595203_828043414317991_4596848371003555840_n.jpg?_nc_ht=instagram.fnag5-1.fna.fbcdn.net&_nc_ohc=WzA_n4sdoQIAX9B5HWJ&tp=1&oh=05546141f5e40a8f02525b497745a3f2&oe=6031653B\"; \nint likesCount = 100 + (i * 10); // below line is use to add data to our modal class. \nInstaModal instaModal = new InstaModal(id, media_type, permalink, media_url, username, caption, timestamp, author_url, likesCount); // below line is use to add modal \n// class to our array list. \ninstaModalArrayList.add(instaModal); // below line we are creating an adapter class and adding our array list in it. \nInstagramFeedRVAdapter adapter = new InstagramFeedRVAdapter(instaModalArrayList, MainActivity.this); \nRecyclerView instRV = findViewById(R.id.idRVInstaFeeds); // below line is for setting linear layout manager to our recycler view. \nLinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false); // below line is to set layout manager to our recycler view. \ninstRV.setLayoutManager(linearLayoutManager); // below line is to set adapter \n// to our recycler view. \ninstRV.setAdapter(adapter); \n} \n} catch (JSONException e) { \n// handling error case. \ne.printStackTrace(); \nToast.makeText(MainActivity.this, \"Fail to get Data..\" + e.getMessage(), Toast.LENGTH_SHORT).show(); \n} \n} \n}, new Response.ErrorListener() { \n@Override\npublic void onErrorResponse(VolleyError error) { \n// handling error message. \nToast.makeText(MainActivity.this, \"Fail to get Data..\" + error, Toast.LENGTH_SHORT).show(); \n} \n}); \nqueue.add(jsonObjectRequest); \n} \n}Now run your app and see the output of the app.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210120175412/Screenrecorder-2021-01-20-16-33-04-649.mp4\nCheck out the project on the below link: https://github.com/ChaitanyaMunje/LibraryApp/tree/InstagramCustomListVIew"}, {"text": "\nHow to Build a Facebook Like Custom RecyclerView in Android?\n\nWe have seen implementing RecyclerView in Android with simple data inside our app. In this article, we will take a look at the implementation of Facebook like Custom RecyclerView in Android. \nWhat we are going to build in this article?\nWe will be building a simple application in which we will display the Facebook like RecyclerView in our Android app. We will be fetching this data from a simple API (https://jsonkeeper.com/b/OB3B) which is given in the article. With the help of this API, we will be displaying that data in our RecyclerView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add the below dependency in your build.gradle file Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. // dependency for loading data from json file.\nimplementation \u2018com.android.volley:volley:1.1.1\u2019\n// dependency for loading image from url.\nimplementation \u2018com.squareup.picasso:picasso:2.71828\u2019\n// dependency for creating a circle image. \nimplementation \u2018de.hdodenhof:circleimageview:3.1.0\u2019Step 3: Adding internet permissions in your AndroidManifest.xml file\nAs we are loading data from the internet, for that, we will have to add the internet permissions to our AndroidManifest.xml file. Navigate to the app > AndroidManifest.xml file and add the below code to it. XML \n Step 4: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n\n \n Step 5: Creating a custom drawable file for our background image\nNavigate to the app > res > drawable > Right-click on it > New > drawable resource file and name your file as background_drawable and add the below code to it for our custom background.XML \n\n\n \n\n \n Step 6: Creating a layout file for our item of RecyclerView\nNavigate to the app > res > layout > Right-click on it > New > layout Resource file and name it as facebook_feed_rv_item and add the below code to it. Comments are added in the code to get to know in more detail.Note: Icons used in this file are present in the drawable folder. Navigate to the app > res > drawable folder and add your icons to that folder.XML \n\n\n \n \n \n \n \n Step 7: Creating a modal class for storing our data\nNavigate to the app > java > your app\u2019s package name > Right-click on it > New > Java class and name your class as FacebookFeedModal and add the below code to it.Java public class FacebookFeedModal {\n// variables for storing our author image,\n// author name, postDate,postDescription,\n// post image,post likes,post comments.\nprivate String authorImage;\nprivate String authorName;\nprivate String postDate;\nprivate String postDescription;\nprivate String postIV;\nprivate String postLikes;\nprivate String postComments;// creating getter and setter methods.\npublic String getAuthorImage() {\nreturn authorImage;\n}public void setAuthorImage(String authorImage) {\nthis.authorImage = authorImage;\n}public String getAuthorName() {\nreturn authorName;\n}public void setAuthorName(String authorName) {\nthis.authorName = authorName;\n}public String getPostDate() {\nreturn postDate;\n}public void setPostDate(String postDate) {\nthis.postDate = postDate;\n}public String getPostDescription() {\nreturn postDescription;\n}public void setPostDescription(String postDescription) {\nthis.postDescription = postDescription;\n}public String getPostIV() {\nreturn postIV;\n}public void setPostIV(String postIV) {\nthis.postIV = postIV;\n}public String getPostLikes() {\nreturn postLikes;\n}public void setPostLikes(String postLikes) {\nthis.postLikes = postLikes;\n}public String getPostComments() {\nreturn postComments;\n}public void setPostComments(String postComments) {\nthis.postComments = postComments;\n}// creating a constructor class.\npublic FacebookFeedModal(String authorImage, String authorName, String postDate, \nString postDescription, String postIV, String postLikes, \nString postComments) {\nthis.authorImage = authorImage;\nthis.authorName = authorName;\nthis.postDate = postDate;\nthis.postDescription = postDescription;\nthis.postIV = postIV;\nthis.postLikes = postLikes;\nthis.postComments = postComments;\n}\n}Step 8: Creating an Adapter class for setting data to our item of RecyclerView\nNavigate to the app > java > your app\u2019s package name > Right-click on it > New Java class and name it as FacebookFeedRVAdapter and add the below code to it.Java import android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;import androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;import com.squareup.picasso.Picasso;import java.util.ArrayList;import de.hdodenhof.circleimageview.CircleImageView;public class FacebookFeedRVAdapter extends RecyclerView.Adapter {// arraylist for our facebook feeds.\nprivate ArrayList facebookFeedModalArrayList;\nprivate Context context;// creating a constructor for our adapter class.\npublic FacebookFeedRVAdapter(ArrayList facebookFeedModalArrayList, Context context) {\nthis.facebookFeedModalArrayList = facebookFeedModalArrayList;\nthis.context = context;\n}@NonNull\n@Override\npublic FacebookFeedRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n// inflating our layout for item of recycler view item.\nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.facebook_feed_rv_item, parent, false);\nreturn new FacebookFeedRVAdapter.ViewHolder(view);\n}@Override\npublic void onBindViewHolder(@NonNull FacebookFeedRVAdapter.ViewHolder holder, int position) {\n// getting data from array list and setting it to our modal class.\nFacebookFeedModal modal = facebookFeedModalArrayList.get(position);// setting data to each view of recyclerview item.\nPicasso.get().load(modal.getAuthorImage()).into(holder.authorIV);\nholder.authorNameTV.setText(modal.getAuthorName());\nholder.timeTV.setText(modal.getPostDate());\nholder.descTV.setText(modal.getPostDescription());\nPicasso.get().load(modal.getPostIV()).into(holder.postIV);\nholder.likesTV.setText(modal.getPostLikes());\nholder.commentsTV.setText(modal.getPostComments());\n}@Override\npublic int getItemCount() {\n// returning the size of our array list.\nreturn facebookFeedModalArrayList.size();\n}public class ViewHolder extends RecyclerView.ViewHolder {\n// creating variables for our views \n// of recycler view items.\nprivate CircleImageView authorIV;\nprivate TextView authorNameTV, timeTV, descTV;\nprivate ImageView postIV;\nprivate TextView likesTV, commentsTV;\nprivate LinearLayout shareLL;public ViewHolder(@NonNull View itemView) {\nsuper(itemView);\n// initializing our variables\nshareLL = itemView.findViewById(R.id.idLLShare);\nauthorIV = itemView.findViewById(R.id.idCVAuthor);\nauthorNameTV = itemView.findViewById(R.id.idTVAuthorName);\ntimeTV = itemView.findViewById(R.id.idTVTime);\ndescTV = itemView.findViewById(R.id.idTVDescription);\npostIV = itemView.findViewById(R.id.idIVPost);\nlikesTV = itemView.findViewById(R.id.idTVLikes);\ncommentsTV = itemView.findViewById(R.id.idTVComments);\n}\n}\n}Step 9: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.view.View;\nimport android.widget.ProgressBar;\nimport android.widget.Toast;import androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;import com.android.volley.Request;\nimport com.android.volley.RequestQueue;\nimport com.android.volley.Response;\nimport com.android.volley.VolleyError;\nimport com.android.volley.toolbox.JsonObjectRequest;\nimport com.android.volley.toolbox.Volley;import org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;import java.util.ArrayList;public class MainActivity extends AppCompatActivity {// creating variables for our requestqueue,\n// array list, progressbar, edittext,\n// image button and our recycler view.\nprivate RequestQueue mRequestQueue;\nprivate ArrayList instaModalArrayList;\nprivate ArrayList facebookFeedModalArrayList;\nprivate ProgressBar progressBar;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// initializing our views.\nprogressBar = findViewById(R.id.idLoadingPB);// calling method to load\n// data in recycler view.\ngetFacebookFeeds();\n}private void getFacebookFeeds() {\nfacebookFeedModalArrayList = new ArrayList<>();// below line is use to initialize the variable for our request queue.\nmRequestQueue = Volley.newRequestQueue(MainActivity.this);// below line is use to clear\n// cache this will be use when\n// our data is being updated.\nmRequestQueue.getCache().clear();// below is the url stored in\n// string for our sample data\nString url = \"https://jsonkeeper.com/b/OB3B\";JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {\n@Override\npublic void onResponse(JSONObject response) {\nprogressBar.setVisibility(View.GONE);\ntry {\n// in below line we are extracting the data from json object.\nString authorName = response.getString(\"authorName\");\nString authorImage = response.getString(\"authorImage\");// below line is to get json array from our json object.\nJSONArray feedsArray = response.getJSONArray(\"feeds\");// running a for loop to add data to our array list\nfor (int i = 0; i < feedsArray.length(); i++) {\n// getting json object of our json array.\nJSONObject feedsObj = feedsArray.getJSONObject(i);// extracting data from our json object.\nString postDate = feedsObj.getString(\"postDate\");\nString postDescription = feedsObj.getString(\"postDescription\");\nString postIV = feedsObj.getString(\"postIV\");\nString postLikes = feedsObj.getString(\"postLikes\");\nString postComments = feedsObj.getString(\"postComments\");// adding data to our modal class.\nFacebookFeedModal feedModal = new FacebookFeedModal(authorImage, authorName, postDate, postDescription, postIV, postLikes, postComments);\nfacebookFeedModalArrayList.add(feedModal);// below line we are creating an adapter class and adding our array list in it.\nFacebookFeedRVAdapter adapter = new FacebookFeedRVAdapter(facebookFeedModalArrayList, MainActivity.this);\nRecyclerView instRV = findViewById(R.id.idRVInstaFeeds);// below line is for setting linear layout manager to our recycler view.\nLinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);// below line is to set layout \n// manager to our recycler view.\ninstRV.setLayoutManager(linearLayoutManager);// below line is to set adapter \n// to our recycler view.\ninstRV.setAdapter(adapter);\n}\n} catch (JSONException e) {\ne.printStackTrace();\n}\n}\n}, new Response.ErrorListener() {\n@Override\npublic void onErrorResponse(VolleyError error) {\nToast.makeText(MainActivity.this, \"Fail to get data with error \" + error, Toast.LENGTH_SHORT).show();\n}\n});\nmRequestQueue.add(jsonObjectRequest);\n}\n}Now run your app and see the output of the app.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210127131954/Build-a-Facebook-Like-Custom-RecyclerView-in-Android.mp4\nYou can check the project on the below link: https://github.com/ChaitanyaMunje/LibraryApp/tree/FacebookBranch"}, {"text": "\nDifference Between MVC and MVVM Architecture Pattern in Android\n\nDeveloping an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in the future. MVC (Model \u2014 View \u2014 Controller) and MVVM (Model \u2014 View \u2014 ViewModel) are the two most popular android architectures among developers.\nThe Model\u2014View\u2014Controller(MVC) Pattern\nThe MVC pattern suggests splitting the code into 3 components. While creating the class/file of the application, the developer must categorize it into one of the following three layers:Model: This component stores the application data. It has no knowledge about the interface. The model is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: It is the UI(User Interface) layer that holds components that are visible on the screen. Moreover, it provides the visualization of the data stored in the Model and offers interaction to the user.\nController: This component establishes the relationship between the View and the Model. It contains the core application logic and gets informed of the user\u2019s response and updates the Model as per the need.The Model \u2014 View \u2014 ViewModel (MVVM) Pattern\nMVVM pattern has some similarities with the MVP(Model \u2014 View \u2014 Presenter) design pattern as the Presenter role is played by the ViewModel. However, the drawbacks of the MVP pattern has been solved by MVVM. It suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. The separate code layers of MVVM are:Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.\nView: The purpose of this layer is to inform the ViewModel about the user\u2019s action. This layer observes the ViewModel and does not contain any kind of application logic.\nViewModel: It exposes those data streams which are relevant to the View. Moreover, it servers as a link between the Model and the View.Difference Between MVC and MVVM Design PatternMVC(Model View Controller)MVVM(Model View ViewModel)Oldest android app architecture.\nIndustry-recognized architecture pattern for applications.User Inputs are handled by the Controller.\nThe View takes the input from the user and acts as the entry point of the application.Controller and View exist with the one-to-many relationship. One Controller can select different View based upon required operation.\nMultiple View can be mapped with single ViewModel and thus, the one-to-many relationship exists between View and ViewModel.The View has no knowledge about the Controller.\nThe View has reference to the ViewModel.This architecture has high dependency on the Android APIs.\nHas low or no dependency on the Android APIs.Difficult to make changes and modify the app features as the code layers are tightly coupled.\nEasy to make changes in application. However, if data binding logic is too complex, it will be a little harder to debug the application.Limited support to Unit testing.\nUnit testability is highest in this architecture.It does not follow modular and single responsibility principle.\nFollows modular and single responsibility principle.Overall, the main difference between MVC and MVVM is the role of the mediator component. In MVC, the Controller serves as the mediator between the View and the Model, while in MVVM, the ViewModel serves as the mediator between the View and the Model. MVC is a simpler pattern, while MVVM is more flexible and allows for a cleaner separation of concerns between the different layers of the application. While both MVC and MVVM are useful patterns for organizing the code for a software application, MVVM offers a number of advantages over MVC, here are a few of them:Improved separation of concerns: In MVVM, the ViewModel serves as a mediator between the View and the Model, which allows for a cleaner separation of concerns between the different layers of the application. This can make it easier to maintain and modify the codebase over time.\nBetter testability: Because the ViewModel is responsible for exposing the data and logic of the Model to the View, it can be easier to test the ViewModel separately from the View. This can make it easier to ensure that the application is functioning correctly and can make it easier to identify and fix bugs.\nGreater flexibility: The ViewModel in MVVM is more flexible than the Model in MVC, as it can expose data and logic from the Model in a way that is easier for the View to consume. This can make it easier to create different views for the same data and logic, or to reuse the same ViewModel with multiple views.\nBetter support for multiple developers: Because the MVVM pattern allows for a cleaner separation of concerns between the different layers of the application, it can be easier for multiple developers to work on different parts of the codebase concurrently. This can improve the efficiency of the development process and reduce the risk of conflicts between different parts of the codebase."}, {"text": "\nRecyclerView as Staggered Grid in Android With Example\n\nGridView: A ViewGroup that shows the items in a two-dimensional scrolling grid. In Grid View, each grid is of the same size .i.e., the height and width of each grid are equal. It shows symmetric items in the views.Staggered GridView: This ViewGroup is the extension of Grid View. In this view, the Grid is of varying size .i.e., their height and width may vary. It shows asymmetric items in the views. It automatically sets the item views according to its height and width.In order to use RecyclerView for creating staggering grid views, we need to use StaggeredGridLayoutManager. LayoutManager is responsible for measuring and positioning item views in the RecyclerView and also recycle the item views when they are no longer visible to the user. There are three types of built-in layout managers.LinearLayoutManager: It is used to show item views in a vertical and horizontal list.\nGridLayoutManager: It is used to show item views grid views.\nStaggeredLayoutManager: It is used to show item views in staggered views.We can also create a custom layout manager by RecyclerView.LayoutManager class.\nStaggeredGridLayoutManager(int spanCount, int orientation)Creates staggered grid layout with given parameters\nThe first parameter, spanCount is used to set the number of columns in a vertical orientation or the number of rows in the horizontal orientation\nThe second parameter, orientation is used to set the vertical or horizontal orientationStaggered Grid with Vertical OrientationRecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);\n// staggeredGridLayoutManager with 3 columns and vertical orientation\nStaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);\n// setting recycler view layout to staggered grid\nrecyclerView.setLayoutManager(staggeredGridLayoutManager);Staggered Grid with Horizontal OrientationRecyclerView recyclerView = (RecyclerView)findViewById(R.id.recyclerView);\n// staggeredGridLayoutManager with 3 rows and horizontal orientation\nStaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL);\n// setting recycler view layout to staggered grid\nrecyclerView.setLayoutManager(staggeredGridLayoutManager);Example\nIn this example, we would store data into ArrayList which is used for populating RecyclerView. After that we set the layout manager of RecyclerView as a staggered grid view and then, we set the Adapter for RecyclerView to show item views. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Adding dependencies\nWe are going to use the RecyclerView. So, we need to add the dependency of it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now.dependencies {\n implementation \u2018androidx.recyclerview:recyclerview:1.1.0\u2019\n}Before moving further let\u2019s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.XML \n#0F9D58 \n#16E37F \n#03DAC5 \n Step 3: Working with the activity_main.xml file\nIn this step, we will create a RecyclerView layout in the activity_main.xml file. Go to app > res > layout > activity_main.xml and add the following code snippet.XML \n \n Step 4: Create a new layout file list_item.xml for the list items of RecyclerView\nGo to the app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml layout file contains an ImageView which is used for populating the rows of RecyclerView.XML \n \n Step 5: Creating Adapter class for RecyclerView\nNow, we will create an Adapter.java class that will extend the RecyclerView.Adapter with ViewHolder. Go to the app > java > package > right-click and create a new java class and name it as Adapter. In Adapter class we will override the onCreateViewHolder() method which will inflate the list_item.xml layout and pass it to View Holder. Then onBindViewHolder() method where we set data to the Views with the help of View Holder. Below is the code snippet for Adapter.java class.Java import android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.ImageView; \nimport androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; \nimport java.util.ArrayList; // Extends the Adapter class to RecyclerView.Adapter \n// and implement the unimplemented methods \npublic class Adapter extends RecyclerView.Adapter { \nArrayList images; \nContext context; // Constructor for initialization \npublic Adapter(Context context, ArrayList images) { \nthis.context = context; \nthis.images = images; \n} @NonNull\n@Override\npublic Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \n// Inflating the Layout(Instantiates list_item.xml layout file into View object) \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); // Passing view to ViewHolder \nAdapter.ViewHolder viewHolder = new Adapter.ViewHolder(view); \nreturn viewHolder; \n} // Binding data to the into specified position \n@Override\npublic void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) { \n// TypeCast Object to int type \nint res = (int) images.get(position); \nholder.images.setImageResource(res); \n} @Override\npublic int getItemCount() { \n// Returns number of items currently available in Adapter \nreturn images.size(); \n} // Initializing the Views \npublic class ViewHolder extends RecyclerView.ViewHolder { \nImageView images; public ViewHolder(View view) { \nsuper(view); \nimages = (ImageView) view.findViewById(R.id.imageView); \n} \n} \n}Step 6: Working with the MainActivity.java file\nIn MainActivity.java class we create an ArrayList for storing images. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of these. And then we get the reference RecyclerView and set the LayoutManager as StaggeredGridLayoutManager and Adapter, to show items in RecyclerView. Below is the code for the MainActivity.java file.Java import android.os.Bundle; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; \nimport androidx.recyclerview.widget.StaggeredGridLayoutManager; \nimport java.util.ArrayList; \nimport java.util.Arrays; public class MainActivity extends AppCompatActivity { RecyclerView recyclerView; // Using ArrayList to store images data \nArrayList images = new ArrayList<>(Arrays.asList(R.drawable.img_1, R.drawable.img_2, R.drawable.img_3, \nR.drawable.img_4, R.drawable.img_5, R.drawable.img_6, R.drawable.img_7, R.drawable.img_8, \nR.drawable.img_9, R.drawable.img_10)); @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Getting reference of recyclerView \nrecyclerView = (RecyclerView) findViewById(R.id.recyclerView); // Setting the layout as Staggered Grid for vertical orientation \nStaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL); \nrecyclerView.setLayoutManager(staggeredGridLayoutManager); // Sending reference and data to Adapter \nAdapter adapter = new Adapter(MainActivity.this, images); // Setting Adapter to RecyclerView \nrecyclerView.setAdapter(adapter); \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201113000122/RecyclerView-as-Staggered-Grid-in-Android.mp4"}, {"text": "\nJSON Parsing in Android\n\nJSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server\u2019s data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language. Android supports all the JSON classes such as JSONStringer, JSONObject, JSONArray, and all other forms to parse the JSON data and fetch the required information by the program. JSON\u2019s main advantage is that it is a language-independent, and the JSON object will contain data like a key/value pair. In general, JSON nodes will start with a square bracket ([) or with a curly bracket ({). The square and curly bracket\u2019s primary difference is that the square bracket ([) represents the beginning of a JSONArray node. Whereas, the curly bracket ({) represents a JSONObject. So one needs to call the appropriate method to get the data. Sometimes JSON data start with [. We then need to use the getJSONArray() method to get the data. Similarly, if it starts with {, then we need to use the getJSONobject() method. The syntax of the JSON file is as following:\n{ \n\"Name\": \"GeeksforGeeks\", \n\"Estd\": 2009, \n\"age\": 10, \n\"address\": { \n \"buildingAddress\": \"5th & 6th Floor Royal Kapsons, A- 118\", \n \"city\": \"Sector- 136, Noida\", \n \"state\": \"Uttar Pradesh (201305)\", \n \"postalCode\": \"201305\"\n}, In this article, we are going to parse a JSON file in Android. Note that we are going toimplement this project using theKotlinlanguage.\nStep by Step Implementation\nTo parse a JSON file in Android, follow the following steps:\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.\nStep 2: Working with the activity_main.xml file\nGo to the activity_main.xml file which represents the UI of the application. Create a ListView as shown. Below is the code for theactivity_main.xml file.XML \n \n Step 3: Create another layout resource file\nGo to app > res > layout > right-click > New > Layout Resource File and create another layout list_row.xml to show the data in the ListView. Below is the code for thelist_row.xml file.XML \n \n \n \n \n Step 4: Working with the MainActivity.kt file\nGo to the MainActivity.kt file, and refer to the following code. Below is the code for theMainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.os.Bundle \nimport android.util.Log \nimport android.widget.ListAdapter \nimport android.widget.ListView \nimport android.widget.SimpleAdapter \nimport androidx.appcompat.app.AppCompatActivity \nimport org.json.JSONException \nimport org.json.JSONObject \nimport java.util.* class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // private string declare in the latter section of the program \nval jsonStr = listData \ntry { // Create a userList string hashmap arraylist \nval userList = ArrayList>() // Declaring the listView from the layout file \nval lv = findViewById(R.id.user_list) // Initializing the JSON object and extracting the information \nval jObj = JSONObject(jsonStr) \nval jsonArry = jObj.getJSONArray(\"users\") \nfor (i in 0 until jsonArry.length()) { \nval user = HashMap() \nval obj = jsonArry.getJSONObject(i) \nuser[\"name\"] = obj.getString(\"name\") \nuser[\"designation\"] = obj.getString(\"designation\") \nuser[\"location\"] = obj.getString(\"location\") \nuserList.add(user) \n} // ListAdapter to broadcast the information to the list elements \nval adapter: ListAdapter = SimpleAdapter( \nthis, userList, R.layout.list_row, \narrayOf(\"name\", \"designation\", \"location\"), intArrayOf( \nR.id.name, \nR.id.designation, R.id.location \n) \n) \nlv.adapter = adapter \n} catch (ex: JSONException) { \nLog.e(\"JsonParser Example\", \"unexpected JSON exception\", ex) \n} \n} // JSON object in the form of input stream \nprivate val listData: String \nget() = (\"{ \\\"users\\\" :[\" + \n\"{\\\"name\\\":\\\"Ace\\\",\\\"designation\\\":\\\"Engineer\\\",\\\"location\\\":\\\"New York\\\"}\" + \n\",{\\\"name\\\":\\\"Tom\\\",\\\"designation\\\":\\\"Director\\\",\\\"location\\\":\\\"Chicago\\\"}\" + \n\",{\\\"name\\\":\\\"Tim\\\",\\\"designation\\\":\\\"Charted Accountant\\\",\\\"location\\\":\\\"Sunnyvale\\\"}] }\") \n}Output: Run on Emulator"}, {"text": "\nHorizontalScrollView in Kotlin\n\nIn Android ScrollView allows multiple views that are places within the parent view group to be scrolled. Scrolling in the android application can be done in two ways either Vertically or Horizontally.\nIn this article, we will be discussing how to create a Horizontal ScrollView in Kotlin .XML Attributes\nDescriptionandroid:fillViewport\nIt defines whether the horizontal scrollview should stretch its content to fill the viewport.android:layout_height\nSets the height of the horizontal scroll view android:layout_width \nSets the width of the horizontal scroll viewandroid:src\nSets background of the imageandroid:id\nSets unique id of the viewLet\u2019s start by first creating a project in Android Studio. To do so, follow these instructions:\nFirst step is to create a new Project in Android Studio. For this follow these steps:Click on File, then New and then New Project and give name whatever you like\nThen, select Kotlin language Support and click next button.\nSelect minimum SDK, whatever you need\nSelect Empty activity and then click finish.Modify activity_main.xml file \n \n Add Images\nWe need to add some images which can be used for scrolling purpose. So, we have to copy the images from our local computer path to app/res/mipmap folder.\nNote: We have added the images to mipmap folder instead of drawable folder because the size of the images is very large. \nCreate HorizontalScrollView in MainActivity.kt file\nOpen app/src/main/java/yourPackageName/MainActivity.kt and do the following changes: package com.geeksforgeeks.myfirstKotlinapp import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} \n} AndroidManifest.xml file \n \n \n \n \n \n \n Run as Emulator: https://media.geeksforgeeks.org/wp-content/uploads/20191125223135/HScroll.mp4"}, {"text": "\nHow to Add RangeSeekbar in Android Using Kotlin?\n\nIn this article, RangeSeekbar is implemented in an application in android. Android Seekbar is a type of progress bar. We can drag the seekbar from left to right and vice versa and hence changes the current progress. Here we use the RangeSeekbar library to add custom seekbar in our app. This library provides us various features like steps, mode, thumbDrawable, etc which makes it way better than seekbar provided by android.\nApproach\nStep 1: Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bitbucket can be directly used in the application.XML allprojects { \nrepositories { \nmaven { url 'https://jitpack.io' } \n} \n} Step 2: Add the support library in build.gradle file and add the dependency in the dependencies section. Through this directly RangeSeekbar will be used in the XML.XML dependencies { \nimplementation 'com.github.Jay-Goo:RangeSeekBar:v3.0.0' \n} Step 3: Create a string-array in strings.xml file present in the values folder.strings.xml \n- Lv1
\n- Lv2
\n- Lv3
\n- Lv4
\n- Lv5
\n Step 4: Add the following code in the activity_main.xml file. In this file, seekbar is added to the layout and the important tag like steps, thumbDrawable, mode, and many more are added according to the requirement.activity_main.xml \n Step 5: Add the following code in MainActivity.kt file. Here setOnRangeChangedListener is added with the seekbar. It is invoked when the user changes the seekbar bar and shows the percentage of progress to which it is changed.MainActivity.kt package org.geeksforgeeks.rangeseekbar import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.widget.Toast \nimport com.jaygoo.widget.OnRangeChangedListener \nimport com.jaygoo.widget.RangeSeekBar \nimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) //whenever we change progress of seekbar this function \n//get invoked automatically. \nrange_seekbar?.setOnRangeChangedListener(object : \nOnRangeChangedListener { \noverride fun onRangeChanged( \nrangeSeekBar: RangeSeekBar, leftValue: Float, \nrightValue: Float, isFromUser: Boolean) { \nToast.makeText(this@MainActivity, \nleftValue.toString(),Toast.LENGTH_LONG).show() \n} override fun onStartTrackingTouch(view: RangeSeekBar?, \nisLeft: Boolean) { \n} override fun onStopTrackingTouch(view: RangeSeekBar?, \nisLeft: Boolean) { \n} \n}) \n} \n} Output:https://media.geeksforgeeks.org/wp-content/uploads/20200713231823/2020_07_09_22_00_22_trim1.mp4\nRefer to the official documentation for more information."}, {"text": "\nViewPager Using Fragments in Android with Example\n\nViewPager is a layout manager that allows the user to flip left and right through pages of data. It is mostly found in apps like Youtube, Snapchat where the user shifts right \u2013 left to switch to a screen. Instead of using activities fragments are used. It is also used to guide the user through the app when the user launches the app for the first time.\nViewPager Using Fragments in Android\nSteps for implementing viewpager:Adding the ViewPager widget to the XML layout (usually the main_layout).\nCreating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class.An adapter populates the pages inside the Viewpager. PagerAdapter is the base class which is extended by FragmentPagerAdapter and FragmentStatePagerAdapter. Let\u2019s see a quick difference between the two classes.\nDifference between FragmentPagerAdapter and FragmentStatePagerAdapter:FragmentStatePagerAdapter: Keeps in memory only the current fragment displayed on the screen. This is memory efficient and should be used in applications with dynamic fragments. (where the number of fragments is not fixed.).\nFragmentPagerAdapter: This adapter should be used when the number of fragments is fixed. An application that has 3 tabs which won\u2019t change during the runtime of the application. This tutorial will be using FragmentPagerAdapter.Following is the structure of the ViewPagerAdapter Class:Java import androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\nimport androidx.fragment.app.FragmentManager;\nimport androidx.fragment.app.FragmentPagerAdapter;\nimport java.util.ArrayList;\nimport java.util.List;public class ViewPagerAdapter extends FragmentPagerAdapter {private final List fragments = new ArrayList<>();\nprivate final List fragmentTitle = new ArrayList<>();public ViewPagerAdapter(@NonNull FragmentManager fm)\n{\nsuper(fm);\n}public void add(Fragment fragment, String title)\n{\nfragments.add(fragment);\nfragmentTitle.add(title);\n}@NonNull @Override public Fragment getItem(int position)\n{\nreturn fragments.get(position);\n}@Override public int getCount()\n{\nreturn fragments.size();\n}@Nullable\n@Override\npublic CharSequence getPageTitle(int position)\n{\nreturn fragmentTitle.get(position);\n}\n}Method Description:getCount(): This method returns the number of fragments to display. (Required to Override)\ngetItem(int pos): Returns the fragment at the pos index. (Required to override)\nViewPagerAdapter(@NonNull FragmentManager FM): (required) The ViewPager Adapter needs to have a parameterized constructor that accepts the FragmentManager instance. Which is responsible for managing the fragments. A FragmentManager manages Fragments in Android, specifically, it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments.\ngetPageTitle(int pos): (optional) Similar to getItem() this methods returns the title of the page at index pos.\nadd(Fragment fragment, String title): This method is responsible for populating the fragments and fragmentTitle lists. which hold the fragments and titles respectively.Example\nA sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Initially, the project directory should look like this.Step 2: Working with the activity_main.xml fileThe three widgets AppBarLayout used to host the TabLayout which is responsible for displaying the page titles. ViewPager layout which will house the different fragments. The below Image explains the important parameters to set to get the app working as intended.In the TabLayout we need to add the tabmode = \u201cfixed\u201d parameter which tells the android system that will have a fixed number of tabs in our application. Add the following code to the \u201cactivity_main.xml\u201d file.XML \n Step 3: Create Fragments\nNow we need to design out pages that are fragmented. For this tutorial, we will be using three Pages (fragments). Add three blank fragments to the project. The project Structure should look like this. Below is the code for the Page1.java, Page2.java, and Page3.java file respectively.Java import android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;public class Page1 extends Fragment {public Page1() {\n// required empty public constructor.\n}@Override\npublic void onCreate(@Nullable Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\n}@Nullable\n@Override\npublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\nreturn inflater.inflate(R.layout.fragment_page1, container, false);\n}\n}Java import android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;public class Page2 extends Fragment {public Page2() {\n// required empty public constructor.\n}@Override\npublic void onCreate(@Nullable Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\n}@Nullable\n@Override\npublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\nreturn inflater.inflate(R.layout.fragment_page2, container, false);\n}\n}Java import android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;public class Page3 extends Fragment {public Page3() {\n// required empty public constructor.\n}@Override\npublic void onCreate(@Nullable Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\n}@Nullable\n@Override\npublic View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\nreturn inflater.inflate(R.layout.fragment_page3, container, false);\n}\n}Method Description:Page1(): Default Constructure.\nonCreateView( onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState): This method is responsible for inflating (parsing) the respective XML file and return the view which is added to the ViewPager adapter.\nonCreate(Bundle SaveInstanceState): This methods is similar to activities OnCreate() method.Designing the Page XML Files. All the fragments XML layouts have the same designs. We have a TextView at the center displaying the name of the respective page, the root container used here is FrameLayout whose background is set to #0F9D58\nBelow is the code for the fragment_page1.xml file:Code:XML \n\n \n Below is the code for the fragment_page2.xml file:Code:XML \n\n \n Below is the code for the fragment_page3.xml file:Code:XML \n\n \n Step 4: Creating the ViewPager Adapter\nAdd a java class named ViewPagerAdapter to the project structure. The project structure would look like this.Below is the code for the ViewPagerAdapter.java file: Java import androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.Fragment;\nimport androidx.fragment.app.FragmentManager;\nimport androidx.fragment.app.FragmentPagerAdapter;\nimport java.util.ArrayList;\nimport java.util.List;public class ViewPagerAdapter extends FragmentPagerAdapter {private final List fragments = new ArrayList<>();\nprivate final List fragmentTitle = new ArrayList<>();public ViewPagerAdapter(@NonNull FragmentManager fm) {\nsuper(fm);\n}public void add(Fragment fragment, String title) {\nfragments.add(fragment);\nfragmentTitle.add(title);\n}@NonNull\n@Override\npublic Fragment getItem(int position) {\nreturn fragments.get(position);\n}@Override\npublic int getCount() {\nreturn fragments.size();\n}@Nullable\n@Override\npublic CharSequence getPageTitle(int position) {\nreturn fragmentTitle.get(position);\n}\n}Step 5: Working with the MainActivity.java file\nIn the MainActivity, we need to perform the following steps. Initialize the ViewPager, TabLayout, and the Adapter.\nAdd the Pages (fragments ) along with the titles\nLink the TabLayout to the Viewpager using the setupWithiewPager method.Syntax:TabLayout.setupWithiewPager(ViewPager pager).\nDescription: The tablayout with the viewpager. The titles of each pager now appears on the tablayout. The user can also navigate through the fragments by clicking on the tabs.\nParameter:\nViewpager: Used to display the fragments.Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.viewpager.widget.ViewPager;\nimport com.google.android.material.tabs.TabLayout;public class MainActivity extends AppCompatActivity {private ViewPagerAdapter viewPagerAdapter;\nprivate ViewPager viewPager;\nprivate TabLayout tabLayout;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);viewPager = findViewById(R.id.viewpager);// setting up the adapter\nviewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());// add the fragments\nviewPagerAdapter.add(new Page1(), \"Page 1\");\nviewPagerAdapter.add(new Page2(), \"Page 2\");\nviewPagerAdapter.add(new Page3(), \"Page 3\");// Set the adapter\nviewPager.setAdapter(viewPagerAdapter);// The Page (fragment) titles will be displayed in the\n// tabLayout hence we need to set the page viewer\n// we use the setupWithViewPager().\ntabLayout = findViewById(R.id.tab_layout);\ntabLayout.setupWithViewPager(viewPager);\n}\n}Output: https://media.geeksforgeeks.org/wp-content/uploads/20201108145106/viewPager.mp4\nFind the code in the following GitHub repo: https://github.com/evilc3/ViewPager"}, {"text": "\nWheelView in Android\n\nIn this article, WheelView is added in android. WheelView provides a very impressive UI that allows the developer to create a Wheel and add items according to his need. Some important tags provided by WheelView are wheelArcBackgroundColor, wheelAnchorAngle, wheelStartAngle, wheelMode, wheelCenterIcon, and many more. It can be used where the user wants to select items from a list of items. Suppose in the banking app, the user has the option to select its bank account to check balance, payment history, etc in that case this can be used.\nAdvantages:It can be customized according to the requirements.\nIt provides animation with the view which improves the User Interface.\nIt provides an inbuilt layout that its alternatives like Custom Dialog which can be used instead of wheel view does not provide.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.\nStep 2: Add dependency and JitPack Repository\nNavigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation \u2018com.github.psuzn:WheelView:1.0.1\u2019Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.allprojects {\nrepositories {\n \u2026\n maven { url \u201chttps://jitpack.io\u201d }\n }\n}After adding this dependency sync your project and now we will move towards its implementation. \nStep 3: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML Step 4: Working with the MainActivityfile\nGo to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.Java import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport java.util.Arrays;\nimport me.sujanpoudel.wheelview.WheelView;public class MainActivity extends AppCompatActivity {@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// create a string array of tiles\nString[] titles={\"Bubble Sort\", \"Quick Sort\", \"Merge Sort\", \"Radix Sort\"};// get the reference of the wheelView\nWheelView wheelView =(WheelView)findViewById(R.id.wheel_view);// convert tiles array to list and pass it to setTitles \nwheelView.setTitles(Arrays.asList(titles));\n}\n}Kotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport me.sujanpoudel.wheelview.WheelView class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) val wheelView = findViewById(R.id.wheel_view) \nwheelView.titles = listOf(\"Bubble Sort\", \"Quick Sort\", \"Merge Sort\", \"Radix Sort\") \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200718132250/Record_2020-07-18-13-21-50_69fa71ed7e998de6cab47c8740bea3c11.mp4"}, {"text": "\nHow to add a Snackbar in Android\n\nSnackbar provides lightweight feedback about an operation. The message appears at the bottom of the screen on mobile and lower left on larger devices. Snackbar appears above all the elements of the screen. But no component is affected by it. Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets. Snackbar is similar to Toast but the only major difference is that an action can be added with Snackbar.\nApproach:Add the support Library in build.gradle file and add Material Design dependency in the dependencies section.It is a part of Material Design that\u2019s why we have to add a dependency. dependencies { \nimplementation 'com.google.android.material:material:1.1.0' \n} Now add the following code in the activity_main.xml file. It will create a button named Open Snackbar.activity_main.xml \n Now add the following code in the MainActivity.java file. This will define the button and add a onClickListener to the button. In the onClickListener a Snackbar is created and is called. So whenever the button is clicked, the onClickListener creates a snackbar and calls it and the user sees the message. This snackbar contains an action and if clicked will show a toast.MainActivity.java package org.geeksforgeeks.gfgsnackbar; import androidx.appcompat.app.AppCompatActivity; \nimport androidx.coordinatorlayout \n.widget.CoordinatorLayout; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.Toast; import com.google.android.material \n.snackbar \n.Snackbar; public class MainActivity \nextends AppCompatActivity { Button button; \nCoordinatorLayout layout; @Override\nprotected void onCreate( \nBundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); button = findViewById(R.id.button); \nlayout = findViewById(R.id.layout); button.setOnClickListener( \nnew View.OnClickListener() { \n@Override\npublic void onClick(View v) \n{ // Create a snackbar \nSnackbar snackbar \n= Snackbar \n.make( \nlayout, \n\"Message is deleted\", \nSnackbar.LENGTH_LONG) \n.setAction( \n\"UNDO\", // If the Undo button \n// is pressed, show \n// the message using Toast \nnew View.OnClickListener() { \n@Override\npublic void onClick(View view) \n{ \nToast \n.makeText( \nMainActivity.this, \n\"Undo Clicked\", \nToast.LENGTH_SHORT) \n.show(); \n} \n}); snackbar.show(); \n} \n}); \n} \n} Output:https://media.geeksforgeeks.org/wp-content/uploads/20200505003945/Record_2020-05-05-00-35-43_6f6ad7a6a32d4495fc2b19b76a14ac9e1.mp4"}, {"text": "\nFrameLayout in Android\n\nAndroid Framelayout is a ViewGroup subclass that is used to specify the position of multiple views placed on top of each other to represent a single view screen. Generally, we can say FrameLayout simply blocks a particular area on the screen to display a single view. Here, all the child views or elements are added in stack format means the most recently added child will be shown on the top of the screen. But, we can add multiple children\u2019s views and control their positions only by using gravity attributes in FrameLayout.\nThe FrameLayout can be defined using the code below:\n\n // Add items or widgets here\n \nStep By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail. In this file, we declare the FrameLayout and start adding multiple views like textView, editText, Button, etc. All the views are placed on each other but we displace them according to our requirements. First, we add an image in the background and add other widgets on the top. On the screen, we can see the beautiful login page having an image in the background.XML \n \n Step 3: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. When we have created the layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element from the XML using findViewById.Kotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.widget.EditText \nimport android.widget.TextView class MainActivity : AppCompatActivity() { private lateinit var textView: TextView \nprivate lateinit var editText1: EditText \nprivate lateinit var editText2: EditText override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n// finding the UI elements textView = findViewById(R.id.txtvw1) \neditText1 = findViewById(R.id.editText1); \neditText2 = findViewById(R.id.editText2); \n} \n}Java import android.os.Bundle; \nimport android.widget.EditText; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { TextView textView; \nEditText editText1, editText2; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \n// finding the UI elements textView = findViewById(R.id.txtvw1); \neditText1 = findViewById(R.id.editText1); \neditText2 = findViewById(R.id.editText2); \n} \n}Output:\nWe need to run using Android Virtual Device(AVD) to see the output."}, {"text": "\nHow to create a COVID-19 Tracker Android App\n\nThe world is facing one of the worst epidemics, the outbreak of COVID-19, you all are aware of that. So during this lockdown time let\u2019s create a COVID-19 Tracker Android App using REST API which will track the Global Stats only.\nPre-requisites:\nAndroid App Development Fundamentals for BeginnersGuide to Install and Set up Android StudioAndroid | How to Create/Start a New Project in Android Studio?Android | Running your first Android appREST API (Introduction)Volley Library in AndroidStep by Step Implementation to Create Covid-19 Tracker Android ApplicationStep1: Opening a New ProjectOpen a new project just click of File option at topmost corner in left.Then click on new and open a new project with whatever name you want.Now we gonna work on Empty Activity with language as Java. Leave all other options as untouched.You can change the name of project as per your choice.By default, there will be two files activity_main.xml and MainActivity.java.\nStep 2: Before going to the coding section first you have to do some pre-task.Go to Gradle Scripts->build.gradle (Module: app) section and import following dependencies and click the \u201csync Now\u201d on the above pop up.\nbuild.gradle (:app)dependencies { // Other dependencies... implementation 'com.android.volley:volley:1.2.1'}Go to app->manifests->AndroidManifests.xml section and allow \u201cInternet Permission\u201c.\nAndroidManifests.xml Step3: Designing the UIBelow is the code for the xml file.activity_main.xml\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n After using this code in .xml file, the UI will be like:\nStep 4: Working with Java fileOpen the MainActivity.java file there within the class, first of all create the object of TextView class.\n// Create the object of TextView ClassTextView tvCases, tvRecovered, tvCritical, tvActive, tvTodayCases, tvTotalDeaths, tvTodayDeaths, tvAffectedCountries;\nSecondly inside onCreate() method, we have to link those objects with their respective id\u2019s that we have given in .XML file.\n// link those objects with their respective id\u2019s that we have given in .XML filetvCases = findViewById(R.id.tvCases);tvRecovered = findViewById(R.id.tvRecovered);tvCritical = findViewById(R.id.tvCritical);tvActive = findViewById(R.id.tvActive);tvTodayCases = findViewById(R.id.tvTodayCases);tvTotalDeaths = findViewById(R.id.tvTotalDeaths);tvTodayDeaths = findViewById(R.id.tvTodayDeaths);tvAffectedCountries = findViewById(R.id.tvAffectedCountries);\nCreate a private void fetchdata() method outside onCreate() method and define it.Inside fetchdata() method the most important task is going to happen that is how we fetch the data from a third party API and implement it in our app. My request is please read thoroughly the two articles Volley Library in Android and REST API (Introduction) to understand the following concepts.Create a String request using Volley Library and assign the \u201curl\u201d with \u201chttps://corona.lmao.ninja/v2/all\u201d link.\nJava// Create a String request using Volley Library\nString url = \"https:// corona.lmao.ninja/v2/all\";StringRequest request\n = new StringRequest(\n Request.Method.GET,\n url,\n new Response.Listener() {\n @Override\n public void onResponse(\n String response) {}\n },\n new Response.ErrorListener() {\n @Override\n public void onErrorResponse(\n VolleyError error) {}\n });RequestQueue requestQueue = Volley.newRequestQueue(this);\nrequestQueue.add(request);Please refer this website to take a look at the requested data are in JSON format.\nSo the next thing you have to do is, inside the onResponse() method create the object of \u201cJSONObject\u201d class then set the data in text view which are available in JSON format with the help of \u201cjsonobject\u201d. Make sure that you have to do these things inside a \u201ctry\u201d block. \nNote: Remember that the parameter inside the getString() must match with the name given in JSON format.Java// Handle the JSON object and handle it inside try and catchtry {\n // Creating object of JSONObject\n JSONObject jsonObject\n = new JSONObject(\n response.toString()); // Set the data in text view\n // which are available in JSON format\n // Note that the parameter\n // inside the getString() must match\n // with the name given in JSON format\n tvCases.setText(\n jsonObject.getString(\"cases\"));\n tvRecovered.setText(\n jsonObject.getString(\"recovered\"));\n tvCritical.setText(\n jsonObject.getString(\"critical\"));\n tvActive.setText(\n jsonObject.getString(\"active\"));\n tvTodayCases.setText(\n jsonObject.getString(\"todayCases\"));\n tvTotalDeaths.setText(\n jsonObject.getString(\"deaths\"));\n tvTodayDeaths.setText(\n jsonObject.getString(\"todayDeaths\"));\n tvAffectedCountries.setText(\n jsonObject.getString(\"affectedCountries\"));\n}\ncatch (JSONException e) {\n e.printStackTrace();\n}And inside onErrorResponse() method you have to show a toast message if any error occurred.\nToast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT) .show();At last invoke the fetchdata() method inside onCreate() method.\nfetchdata();Output:"}, {"text": "\nDatePickerDialog in Android\n\nAndroid DatePicker is a user interface control that is used to select the date by day, month, and year in the android application. DatePicker is used to ensure that the users will select a valid date. In android DatePicker having two modes, the first one shows the complete calendar and the second one shows the dates in the spinner view. One can create a DatePicker control in two ways either manually in the XML file or create it in the Activity file programmatically. We are going to do it programmatically by using Java.Note: To implement DatePicker using Kotlin please refer to this.Approach\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Working with activity_main.xml file\nIn the activity_main.xml file add only a TextView to display the selected date and a Button to select the date from the DatePickerDialog. Below is the complete code for the activity_main.xml file.XML \n Step 3: Create a new class and names as DatePicker\nNow create a new class by going to the package and right-click on it and select new and then Java Class. Name the class as DatePicker and its superclass as DialogFragment (androidx.fragment.app.DialogFragment) and click OK.Now override a method onCreateDialog and instead of returning super.onCreateDialog return an instance of DatePickerDialog.@NonNull\n @Override\n public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {\n return new DatePickerDialog();\n }Now pass parameters to the constructor of DatePickerDialog which requires context, OnDateSetListener, year, month, dayOfMonth.Pass the getActivity method for the context.\nFor OnDateSetListener typecast the getActivity method to OnDateSetListener.\nFor the year, month, and dayOfMonth create an instance of calendar class and assign the year, month, and dayOfMonth to variables of type int.\nPass year and month and dayOfMonth so that when the DatePickerDialog opens it has the current date.@NonNull\n@Override\npublic Dialog\nonCreateDialog(@Nullable Bundle savedInstanceState)\n{\n Calendar mCalendar = Calendar.getInstance();\n int year = mCalendar.get(Calendar.YEAR);\n int month = mCalendar.get(Calendar.MONTH);\n int dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);\n return new DatePickerDialog(\n getActivity(),\n (DatePickerDialog.OnDateSetListener)getActivity(),\n year, month, dayOfMonth);\n}Thecomplete code for the DatePicker.java class is given below.Java package tutorials.droid.datepicker;import android.app.DatePickerDialog;\nimport android.app.Dialog;\nimport android.os.Bundle;\nimport androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;\nimport androidx.fragment.app.DialogFragment;\nimport java.util.Calendar;public class DatePicker extends DialogFragment {\n@NonNull\n@Override\npublic Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {\nCalendar mCalendar = Calendar.getInstance();\nint year = mCalendar.get(Calendar.YEAR);\nint month = mCalendar.get(Calendar.MONTH);\nint dayOfMonth = mCalendar.get(Calendar.DAY_OF_MONTH);\nreturn new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener)\ngetActivity(), year, month, dayOfMonth);\n}\n}Step 4: Working with MainActivity.java file\nNow In the MainActivity.java file,create an object of both TextView and Button and map the components(TextView and Button) with their ids.TextView tvDate;\nButton btPickDate;\ntvDate = findViewById(R.id.tvDate);\nbtPickDate = findViewById(R.id.btPickDate);Implement OnDateSetListener of DatePickerDialog class and override onDateSet() method. The onDateSet() method will set the date after selection in the tvDate TextView.@Override\n public void onDateSet(DatePicker view, int year, int month, int dayOfMonth)\n{\n // Create a Calendar instance\n Calendar mCalendar = Calendar.getInstance();\n // Set static variables of Calendar instance\n mCalendar.set(Calendar.YEAR,year);\n mCalendar.set(Calendar.MONTH,month);\n mCalendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);\n // Get the date in form of string\n String selectedDate = DateFormat.getDateInstance(DateFormat.FULL).format(mCalendar.getTime());\n // Set the textview to the selectedDate String\n tvDate.setText(selectedDate);\n}In the onClick() method implement setOnClickListener of btPickDate. Create an instance of DatePicker(our class). Use the show method of the instance and pass getSupportFragmentManager() and a Tag. The complete code for the MainActivity.java file is given below.Java package tutorials.droid.datepicker;import android.app.DatePickerDialog;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.DatePicker;\nimport android.widget.TextView;\nimport androidx.appcompat.app.AppCompatActivity;\nimport java.text.DateFormat;\nimport java.util.Calendar;public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {\nTextView tvDate;\nButton btPickDate;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);\ntvDate = findViewById(R.id.tvDate);\nbtPickDate = findViewById(R.id.btPickDate);\nbtPickDate.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {\n// Please note that use your package name here\ntutorials.droid.datepicker.DatePicker mDatePickerDialogFragment;\nmDatePickerDialogFragment = new tutorials.droid.datepicker.DatePicker();\nmDatePickerDialogFragment.show(getSupportFragmentManager(), \"DATE PICK\");\n}\n});\n}@Override\npublic void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {\nCalendar mCalendar = Calendar.getInstance();\nmCalendar.set(Calendar.YEAR, year);\nmCalendar.set(Calendar.MONTH, month);\nmCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);\nString selectedDate = DateFormat.getDateInstance(DateFormat.FULL).format(mCalendar.getTime());\ntvDate.setText(selectedDate);\n}\n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200901000219/date-picker.mp4"}, {"text": "\nNestedScrollView in Android with Example\n\nNestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when we reached the end of the PDF there is an Ad below the pdf file. This is where NestedScrollView comes in. Normally this would be difficult to accomplish since the system would be unable to decide which view to scroll. Let\u2019s discuss a NestedScrollView in Android by taking an example.\nStep by Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the activity_main.xml File\nGo to the app > res > values > strings.xml and add two random text strings inside the strings.xml file to display those strings in the activity_main.xml file.XML \nGFG | NestedScrollView \nHadoop is a data processing tool used to process large size data over distributed \ncommodity hardware. The trend of Big Data Hadoop market is on the boom and it\u2019s \nnot showing any kind of deceleration in its growth. Today, industries are capable \nof storing all the data generated at their business at an affordable price just \nbecause of Hadoop. Hadoop helps the industry to know their customer\u2019s behavior, \ncustomers buying priorities i.e. what they loved the most, and click patterns, \netc. Hadoop provides personalized recommendations and personalizes ad targeting \nfeatures. Companies are generating thousands of petabytes of data every day so the \ndemand for Big Data professionals is very high. Even after a few years, Hadoop will \nbe considered as the must-learn skill for the data-scientist and Big Data Technology. \nCompanies are investing big in it and it will become an in-demand skill in the future. \nHadoop provides personalized recommendations and personalizes ad targeting features. \nCompanies are generating thousands of petabytes of data every day so the demand for Big \nData professionals is very high. Even after a few years, Hadoop will be considered as \nthe must-learn skill for the data-scientist and Big Data Technology. Companies are \ninvesting big in it and it will become an in-demand skill in the future. \n \nHumans are coming closer to the internet at a very fast rate. It means that the \nvolume of data Industries is gathering will increase as time passes because of more \nusers. Industry\u2019s are gradually analyzing the need for this useful information they \nare getting from their users. It is for sure that the data always tends to an increasing \npattern so the company\u2019s are eventually acquiring professionals skilled with Big Data \nTechnologies. According to NASSCOM, India\u2019s Big Data Market will reach 16 billion USD by \n2025 from 2 billion USD. The growth of smart devices in India is growing at a very huge \nrate that will cause growth in theBig Data Market. Since Big Data is growing the demand \nfor Big Data professionals will be high. Hadoop provides personalized recommendations and \npersonalizes ad targeting features. Companies are generating thousands of petabytes of data \nevery day so the demand for Big Data professionals is very high. Even after a few years, \nHadoop will be considered as the must-learn skill for the data-scientist and Big Data \nTechnology. Companies are investing big in it and it will become an in-demand skill in the future. \n \n In the activity_main.xml file\nAdd the NestedScrollView and inside NestedScrollView add a LinearLayout and inside LinearLayout add two TextView to display the strings which are created inside the strings.xml file and one Button between the TextView. Here is the code for the activity_main.xml file. One can add as many views inside the NestedScrollView\u2019s LinearLayoutXML \n \n \n \n \n \n \n \n Step 3: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Since there is no change in MainActivity File, So keep it as it is.Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; public class MainActivity extends AppCompatActivity { \n@Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \n} \n}Kotlin import android.os.Bundle \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200917114446/nested-scroll-view.mp4"}, {"text": "\nHow to Retrieve Data from the Firebase Realtime Database in Android?\n\nFirebase Realtime Database is the backend service which is provided by Google for handling backend tasks for your Android apps, IOS apps as well as your websites. It provides so many services such as storage, database, and many more. The feature for which Firebase is famous is for its Firebase Realtime Database. By using Firebase Realtime Database in your app you can give live data updates to your users without actually refreshing your app. So in this article, we will be creating a simple app in which we will be using Firebase Realtime Database and retrieve the data from Firebase Realtime database and will see the Realtime data changes in our app.\nWhat we are going to build in this article?\nWe will be building a simple Android application in which we will be displaying a simple Text View. Inside that TextView, we will be displaying data from Firebase. We will see how Real-time data changes happen in our app by actually changing data on the server-side. Note that we are going toimplement this project using theJavalanguage.Note: You may also refer to How to Save Data to the Firebase Realtime Database in Android?Step by Step Implementation\nStep 1: Create a new Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. \nStep 2: Connect your app to Firebase\nAfter creating a new project, navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.After completing this process you will get to see the below screen.Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle file and make sure that the below dependency is added in your dependencies section.implementation \u2018com.google.firebase:firebase-database:19.6.0\u2019If the above dependency is not added in your dependencies section. Add this dependency and sync your project. Now we will move towards the XML part of our app.\nStep 3: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n Step 4: Add internet permission in your AndroidManifest.xml file\nAdd the permission for the internet in the AndroidManifest.xml file.XML \n Step 5: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.widget.TextView;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.firebase.database.DataSnapshot;\nimport com.google.firebase.database.DatabaseError;\nimport com.google.firebase.database.DatabaseReference;\nimport com.google.firebase.database.FirebaseDatabase;\nimport com.google.firebase.database.ValueEventListener;public class MainActivity extends AppCompatActivity {// creating a variable for \n// our Firebase Database.\nFirebaseDatabase firebaseDatabase;// creating a variable for our \n// Database Reference for Firebase.\nDatabaseReference databaseReference;// variable for Text view.\nprivate TextView retrieveTV;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// below line is used to get the instance \n// of our Firebase database.\nfirebaseDatabase = FirebaseDatabase.getInstance();// below line is used to get \n// reference for our database.\ndatabaseReference = firebaseDatabase.getReference(\"Data\");// initializing our object class variable.\nretrieveTV = findViewById(R.id.idTVRetrieveData);// calling method \n// for getting data.\ngetdata();\n}private void getdata() {// calling add value event listener method\n// for getting the values from database.\ndatabaseReference.addValueEventListener(new ValueEventListener() {\n@Override\npublic void onDataChange(@NonNull DataSnapshot snapshot) {\n// this method is call to get the realtime\n// updates in the data.\n// this method is called when the data is \n// changed in our Firebase console.\n// below line is for getting the data from\n// snapshot of our database.\nString value = snapshot.getValue(String.class);// after getting the value we are setting\n// our value to our text view in below line.\nretrieveTV.setText(value);\n}@Override\npublic void onCancelled(@NonNull DatabaseError error) {\n// calling on cancelled method when we receive\n// any error or we are not able to get the data.\nToast.makeText(MainActivity.this, \"Fail to get data.\", Toast.LENGTH_SHORT).show();\n}\n});\n}\n}After adding this code to your app. Now go to Firebase and click on Go to console option which is on the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. Inside that screen click n Realtime Database in the left window. After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.In this project, we are adding our rules as true for reading as well as a write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.\nStep 6: Adding data in Firebase Console\nInside Firebase in the Data tab, you are getting to see the below screen. Hover your cursor on null and click on the \u201c+\u201d option on the right side and click on that option. After clicking on that option. Add the data as added in the below image. Make sure to add \u201cData\u201d in the Name field because we are setting our reference for Firebase as \u201cData\u201d in our code on line 55. So we have to set it to \u201cData\u201d. You can change your reference and also change it in the Database. Inside the value field, you can add any data you want. This will be the string which we are going to display inside our text view. After adding data click on the add button and your data will be added in Firebase and this data will be displayed in your app.After adding this data you will get to see the below screen: After adding this data run your app and see the output of the app:\nOutput:\nWhile testing your app you can change your value field in your Firebase console and you can get to see that it will also get updated in your app as well. So in this task, we do not have to refresh our app any time. As soon as we update the value in our Firebase it will get updated in our App as well. In the below video we have changed the data from Firebase and it is being updated in-app as well.https://media.geeksforgeeks.org/wp-content/uploads/20201229160759/Screenrecorder-2020-12-29-14-04-19-430.mp4"}, {"text": "\nImplement Zoom In or Zoom Out in Android\n\nZoom In and Zoom Out animations are used to enlarge and reduce the size of a view in Android applications respectively. These types of animations are often used by developers to provide a dynamic nature to the applications. Users also feel the changes happening in the application by watching these kinds of animations.XML Attributes of Scale Tag\nThe characteristics of Zoom In and Zoom Out animations are defined in the XML files by using scale tag.XML attribute\nDescriptionandroid:duration\nUsed to define the duration of the animation in millisecondandroid:fromXScale\nUsed to set initial size of the view in X-axisandroid:fromYScale\nUsed to set initial size of the view in Y-axisandroid:pivotX\nTo define the X coordinate of the point about which the object is being zoom in/outandroid:pivotY\nTo define the Y coordinate of the point about which the object is being zoom in/outandroid:toXScale\nUsed to set final size of the view in X-axisandroid:toYScale\nUsed to set final size of the view in Y-axisHow to Add Zoom In/Out Animation in Android\nThe following example demonstrates the steps involved in implementing Zoom In and Zoom Out animation to an image file. An image file will be added in the activity using ImageView.Note: Following steps are performed on Android Studio version 4.0Step 1: Create new projectClick on File, then New => New Project.\nSelect language as Kotlin.\nSelect the minimum SDK as per your need.Step 2: Modify activity_main.xml fileBelow is the code for activity_main.xml file to add a TextView, ImageView and two Buttons in an activity.\nFilename: activity_main.xmlXML \n \n Step 3: Define XML file for Zoom In and Zoom Out animation of the imageCreate a new directory in the res folder of the application through right-click on res => New => Android Resource Directory. Select Resource Type as anim and Directory name should also be anim. In this directory create 2 Animation Resource File namely zoom_in and zoom_out. These 2 files are the XML file which holds the details of the animation. Below is the code for both the file.\nFilename: zoom_in.xmlXML \n Filename: zoom_out.xmXML \n The android:fillAfter attribute under set tag is used to fix the final size of the image file until any other animation happens.Step 4: Modify MainActivity.kt fileBelow is the code for MainActivity.kt file to load and start the animation on the ImageView widget according to the button clicked by the user.\nFilename: MainActivity.ktJava package com.example.zomminoutimport android.os.Bundle\nimport android.view.animation.AnimationUtils\nimport android.widget.Button\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// assigning id of the button\n// which zoom in the image\nval buttonZoomIn: Button = findViewById(R.id.zoomInButton)// assigning id of the button\n// which zoom out the image\nval buttonZoomOut: Button = findViewById(R.id.zoomOutButton)// assigning id of imageview on\n// which zoom in/out will be performed\nval image: ImageView = findViewById(R.id.imageView)// actions to be performed when\n// \"Zoom In\" button is clicked\nbuttonZoomIn.setOnClickListener() {// loading the animation of\n// zoom_in.xml file into a variable\nval animZoomIn = AnimationUtils.loadAnimation(this,\nR.anim.zoom_in)\n// assigning that animation to\n// the image and start animation\nimage.startAnimation(animZoomIn)\n}// actions to be performed when\n// \"Zoom Out\" button is clicked\nbuttonZoomOut.setOnClickListener() {// loading the animation of\n// zoom_out.xml file into a variable\nval animZoomOut = AnimationUtils.loadAnimation(this,\nR.anim.zoom_out)// assigning that animation to\n// the image and start animation\nimage.startAnimation(animZoomOut)\n}\n}\n}Step 5: Modify strings.xml fileAll the strings which are used in the activity are listed in this file.\nFilename: strings.xmlXML \nZoomInOut \nZoom In/Out in Android \nZoom Out \nZoom In \n Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200718211127/Android_Zoom_In_Out_Recording.mp4"}, {"text": "\nConstraintLayout in Android\n\nConstraintLayout is similar to that of other View Groups which we have seen in Android such as RelativeLayout, LinearLayout, and many more. In this article, we will take a look at using ConstraintLayout in Android.\nImportant Attributes of ConstraintLayoutAttributes\nDescription\nandroid:idThis is used to give a unique ID to the layout.app:layout_constraintBottom_toBottomOfThis is used to constrain the view with respect to the bottom position.app:layout_constraintLeft_toLeftOfThis attribute is used to constrain the view with respect to the left position.app:layout_constraintRight_toRightOfThis attribute is used to constrain the view with respect to the right position.app:layout_constraintTop_toTopOfThis attribute is used to constrain the view with respect to the top position.app:layout_constraintHeight_max\nThis attribute is used to set the max height of view according to the constraints. \napp:layout_constraintHeight_min\nThis attribute is used to set the height of the view according to the constraints.\napp:layout_constraintHorizontal_weight\nThis attribute is used to set the weight horizontally of a particular view same as linear layouts.\napp:layout_constraintVertical_weight\nThis attribute is used to set the weight vertically of a particular view same as linear layouts.\nStep by Step Implementation for adding Constraint Layout in AndroidStep 1: Create a New ProjectTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Adding dependency for using Constraint Layout in AndroidNavigate to the app > Gradle scripts > build.gradle file and add the below dependency to it in the dependencies section.\nAdd the dependency:implementation \"androidx.constraintlayout:constraintlayout:2.1.4\"Now sync your project and we will move towards working with activity_main.xml.\nStep 3: Working with the activity_main.xml fileNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.\nUse the activity mentioned below in your application:\nactivity_main.xml\n As we are working only with layout files so we don\u2019t have to add any code in java or Kotlin file for MainActivity. After adding this code now we have to run the app to see the output of the app.\nOutput:\nAdvantages of using ConstraintLayout in AndroidConstraintLayout provides you the ability to completely design your UI with the drag-and-drop feature provided by the Android Studio design editor.It helps to improve the UI performance over other layouts.With the help of ConstraintLayout, we can control the group of widgets through a single line of code.With the help of ConstraintLayout, we can easily add animations to the UI components which we use in our app.It helps to manage the position and size of views without using nested layouts which improves performance and makes it easier.ConstraintLayout is more efficient than Linear orRelative layouts, especially for complex layouts, because ConstraintLayout uses a more efficient algorithm to calculate the positions and sizes of widgets.ConstraintLayout supports chains and barriers which helps to build complex ui.Disadvantages of using ConstraintLayoutWhen we use the Constraint Layout in our app, the XML code generated becomes a bit difficult to understand.In most of the cases, the result obtain will not be the same as we got to see in the design editor.Sometimes we have to create a separate layout file for handling the UI for the landscape mode.All views need proper contraints to achieve correct design.How ConstraintLayout differs from Linear Layout?Constraint Layout\nLinear Layout\nIn ConstraintLayout, we can position our UI components in any sort of order whether it may be horizontal or vertical. \nBut in the case of Linear Layout, we can only arrange our UI components either in a horizontal or in a vertical manner.\nIn Constraint Layout we have to arrange this UI component manually.\nIn Linear Layout provides usability with which we can equally divide all the UI components in a horizontal or vertical manner using weight sum\nIn Constraint layout if the UI component is not Constrained then the UI will not look the same as that of in design editor.\nIn Linear Layout the UI which is actually seen in the Design editor of Android Studio will be the same as that we will get to see in the app\nHow ConstraintLayout differs from RelativeLayout?Constraint Layout\nRelative Layout\nIn Constraint Layout, we have to add constraints to the view on all four sides\nIn Relative Layout we can simply align our UI component relative to its ID using the ids of UI components.\nIn Constraint layout if the UI component is not Constrained then the UI will not look same as that of in design editor.\nIn Relative Layout, the UI which is actually seen in the Design editor of Android Studio will be the same as that we will get to see in the app\nHow Constraint Layout differs from Grid Layout?Constraint Layout\nGrid Layout\nIn Grid Layout the UI components are only arranged in Grid Manner and we cannot arrange the UI components according to requirement\nConstraint Layout we can align UI components according to the requirement.\nIn Grid Layout, the UI which is actually seen in the Design editor of Android Studio will be the same as that we will get to see in the app\nConstraint layout if the UI component is not Constrained then the UI will not look same as that of in design editor.\nFeatures of ConstrainLayout in AndroidThere are various features associated with ConstraintLayout in Android mentioned below:\nConstrains in AndroidRatio in AndroidChains in AndroidNote :To access the full android application using ConstraintLayout check this repository:ConstraintLayout in Android Application\nClick Here to Learn How to Create Android Application\n"}, {"text": "\nTheming of Material Design EditText in Android with Example\n\nPrerequisite: Material Design EditText in Android with Examples\nIn the previous article Material Design EditText in Android with Examples Material design Text Fields offers more customization and makes the user experience better than the normal text fields. For example, Icon to clear the entire EditText field, helper text, etc. In this article, it\u2019s been discussed how we can customize Material design edit text fields. Have a look at the following image to get an idea of how Material design EditTexts can themed.Note: Now in this article we will only customize the Material design EditText and about implementation refer to the prerequisite article above. The Material design EditText comes under the Small Components.Steps to Theme the Material Design EditText\nWorking with the activity_main.xml fileXML \n \n \n Output UI: Run on EmulatorNow Customizing the EditText Fields by Overriding the Default Material DesignAs we have seen there are three types shaping the Material design components in the article Introduction to Material Design in Android. Those are Triangle edge, Cut corner, and Rounded corner.\nWorking with the styles.xml. Invoke the following code to customize the MDC EditText. Comments are added inside the code for better understanding.XML \n Output UI: Run on EmulatorThere are more attributes to set the radius for particular corners.boxCornerRadiusTopStartboxCornerRadiusTopEnd\nboxCornerRadiusBottomStartboxCornerRadiusBottomEndFollowing code and output is an example of the same. The code needs to be invoked inside styles.xml.XML \n Output UI: Run on Emulator"}, {"text": "\nNotifications in Android with Example\n\nNotification is a kind of message, alert, or status of an application (probably running in the background) that is visible or available in the Android\u2019s UI elements. This application could be running in the background but not in use by the user. The purpose of a notification is to notify the user about a process that was initiated in the application either by the user or the system. This article could help someone who\u2019s trying hard to create a notification for developmental purposes.\nNotifications could be of various formats and designs depending upon the developer. In General, one must have witnessed these four types of notifications:Status Bar Notification (appears in the same layout as the current time, battery percentage)\nNotification drawer Notification (appears in the drop-down menu)\nHeads-Up Notification (appears on the overlay screen, ex: Whatsapp notification, OTP messages)\nLock-Screen Notification (I guess you know it)In this article, we will be discussing how to produce notifications in Kotlin.\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.\nStep 2: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. In this step, we are going to design our layout page. Here, we will use the RelativeLayout to get the Scroll View from the Kotlin file. Below is the code for the activity_main.xml file.XML \n Step 3: Create a new empty activityReference article: How to Create Constructor, Getter/Setter Methods and New Activity in Android Studio using Shortcuts?Name the activity as afterNotification. When someone clicks on the notification, this activity will open up in our app that is the user will be redirected to this page. Below is the code for the activity_after_notification.xml file.XML \n Note 1: Without configuring Notification Channels, you cannot build notification for applications with Android API >=26. For them generating a notification channel is mandatory. Apps with API<26 don\u2019t need notification channels they just need notification builder. Each channel is supposed to have a particular behavior that will be applicable to all the notifications which are a part of it.Every channel will, therefore, have a Channel ID which basically will act as a unique identifier for this Channel which will be useful if the user wants to differentiate a particular notification channel. In contrast, the Notification builder provides a convenient way to set the various fields of a Notification and generate content views using the platform\u2019s notification layout template but is not able to target a particular notification channel.Note 2: If you have referred any other documentation or any other blog before this one, you might have noticed them appealing to implement the following dependency\u201ccom.android.support:support-compat:28.0.0\u201d. What I\u2019ve personally experienced is that there\u2019s no need to implement it, things go far and good without this also.Step 5: Working with the MainActivity.kt file\nGo to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.app.Notification\nimport android.app.NotificationChannel\nimport android.app.NotificationManager\nimport android.app.PendingIntent\nimport android.content.Context\nimport android.content.Intent\nimport android.graphics.BitmapFactory\nimport android.graphics.Color\nimport android.os.Build\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.RemoteViews\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {// declaring variables\nlateinit var notificationManager: NotificationManager\nlateinit var notificationChannel: NotificationChannel\nlateinit var builder: Notification.Builder\nprivate val channelId = \"i.apps.notifications\"\nprivate val description = \"Test notification\"override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// accessing button\nval btn = findViewById(R.id.btn)// it is a class to notify the user of events that happen.\n// This is how you tell the user that something has happened in the\n// background.\nnotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager// onClick listener for the button\nbtn.setOnClickListener {// pendingIntent is an intent for future use i.e after\n// the notification is clicked, this intent will come into action\nval intent = Intent(this, afterNotification::class.java)// FLAG_UPDATE_CURRENT specifies that if a previous\n// PendingIntent already exists, then the current one\n// will update it with the latest intent\n// 0 is the request code, using it later with the\n// same method again will get back the same pending\n// intent for future reference\n// intent passed here is to our afterNotification class\nval pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)// RemoteViews are used to use the content of\n// some different layout apart from the current activity layout\nval contentView = RemoteViews(packageName, R.layout.activity_after_notification)// checking if android version is greater than oreo(API 26) or not\nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\nnotificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)\nnotificationChannel.enableLights(true)\nnotificationChannel.lightColor = Color.GREEN\nnotificationChannel.enableVibration(false)\nnotificationManager.createNotificationChannel(notificationChannel)builder = Notification.Builder(this, channelId)\n.setContent(contentView)\n.setSmallIcon(R.drawable.ic_launcher_background)\n.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background))\n.setContentIntent(pendingIntent)\n} else {builder = Notification.Builder(this)\n.setContent(contentView)\n.setSmallIcon(R.drawable.ic_launcher_background)\n.setLargeIcon(BitmapFactory.decodeResource(this.resources, R.drawable.ic_launcher_background))\n.setContentIntent(pendingIntent)\n}\nnotificationManager.notify(1234, builder.build())\n}\n}\n}With this, we have now successfully created a \u201cNotification\u201d for our application. Note that the parameters listed in the above code are required and the absence of any single parameter could result in crashing or not starting the application. The content title, content text, small icon are customizable parameters but are mandatory also. One can change their values according to the requirement.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20191104235951/noti.mp4"}, {"text": "\nMore Functionalities of Material Design Date Picker in Android\n\nAs discussed in the Material Design Date Picker in Android it offers many functionalities to users and is easy to implement for developers. So in this article, we are going to discuss more functionalities of material design date picker with examples. Note that the UI part will be the same as in the Part-1 article. We are going to work with the Java file only. \nFunctionality 1: Block all the dates before today\u2019s date\nThis feature is very useful for a developer for avoiding users from choosing the wrong date. A sample GIF is given below to get an idea about what we are going to do in this functionality.Go to the MainActivity.java file, and refer to the following code. Below is the code for theMainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.CalendarConstraints; \nimport com.google.android.material.datepicker.DateValidatorPointForward; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; public class MainActivity extends AppCompatActivity { // button to open the material date picker dialog \nprivate Button mPickDateButton; // textview to preview the selected date \nprivate TextView mShowSelectedDateText; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button); \nmShowSelectedDateText = findViewById(R.id.show_selected_date); // create the calendar constraint builder \nCalendarConstraints.Builder calendarConstraintBuilder = new CalendarConstraints.Builder(); // set the validator point forward from june \n// this mean the all the dates before the June month \n// are blocked \ncalendarConstraintBuilder.setValidator(DateValidatorPointForward.now()); // instantiate the Material date picker dialog \n// builder \nfinal MaterialDatePicker.Builder materialDatePickerBuilder = MaterialDatePicker.Builder.datePicker(); \nmaterialDatePickerBuilder.setTitleText(\"SELECT A DATE\"); // now pass the constrained calendar builder to \n// material date picker Calendar constraints \nmaterialDatePickerBuilder.setCalendarConstraints(calendarConstraintBuilder.build()); // now build the material date picker dialog \nfinal MaterialDatePicker materialDatePicker = materialDatePickerBuilder.build(); // handle the Select date button to open the \n// material date picker \nmPickDateButton.setOnClickListener( \nnew View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// show the material date picker with \n// supportable fragment manager to \n// interact with dialog material date \n// picker dialog fragments \nmaterialDatePicker.show(getSupportFragmentManager(), \"MATERIAL_DATE_PICKER\"); \n} \n}); materialDatePicker.addOnPositiveButtonClickListener( \nnew MaterialPickerOnPositiveButtonClickListener() { \n@SuppressLint(\"SetTextI18n\") \n@Override\npublic void onPositiveButtonClick(Object selection) { \n// now update the selected date preview \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.getHeaderText()); \n} \n}); \n} \n}Kotlin import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.CalendarConstraints; \nimport com.google.android.material.datepicker.DateValidatorPointForward; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; class MainActivity : AppCompatActivity() { \n// button to open the material date picker dialog \nprivate var mPickDateButton: Button? = null// textview to preview the selected date \nprivate var mShowSelectedDateText: TextView? = null\noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button) \nmShowSelectedDateText = findViewById(R.id.show_selected_date) // create the calendar constraint builder \nval calendarConstraintBuilder = CalendarConstraints.Builder() // set the validator point forward from june \n// this mean the all the dates before the June month \n// are blocked \ncalendarConstraintBuilder.setValidator(DateValidatorPointForward.now()) // instantiate the Material date picker dialog \n// builder \nval materialDatePickerBuilder: MaterialDatePicker.Builder<*> = \nMaterialDatePicker.Builder.datePicker() \nmaterialDatePickerBuilder.setTitleText(\"SELECT A DATE\") // now pass the constrained calendar builder to \n// material date picker Calendar constraints \nmaterialDatePickerBuilder.setCalendarConstraints(calendarConstraintBuilder.build()) // now build the material date picker dialog \nval materialDatePicker = materialDatePickerBuilder.build() // handle the Select date button to open the \n// material date picker \nmPickDateButton.setOnClickListener( \nobject : OnClickListener() { \nfun onClick(v: View?) { \n// show the material date picker with \n// supportable fragment manager to \n// interact with dialog material date \n// picker dialog fragments \nmaterialDatePicker.show(supportFragmentManager, \"MATERIAL_DATE_PICKER\") \n} \n}) \nmaterialDatePicker.addOnPositiveButtonClickListener { // now update the selected date preview \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.headerText) \n} \n} \n} \n// This code is added by Ujjwal KUmar BhardwajOutput: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201016151813/Untitled-Project1237c395.autosave.mp4Functionality 2: Select the today\u2019s date as the default selection as soon as the material date picker dialog opens\nHave a look at the following image.Go to the MainActivity.java file, and refer to the following code. Below is the code for theMainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; public class MainActivity extends AppCompatActivity { // button to open the material date picker dialog \nprivate Button mPickDateButton; // textview to preview the selected date \nprivate TextView mShowSelectedDateText; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button); \nmShowSelectedDateText = findViewById(R.id.show_selected_date); // now create the instance of the regular material \n// date picker \nMaterialDatePicker.Builder materialDateBuilder = MaterialDatePicker.Builder.datePicker(); // get the today's date from the method \n// todayInUtcMilliseconds() \nlong today = MaterialDatePicker.todayInUtcMilliseconds(); // now define the properties of the \n// materialDateBuilder \nmaterialDateBuilder.setTitleText(\"SELECT A DATE\"); // now make today's date selected by default as soon \n// as the dialog opens \nmaterialDateBuilder.setSelection(today); // now create the instance of the material date \n// picker and build the dialog \nfinal MaterialDatePicker materialDatePicker = materialDateBuilder.build(); // handle select date button which opens the \n// material design date picker \nmPickDateButton.setOnClickListener( \nnew View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// now show the material date picker \n// dialog by passing \n// getSupportFragmentmanager() \nmaterialDatePicker.show(getSupportFragmentManager(), \"MATERIAL_DATE_PICKER\"); \n} \n}); // now handle the positive button click from the \n// material design date picker \nmaterialDatePicker.addOnPositiveButtonClickListener( \nnew MaterialPickerOnPositiveButtonClickListener() { \n@SuppressLint(\"SetTextI18n\") \n@Override\npublic void onPositiveButtonClick(Object selection) { \n// now update selected date preview text \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.getHeaderText()); \n} \n}); \n} \n}Kotlin import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; class MainActivity : AppCompatActivity() { \n// button to open the material date picker dialog \nprivate var mPickDateButton: Button? = null// textview to preview the selected date \nprivate var mShowSelectedDateText: TextView? = null\noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button) \nmShowSelectedDateText = findViewById(R.id.show_selected_date) // now create the instance of the regular material \n// date picker \nval materialDateBuilder: MaterialDatePicker.Builder<*> = \nMaterialDatePicker.Builder.datePicker() // get the today's date from the method \n// todayInUtcMilliseconds() \nval today = MaterialDatePicker.todayInUtcMilliseconds() // now define the properties of the \n// materialDateBuilder \nmaterialDateBuilder.setTitleText(\"SELECT A DATE\") // now make today's date selected by default as soon \n// as the dialog opens \nmaterialDateBuilder.setSelection(today) // now create the instance of the material date \n// picker and build the dialog \nval materialDatePicker = materialDateBuilder.build() // handle select date button which opens the \n// material design date picker \nmPickDateButton.setOnClickListener( \nobject : OnClickListener() { \nfun onClick(v: View?) { \n// now show the material date picker \n// dialog by passing \n// getSupportFragmentmanager() \nmaterialDatePicker.show(supportFragmentManager, \"MATERIAL_DATE_PICKER\") \n} \n}) // now handle the positive button click from the \n// material design date picker \nmaterialDatePicker.addOnPositiveButtonClickListener { // now update selected date preview text \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.headerText) \n} \n} \n} \n// This code is adde by UJjwal Kumar BhardwajOutput: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201016121841/Untitled-Project1237c395.autosave.mp4Functionality 3: Make the user, select a date within bounds\nFor example, select the date from March 2020 to December 2020. A sample GIF is given below to get an idea about what we are going to do in this functionality.Go to the MainActivity.java file, and refer to the following code. Below is the code for theMainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.CalendarConstraints; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; \nimport java.util.Calendar; \nimport java.util.TimeZone; public class MainActivity extends AppCompatActivity { // button to open the material date picker dialog \nprivate Button mPickDateButton; // textview to preview the selected date \nprivate TextView mShowSelectedDateText; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button); \nmShowSelectedDateText = findViewById(R.id.show_selected_date); // create the instance of the calendar to set the \n// bounds \nCalendar calendar = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\")); // now set the starting bound from current month to \n// previous MARCH \ncalendar.set(Calendar.MONTH, Calendar.MARCH); \nlong march = calendar.getTimeInMillis(); // now set the ending bound from current month to \n// DECEMBER \ncalendar.set(Calendar.MONTH, Calendar.DECEMBER); \nlong december = calendar.getTimeInMillis(); // create the instance of the CalendarConstraints \n// Builder \nCalendarConstraints.Builder calendarConstraintBuilder = new CalendarConstraints.Builder(); // and set the start and end constraints (bounds) \ncalendarConstraintBuilder.setStart(march); \ncalendarConstraintBuilder.setEnd(december); // instantiate the Material date picker dialog \n// builder \nfinal MaterialDatePicker.Builder materialDatePickerBuilder = MaterialDatePicker.Builder.datePicker(); \nmaterialDatePickerBuilder.setTitleText(\"SELECT A DATE\"); // now pass the constrained calendar builder to \n// material date picker Calendar constraints \nmaterialDatePickerBuilder.setCalendarConstraints(calendarConstraintBuilder.build()); // now build the material date picker dialog \nfinal MaterialDatePicker materialDatePicker = materialDatePickerBuilder.build(); // handle the Select date button to open the \n// material date picker \nmPickDateButton.setOnClickListener( \nnew View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// show the material date picker with \n// supportable fragment manager to \n// interact with dialog material date \n// picker dialog fragments \nmaterialDatePicker.show(getSupportFragmentManager(), \"MATERIAL_DATE_PICKER\"); \n} \n}); materialDatePicker.addOnPositiveButtonClickListener( \nnew MaterialPickerOnPositiveButtonClickListener() { \n@SuppressLint(\"SetTextI18n\") \n@Override\npublic void onPositiveButtonClick(Object selection) { \n// now update the selected date preview \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.getHeaderText()); \n} \n}); \n} \n}Kotlin import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.CalendarConstraints; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; \nimport java.util.Calendar; \nimport java.util.TimeZone; class MainActivity : AppCompatActivity() { \n// button to open the material date picker dialog \nprivate var mPickDateButton: Button? = null// textview to preview the selected date \nprivate var mShowSelectedDateText: TextView? = null\noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button) \nmShowSelectedDateText = findViewById(R.id.show_selected_date) // create the instance of the calendar to set the \n// bounds \nval calendar: Calendar = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\")) // now set the starting bound from current month to \n// previous MARCH \ncalendar.set(Calendar.MONTH, Calendar.MARCH) \nval march: Long = calendar.getTimeInMillis() // now set the ending bound from current month to \n// DECEMBER \ncalendar.set(Calendar.MONTH, Calendar.DECEMBER) \nval december: Long = calendar.getTimeInMillis() // create the instance of the CalendarConstraints \n// Builder \nval calendarConstraintBuilder = CalendarConstraints.Builder() // and set the start and end constraints (bounds) \ncalendarConstraintBuilder.setStart(march) \ncalendarConstraintBuilder.setEnd(december) // instantiate the Material date picker dialog \n// builder \nval materialDatePickerBuilder: MaterialDatePicker.Builder<*> = \nMaterialDatePicker.Builder.datePicker() \nmaterialDatePickerBuilder.setTitleText(\"SELECT A DATE\") // now pass the constrained calendar builder to \n// material date picker Calendar constraints \nmaterialDatePickerBuilder.setCalendarConstraints(calendarConstraintBuilder.build()) // now build the material date picker dialog \nval materialDatePicker = materialDatePickerBuilder.build() // handle the Select date button to open the \n// material date picker \nmPickDateButton.setOnClickListener( \nobject : OnClickListener() { \nfun onClick(v: View?) { \n// show the material date picker with \n// supportable fragment manager to \n// interact with dialog material date \n// picker dialog fragments \nmaterialDatePicker.show(supportFragmentManager, \"MATERIAL_DATE_PICKER\") \n} \n}) \nmaterialDatePicker.addOnPositiveButtonClickListener { // now update the selected date preview \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.headerText) \n} \n} \n} \n//This code is adde by Ujjwal Kumar BhardwajOutput: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201016144355/Untitled-Project1237c395.autosave.mp4Functionality 4: Open the material date picker dialog at the specific month\nFor example, open the material date picker dialog in August month.A sample GIF is given below to get an idea about what we are going to do in this functionality.Go to the MainActivity.java file, and refer to the following code. Below is the code for theMainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.CalendarConstraints; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; \nimport java.util.Calendar; \nimport java.util.TimeZone; public class MainActivity extends AppCompatActivity { // button to open the material date picker dialog \nprivate Button mPickDateButton; // textview to preview the selected date \nprivate TextView mShowSelectedDateText; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button); \nmShowSelectedDateText = findViewById(R.id.show_selected_date); // create the instance of the calendar to set the \n// bounds \nCalendar calendar = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\")); // from calendar object get the AUGUST month \ncalendar.set(Calendar.MONTH, Calendar.AUGUST); \nlong august = calendar.getTimeInMillis(); // create the instance of the CalendarConstraints \n// Builder \nCalendarConstraints.Builder calendarConstraintBuilder = new CalendarConstraints.Builder(); \ncalendarConstraintBuilder.setOpenAt(august); // instantiate the Material date picker dialog \n// builder \nfinal MaterialDatePicker.Builder materialDatePickerBuilder = MaterialDatePicker.Builder.datePicker(); \nmaterialDatePickerBuilder.setTitleText(\"SELECT A DATE\"); // now pass the constrained calendar builder to \n// material date picker Calendar constraints \nmaterialDatePickerBuilder.setCalendarConstraints(calendarConstraintBuilder.build()); // now build the material date picker dialog \nfinal MaterialDatePicker materialDatePicker = materialDatePickerBuilder.build(); // handle the Select date button to open the \n// material date picker \nmPickDateButton.setOnClickListener( \nnew View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// show the material date picker with \n// supportable fragment manager to \n// interact with dialog material date \n// picker dialog fragments \nmaterialDatePicker.show(getSupportFragmentManager(), \"MATERIAL_DATE_PICKER\"); \n} \n}); materialDatePicker.addOnPositiveButtonClickListener( \nnew MaterialPickerOnPositiveButtonClickListener() { \n@SuppressLint(\"SetTextI18n\") \n@Override\npublic void onPositiveButtonClick(Object selection) { \n// now update the selected date preview \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.getHeaderText()); \n} \n}); \n} \n}Kotlin import android.annotation.SuppressLint; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.datepicker.CalendarConstraints; \nimport com.google.android.material.datepicker.MaterialDatePicker; \nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; \nimport java.util.Calendar; \nimport java.util.TimeZone; class MainActivity : AppCompatActivity() { \n// button to open the material date picker dialog \nprivate var mPickDateButton: Button? = null// textview to preview the selected date \nprivate var mShowSelectedDateText: TextView? = null\noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // register all the UI widgets with their \n// appropriate IDs \nmPickDateButton = findViewById(R.id.pick_date_button) \nmShowSelectedDateText = findViewById(R.id.show_selected_date) // create the instance of the calendar to set the \n// bounds \nval calendar: Calendar = Calendar.getInstance(TimeZone.getTimeZone(\"UTC\")) // from calendar object get the AUGUST month \ncalendar.set(Calendar.MONTH, Calendar.AUGUST) \nval august: Long = calendar.getTimeInMillis() // create the instance of the CalendarConstraints \n// Builder \nval calendarConstraintBuilder = CalendarConstraints.Builder() \ncalendarConstraintBuilder.setOpenAt(august) // instantiate the Material date picker dialog \n// builder \nval materialDatePickerBuilder: MaterialDatePicker.Builder<*> = \nMaterialDatePicker.Builder.datePicker() \nmaterialDatePickerBuilder.setTitleText(\"SELECT A DATE\") // now pass the constrained calendar builder to \n// material date picker Calendar constraints \nmaterialDatePickerBuilder.setCalendarConstraints(calendarConstraintBuilder.build()) // now build the material date picker dialog \nval materialDatePicker = materialDatePickerBuilder.build() // handle the Select date button to open the \n// material date picker \nmPickDateButton.setOnClickListener( \nobject : OnClickListener() { \nfun onClick(v: View?) { \n// show the material date picker with \n// supportable fragment manager to \n// interact with dialog material date \n// picker dialog fragments \nmaterialDatePicker.show(supportFragmentManager, \"MATERIAL_DATE_PICKER\") \n} \n}) \nmaterialDatePicker.addOnPositiveButtonClickListener { // now update the selected date preview \nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.headerText) \n} \n} \n} \n//This code is written by Ujjwal KUmar BhardwajOutput: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201016145508/Untitled-Project1237c395.autosave.mp4"}, {"text": "\nMaterial Design Date Picker in Android\n\nMaterial Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android applications. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Date Picker. There are a lot of date pickers available for Android which are Open Source. But the Material design date pickers offer more functionality to the user and are easy to implement for developers. Have a look at the following images on what type of material design date pickers are going to be discussed in this discussion. Note that we are going toimplement this project using theJavalanguage.In this article, we are going to implement two types of material design date pickers as one can see in the below images.Material Design Normal Date Picker\nMaterial Design Date Range PickerSkeleton of Date Picker Dialog Box\nBefore going to implement the material design date picker, understanding the parts of the dialog box is necessary so that it can become easier while dealing with parts of the dialog box in java code.Steps by Step Implementation\nStep 1: Create a New ProjectTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.\nNote that select Java as the programming language.Step 2: Adding material design components dependencyNow add the following dependency to the app-level gradle file.implementation \u2018com.google.android.material:material:1.3.0-alpha02\u2019After invoking the dependency click on the \u201cSync Now\u201d button. Make sure you are connected to the network so that Android Studio downloads all the required files.\nRefer to the following image if unable to locate the app-level gradle file and invoke the dependency.Step 3: Change the base application theme as Material Theme as followingGo to app > src > main > res > values > styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles. Below is the code for the styles.xml file. As we are using material design components this step is mandatory.XML \n Refer to the following if unable to locate styles.xml and change the base theme of the application.Step 4: Working with the activity_main.xml fileInvoke the following code for the application interface or can design it according to one\u2019s needs.\nAnd this is going to remain the same for the entire discussion. Below is the code for theactivity_main.xml file.XML \n\n \n The icon has been added to the Select Date button above in the code. However, that is optional. Refer Theming Material Design buttons in android with examples on how to add the icon to a button or how to change the theme of the button.Output UI:Implementation of Normal Date Picker\nStep 5: Now invoke the following code to implement the first type of the material design date pickerGo to the MainActivity.java file, and refer to the following code. Below is the code for theMainActivity.java file.\nComments are added inside the code to understand the code in more detail.Java import android.annotation.SuppressLint;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport androidx.appcompat.app.AppCompatActivity;\nimport com.google.android.material.datepicker.MaterialDatePicker;\nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;public class MainActivity extends AppCompatActivity {private Button mPickDateButton;private TextView mShowSelectedDateText;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// now register the text view and the button with\n// their appropriate IDs\nmPickDateButton = findViewById(R.id.pick_date_button);\nmShowSelectedDateText = findViewById(R.id.show_selected_date);// now create instance of the material date picker\n// builder make sure to add the \"datePicker\" which\n// is normal material date picker which is the first\n// type of the date picker in material design date\n// picker\nMaterialDatePicker.Builder materialDateBuilder = MaterialDatePicker.Builder.datePicker();// now define the properties of the\n// materialDateBuilder that is title text as SELECT A DATE\nmaterialDateBuilder.setTitleText(\"SELECT A DATE\");// now create the instance of the material date\n// picker\nfinal MaterialDatePicker materialDatePicker = materialDateBuilder.build();// handle select date button which opens the\n// material design date picker\nmPickDateButton.setOnClickListener(\nnew View.OnClickListener() {\n@Override\npublic void onClick(View v) {\n// getSupportFragmentManager() to\n// interact with the fragments\n// associated with the material design\n// date picker tag is to get any error\n// in logcat\nmaterialDatePicker.show(getSupportFragmentManager(), \"MATERIAL_DATE_PICKER\");\n}\n});// now handle the positive button click from the\n// material design date picker\nmaterialDatePicker.addOnPositiveButtonClickListener(\nnew MaterialPickerOnPositiveButtonClickListener() {\n@SuppressLint(\"SetTextI18n\")\n@Override\npublic void onPositiveButtonClick(Object selection) {// if the user clicks on the positive\n// button that is ok button update the\n// selected date\nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.getHeaderText());\n// in the above statement, getHeaderText\n// is the selected date preview from the\n// dialog\n}\n});\n}\n}Kotlin import android.annotation.SuppressLint;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport androidx.appcompat.app.AppCompatActivity;\nimport com.google.android.material.datepicker.MaterialDatePicker;\nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;class MainActivity : AppCompatActivity() {\nprivate var mPickDateButton: Button? = null\nprivate var mShowSelectedDateText: TextView? = null\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// now register the text view and the button with\n// their appropriate IDs\nmPickDateButton = findViewById(R.id.pick_date_button)\nmShowSelectedDateText = findViewById(R.id.show_selected_date)// now create instance of the material date picker\n// builder make sure to add the \"datePicker\" which\n// is normal material date picker which is the first\n// type of the date picker in material design date\n// picker\nval materialDateBuilder: MaterialDatePicker.Builder<*> =\nMaterialDatePicker.Builder.datePicker()// now define the properties of the\n// materialDateBuilder that is title text as SELECT A DATE\nmaterialDateBuilder.setTitleText(\"SELECT A DATE\")// now create the instance of the material date\n// picker\nval materialDatePicker = materialDateBuilder.build()// handle select date button which opens the\n// material design date picker\nmPickDateButton.setOnClickListener(\nobject : OnClickListener() {\nfun onClick(v: View?) {\n// getSupportFragmentManager() to\n// interact with the fragments\n// associated with the material design\n// date picker tag is to get any error\n// in logcat\nmaterialDatePicker.show(supportFragmentManager, \"MATERIAL_DATE_PICKER\")\n}\n})// now handle the positive button click from the\n// material design date picker\nmaterialDatePicker.addOnPositiveButtonClickListener {\n// if the user clicks on the positive\n// button that is ok button update the\n// selected date\nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.headerText)\n// in the above statement, getHeaderText\n// is the selected date preview from the\n// dialog\n}\n}\n}\n// This code is written by Ujjwal Kumar BhardwajOutput: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201011142153/Untitled-Project.mp4\nImplementation of Date Range Picker\nStep 6: Now invoke the following code to implement the second type of the material design date pickerIn material design date picker there is one more type of the date picker is available, that is called as date range picker.\nThe following code is the implementation of the date range picker.\nGo to the MainActivity.java file, and refer to the following code. Below is the code for theMainActivity.java file.\nComments are added inside the code to understand the code in more detail.Java import android.annotation.SuppressLint;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.core.util.Pair;\nimport com.google.android.material.datepicker.MaterialDatePicker;\nimport com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener;public class MainActivity extends AppCompatActivity {private Button mPickDateButton;\nprivate TextView mShowSelectedDateText;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// now register the text view and the button with\n// their appropriate IDs\nmPickDateButton = findViewById(R.id.pick_date_button);\nmShowSelectedDateText = findViewById(R.id.show_selected_date);// now create instance of the material date picker\n// builder make sure to add the \"dateRangePicker\"\n// which is material date range picker which is the\n// second type of the date picker in material design\n// date picker we need to pass the pair of Long\n// Long, because the start date and end date is\n// store as \"Long\" type value\nMaterialDatePicker.Builder> materialDateBuilder = MaterialDatePicker.Builder.dateRangePicker();// now define the properties of the\n// materialDateBuilder\nmaterialDateBuilder.setTitleText(\"SELECT A DATE\");// now create the instance of the material date\n// picker\nfinal MaterialDatePicker materialDatePicker = materialDateBuilder.build();// handle select date button which opens the\n// material design date picker\nmPickDateButton.setOnClickListener(\nnew View.OnClickListener() {\n@Override\npublic void onClick(View v) {\n// getSupportFragmentManager() to\n// interact with the fragments\n// associated with the material design\n// date picker tag is to get any error\n// in logcat\nmaterialDatePicker.show(getSupportFragmentManager(), \"MATERIAL_DATE_PICKER\");\n}\n});// now handle the positive button click from the\n// material design date picker\nmaterialDatePicker.addOnPositiveButtonClickListener(\nnew MaterialPickerOnPositiveButtonClickListener() {\n@SuppressLint(\"SetTextI18n\")\n@Override\npublic void onPositiveButtonClick(Object selection) {// if the user clicks on the positive\n// button that is ok button update the\n// selected date\nmShowSelectedDateText.setText(\"Selected Date is : \" + materialDatePicker.getHeaderText());\n// in the above statement, getHeaderText\n// will return selected date preview from the\n// dialog\n}\n});\n}\n}Output: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201011145100/GFG_nexus_5.mp4To implement more functionalities of Material Design Date Picker please refer to More Functionalities of Material Design Date Picker in Android article."}, {"text": "\nImplement customized TimePicker in Android using SnapTimePicker\n\nAndroid TimePicker is a user interface control for selecting the time in either 24-hour format or AM/PM mode. It is used to ensure that users pick a valid time for the day in the application. The default TimePicker can be customized by using the SnapTimePicker in Android.Some features of SnapTimePicker are:Selectable time range support.\nText and color customization.\nIOS Time Picker like with Material Design style.ApproachStep 1: Add the support Library in build.gradle file and add dependency in the dependencies section. implementation 'com.akexorcist:snap-time-picker:1.0.0' Step 2: Add the following code in string.xml file in values directory. In this file add all string used in the app. These string can be referenced from app or some other resource files(such as XML layout).string.xml \nGFG | SnapTimePicker \nPlease select the time \nYour selected time is \n%1$s:%2$s \n>> \n<< \n Step 3: Add the following code in activity_main.xml file. In this file add the Buttons to select the time and the TextView to display the selected time.activity_main.xml \n \n \n Step 4: Add the following code in MainActivity.kt file. In this file add onClickListener() method to the buttons so that whenever user click on them a TimePicker dialog will be created.MainActivity.kt package com.madhav.maheshwari.snaptimepicker import android.os.Bundle \nimport androidx.appcompat.app.AppCompatActivity \nimport com.akexorcist.snaptimepicker.SnapTimePickerDialog \nimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) defaultTimePicker.setOnClickListener { \n// Default TimePicker \nSnapTimePickerDialog.Builder().apply { \nsetTitle(R.string.title) \nsetTitleColor(android.R.color.white) \n}.build().apply { \nsetListener { \n// when the user select time onTimePicked \n// function get invoked automatically which \n// sets the time in textViewTime. \nhour, minute -> \nonTimePicked(hour, minute) \n} \n}.show( \nsupportFragmentManager, \nSnapTimePickerDialog.TAG \n) \n} customTimePicker.setOnClickListener { \n// Custom TimePicker \nSnapTimePickerDialog.Builder().apply { \nsetTitle(R.string.title) \nsetPrefix(R.string.time_prefix) \nsetSuffix(R.string.time_suffix) \nsetThemeColor(R.color.colorAccent) \nsetTitleColor(android.R.color.black) \n}.build().apply { \nsetListener { \n// when the user select time onTimePicked \n// function get invoked automatically which \n// sets the time in textViewTime. \nhour, minute -> \nonTimePicked(hour, minute) \n} \n}.show( \nsupportFragmentManager, \nSnapTimePickerDialog.TAG \n) \n} } private fun onTimePicked(selectedHour: Int, selectedMinute: Int) { \n// Pads the string to the specified length \n// at the beginning with the specified \n// character or space. \nval hour = selectedHour.toString() \n.padStart(2, '0') \nval minute = selectedMinute.toString() \n.padStart(2, '0') \nselectedTime.text = String.format( \ngetString( \nR.string.selected_time_format, \nhour, minute \n) \n) \n} \n} Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200717131302/2020_07_17_13_01_37_0011.mp4\nAdvantages:\nThe advantages of using SnapTimePicker over simple TimePicker are:SnapTimePicker can be customized according to the requirements.\nIt is very easy to use.\nIt gives IOS feel of an app."}, {"text": "\nHow to Build a Simple Notes App in Android?\n\nNotes app is used for making short text notes, updating when you need them, and trashing when you are done. It can be used for various functions as you can add your to-do list in this app, some important notes for future reference, etc. The app is very useful in some cases like when you want quick access to the notes. Likewise, here let\u2019s create an Android App to learn how to create a simple NotesApp. So in this article let\u2019s build a Notes App in which the user can add any data, remove any data as well as edit any data. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.\nResources Used in the ApplicationIn this Application, we will be using Activities and Simple Java Code:\nMain Activity: The Main Activity is used for Activities on the Main Page.Detail Activity: Detail Activity is used for Details of the Notes Opened using the Open Button.Add Note Activity: The Add Note Activity is used for Creating new Entries in the Data.My Adapter: It is a Java Program used for Defining the Structure of Every Single List Item.Layouts Used in this Application:\nactivity_main: The layout of the main page is used here.list_item: The layout for the list item which is used in the main activity is mentioned here.activity_detail: The layout for the window where we will be opening the Notes in Full Page in the CardViewactivity_add_note: The layout for the window where we can add the new item on the main page.Directory Structure of the Application\nSteps for Creating a Notes Application on AndroidStep 1: Create a New ProjectTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. \nNote: Select Java as the programming language.\nStep 2: Working with the activity_main.xml fileIn the activity_main.xml file the main page we will only display the Notes with Add , Open and Delete Button. \nBelow is the complete code for theactivity_main.xml file.activity_main.xml\n Output UI:Apart from this we will need a Layout template for every ListItem. So, we will be creating a new Layout File.\nFile Name: list_item.xml list_item.xml\n \n Output UI:Now we have created our Main Page. In the next step we will be defining the functionalities of the the Main page buttons.Step 3: Creating New Layouts for Opening the Details and Adding the Items.Go to app > java > right-click > New > Activity > Empty Activity and name it as AddNoteActivity.\nNote: Similarly Create DetailActivity. \nResource File Created : \n AddNoteActivity.java and activity_add_note.xmlDetailActivity.java and activity_detail_activity.xmlBelow is the Layout used for AddNoteActivity:\nactivity_add_note.xml \n Output UI:\nAnd the another layout for DetailActivity.java\nactivity_detail.xml \n Output UI:Step 4: Adding Functionalities to MainActivityNow we have all the Layout Prepared. So, let us add functionalities to the Buttons:MainActivity.javapackage org.geeksforgeeks.simple_notes_application_java;import android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ListView;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList;\nimport java.util.List;public class MainActivity extends AppCompatActivity { private static final int REQUEST_CODE_ADD_NOTE = 1;\n private MyAdapter adapter;\n private List items; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); ListView listView = findViewById(R.id.listView);\n Button addNoteButton = findViewById(R.id.add_button); // Initialize the list of items\n items = new ArrayList<>(); // Add a temporary item\n items.add(\"Temp Add Element\"); // Create the adapter and set it to the ListView\n adapter = new MyAdapter(this, items);\n listView.setAdapter(adapter); // Set click listener for the add note button\n addNoteButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(MainActivity.this, AddNoteActivity.class);\n startActivityForResult(intent, REQUEST_CODE_ADD_NOTE);\n }\n });\n } @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_ADD_NOTE && resultCode == RESULT_OK) {\n String newNote = data.getStringExtra(\"NEW_NOTE\");\n if (newNote != null) {\n items.add(newNote);\n adapter.notifyDataSetChanged();\n }\n }\n }\n}Also, we need a Program to Support the MainAcitivity for adding the functionalities to ListView Items i.e. Add Button and Delete Button. \nCreate MyAdapter.java Class containing the Functionalities. Create New Java Class MyAdapter.java file in the main src project in the same repo as MainActivity.java file:MyAdapter.javapackage org.geeksforgeeks.simple_notes_application_java;import android.content.Context;\nimport android.content.Intent;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;import java.util.List;public class MyAdapter extends ArrayAdapter {\n private final Context context;\n private final List values; public MyAdapter(Context context, List values) {\n super(context, R.layout.list_item, values);\n this.context = context;\n this.values = values;\n } @Override\n public View getView(final int position, View convertView, ViewGroup parent) {\n LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n View rowView = inflater.inflate(R.layout.list_item, parent, false); TextView textView = rowView.findViewById(R.id.textView);\n Button openButton = rowView.findViewById(R.id.button);\n Button deleteButton = rowView.findViewById(R.id.delete_button); textView.setText(values.get(position)); openButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Start DetailActivity and pass the item data\n Intent intent = new Intent(context, DetailActivity.class);\n intent.putExtra(\"ITEM\", values.get(position));\n context.startActivity(intent);\n }\n }); deleteButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(context, \"Delete button clicked for item \" + values.get(position), Toast.LENGTH_SHORT).show();\n // Remove the item from the list\n values.remove(position);\n // Notify the adapter to refresh the list view\n notifyDataSetChanged();\n }\n }); return rowView;\n }\n}Step 5: Adding New Node to the ApplicationAlthough we have created a layout for adding New Node but without Adding the Functionalities to it the Layout is of no use. So, let us start working on the ActivityAddNote.java file so that we can add few more Important Nodes to the Application.Javapackage org.geeksforgeeks.simple_notes_application_java;import android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;import androidx.appcompat.app.AppCompatActivity;public class AddNoteActivity extends AppCompatActivity { @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_add_note); EditText editText = findViewById(R.id.editTextNote);\n Button buttonAdd = findViewById(R.id.buttonAddNote); buttonAdd.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String newNote = editText.getText().toString().trim();\n if (!newNote.isEmpty()) {\n Intent resultIntent = new Intent();\n resultIntent.putExtra(\"NEW_NOTE\", newNote);\n setResult(RESULT_OK, resultIntent);\n finish();\n }\n }\n });\n }\n}Now On clicking on the Add Note Button in the Main Page we will be redirected to this Activity where we can add new Note.\nStep 6: Opening the Details Page in the Android ApplicationAlthough we can read the Node from the Main Page but we are adding the Dedicated page to Open a Single Note in a page, using this activity.\nBelow is the Program to View the Details of a Node in the Application:\nDetailsActivity.javapackage org.geeksforgeeks.simple_notes_application_java;import android.os.Bundle;\nimport android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;public class DetailActivity extends AppCompatActivity { @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_detail); TextView detailTextView = findViewById(R.id.detailTextView);\n TextView dataNotesTextView = findViewById(R.id.Data_Notes); // Get the data passed from MainActivity\n String item = getIntent().getStringExtra(\"ITEM\"); // Set the data to the TextViews\n detailTextView.setText(\"Notes Content\");\n dataNotesTextView.setText(item);\n }\n}Now we have added all the functionalities to the Application\nStep 7: Formatting the String.xml fileAlthough we have not added any Majot changes in the String.xml file but still it will require some changes to run the application as we are using some resources there.\nBelow is the code for string.xml file:\nstring.xml\n Simple_Notes_Application_Java \n Simple Notes Application GFG \n After Adding this code we will be able to run of the application.\nhttps://media.geeksforgeeks.org/wp-content/uploads/20240616190817/Simple_Notes_Application.mp4\nFinal Application to Build a Simple Notes AppNote: The Application we have created is like a template for your Notes Application you can make changes in it as you want.\nThe GitHub Link for the Application is : Click Here to access the Complete Code to create a Simple Notes Application\nClick Here to Check More Android Projects \n"}, {"text": "\nScreen Orientations in Android with Examples\n\nScreen Orientation, also known as screen rotation, is the attribute of activity element in android. When screen orientation change from one state to other, it is also known as configuration change. \nStates of Screen orientation\nThere are various possible screen orientation states for any android application, such as:ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE\nActivityInfo.SCREEN_ORIENTATION_PORTRAIT\nActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED\nActivityInfo.SCREEN_ORIENTATION_USER\nActivityInfo.SCREEN_ORIENTATION_SENSOR\nActivityInfo.SCREEN_ORIENTATION_BEHIND\nActivityInfo.SCREEN_ORIENTATION_NOSENSOR\nActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE\nActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT\nActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT The initial orientation of the Screen has to be defined in the AndroidManifest.xml file. \nSyntax:AndroidManifest.xml \n "}, {"text": "\nHow to Integrate Facebook Audience Network (FAN) Interstitial Ads in Android?\n\nIn order to earn money from the Android app or game, there are many ways such as in-App Purchases, Sponsorship, Advertisements, and many more. But there is another popular method to earn money from the Android app is by integrating a third party advertisement e.g known as Facebook Audience Network (FAN). Facebook Audience Network is designed to help monetize with the user experience in mind. By using high-value formats, quality ads, and innovative publisher tools it helps to grow the business while keeping people engaged.\nWhy Facebook Audience Network?Facebook Audience Network is one of the best alternatives for Google Admob to monetize the Android or IOS App.\nMinimum Payout is $100\nWide Range of Ad Formats\nMaximum Fill Rates\nHigh eCPM(Effective Cost Per Mille)\nQuality Ads\nPersonalized AdsFormats of Facebook Audience Network\nThere are mainly five types of flexible, high-performing format available in Facebook Audience NetworkNative: Ads that you design to fit the app, seamlessly\nInterstitial: Full-screen ads that capture attention and become part of the experience.\nBanner: Traditional formats in a variety of placements.\nRewarded Video: An immersive, user-initiated video ad that rewards users for watching.\nPlayables: A try-before-you-buy ad experience allowing users to preview a game before installing.In this article let\u2019s integrate Facebook Audience Network Interstitial ads in the Android app.\nInterstitial Ad: Interstitial ad is a full-screen ad that covers the whole UI of the app. The eCPM (Effective Cost Per Mille) of Interstitial ads are relatively higher than banner ads and also leads to higher CTR(Click Through Rate) which results in more earning from the app.Approach\nStep 1: Creating a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language.\nStep 2: Before going to the coding section first do some pre-taskGo to app -> res -> values -> colors.xml file and set the colors for the app.colors.xml \n \n#0F9D58 \n#0F9D58 \n#05af9b \n Go to Gradle Scripts -> build.gradle (Module: app) section and import following dependencies and click the \u201csync now\u201d on the above pop up.implementation \u2018com.facebook.android:audience-network-sdk:5.+\u2019Go to app -> manifests -> AndroidManifests.xml section and allow \u201cInternet Permission\u201c.Step 3: Designing the UI\nIn the activity_main.xml file add only one Button, so whenever the user clicks the Button the Rewarded video ad will be played.activity_main.xml \n \n Step 4: Working with MainActivity.java fileOpen the MainActivity.java file there within the class, first create the object of the Button class.// Creating an object of Button class\nButton showInterstitialBtn;Now inside the onCreate() method, link those objects with their respective IDs that have given in activity_main.xml file.// link those objects with their respective id\u2019s that we have given in activity_main.xml file\nshowInterstitialBtn=(Button)findViewById(R.id.showInterBtn);Now inside onCreate() method, initialize the Facebook Audience Network SDK.// initializing the Audience Network SDK\nAudienceNetworkAds.initialize(this);Create an object of InterstitialAd inside MainActivity.java class// creating object of InterstitialAd\nInterstitialAd fbInterstitialAd;Next create a private void loadInterstitial() method outside onCreate() method and define it.private void showInterstitial()\n {\n // initializing InterstitialAd Object\n // InterstitialAd Constructor Takes 2 Arguments\n // 1)Context\n // 2)Placement Id\n fbInterstitialAd = new InterstitialAd(this, \u201cIMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID\u201d);\n // loading Ad\n fbInterstitialAd.loadAd(); \n }Call the loadInterstitial() inside onCreate() method after initializing the SDK.Note: Replace \u201cIMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID\u201d with your own placement id to show real ads.Next create a void showInterstitial() method outside onCreate() method which we call later to show ad.void showInterstitial()\n {\n // Checking If Ad is Loaded or Not\n if(fbInterstitialAd.isAdLoaded())\n {\n // showing Ad\n fbInterstitialAd.show();\n }\n else\n {\n // Loading Ad If Ad is Not Loaded\n fbInterstitialAd.loadAd();\n }\n}So the next thing is to call the showInterstitial() method when a user clicks a show ad button.\nNow in onCreate() method create a ClickListener for the button and call showInterstitial(). // click listener to show Interstitial Ad\nshowInterstitialBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n showInterstitial();\n }\n });Now add InterstitialAdListener for Interstitial Ad, so that users will know the status of the ads. To add InterstitialAdListener open loadInterstitial() method and add the below code before fbInterstitialAd.loadAd().// Interstitial AdListener\nfbInterstitialAd.setAdListener(new InterstitialAdListener() {\n @Override\n public void onInterstitialDisplayed(Ad ad) {\n // Showing Toast Message\n Toast.makeText(MainActivity.this, \u201conInterstitialDisplayed\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onInterstitialDismissed(Ad ad) {\n // Showing Toast Message\n Toast.makeText(MainActivity.this, \u201conInterstitialDismissed\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onError(Ad ad, AdError adError) {\n // Showing Toast Message\n Toast.makeText(MainActivity.this, \u201conError\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onAdLoaded(Ad ad) {\n // Showing Toast Message\n Toast.makeText(MainActivity.this, \u201conAdLoaded\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onAdClicked(Ad ad) {\n // Showing Toast Message\n Toast.makeText(MainActivity.this, \u201conAdClicked\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onLoggingImpression(Ad ad) {\n // Showing Toast Message\n Toast.makeText(MainActivity.this, \u201conLoggingImpression\u201d, Toast.LENGTH_SHORT).show();\n }\n });And inside InterstitialAdListener Override methods show a toast message so that users know the status of ad. Below is the complete code for the MainActivity.java file.MainActivity.java package org.geeksforgeeks.project; import android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.Toast; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.facebook.ads.Ad; \nimport com.facebook.ads.AdError; \nimport com.facebook.ads.AudienceNetworkAds; \nimport com.facebook.ads.InterstitialAd; \nimport com.facebook.ads.InterstitialAdListener; public class MainActivity extends AppCompatActivity { // Creating a object of Button class \nButton showInterstitialBtn; \n// creating object of InterstitialAd \nInterstitialAd fbInterstitialAd; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // link those objects with their respective id's that we have given in activity_main.xml file \nshowInterstitialBtn = (Button) findViewById(R.id.showInterBtn); // initializing the Audience Network SDK \nAudienceNetworkAds.initialize(this); loadInterstitial(); // click listener to show Interstitial Ad \nshowInterstitialBtn.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) { \nshowInterstitial(); \n} \n}); \n} void showInterstitial() { \n// Checking If Ad is Loaded or Not \nif (fbInterstitialAd.isAdLoaded()) { \n// showing Ad \nfbInterstitialAd.show(); \n} else { \n// Loading Ad If Ad is Not Loaded \nfbInterstitialAd.loadAd(); \n} \n} private void loadInterstitial() { \n// initializing InterstitialAd Object \n// InterstitialAd Constructor Takes 2 Arguments \n// 1)Context \n// 2)Placement Id \nfbInterstitialAd = new InterstitialAd(this, \"IMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID\"); // Interstitial AdListener \nfbInterstitialAd.setAdListener(new InterstitialAdListener() { \n@Override\npublic void onInterstitialDisplayed(Ad ad) { \n// Showing Toast Message \nToast.makeText(MainActivity.this, \"onInterstitialDisplayed\", Toast.LENGTH_SHORT).show(); \n} @Override\npublic void onInterstitialDismissed(Ad ad) { \n// Showing Toast Message \nToast.makeText(MainActivity.this, \"onInterstitialDismissed\", Toast.LENGTH_SHORT).show(); \n} @Override\npublic void onError(Ad ad, AdError adError) { \n// Showing Toast Message \nToast.makeText(MainActivity.this, \"onError\", Toast.LENGTH_SHORT).show(); \n} @Override\npublic void onAdLoaded(Ad ad) { \n// Showing Toast Message \nToast.makeText(MainActivity.this, \"onAdLoaded\", Toast.LENGTH_SHORT).show(); \n} @Override\npublic void onAdClicked(Ad ad) { \n// Showing Toast Message \nToast.makeText(MainActivity.this, \"onAdClicked\", Toast.LENGTH_SHORT).show(); \n} @Override\npublic void onLoggingImpression(Ad ad) { \n// Showing Toast Message \nToast.makeText(MainActivity.this, \"onLoggingImpression\", Toast.LENGTH_SHORT).show(); \n} \n}); // loading Ad \nfbInterstitialAd.loadAd(); \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200824180045/Facebook-Audience-Network-Interstitial-Ad.mp4"}, {"text": "\nHow to Reduce APK Size in Android?\n\nAPK size is one of the most important factors while building any app for any organization or any business. No user would like to install a very large APK and consume his data on downloading that APK. The APK size will make an impact on your app performance about How fast it loads, How much memory it consumes, and How much memory it uses. It is very important to take a look at your APK size while developing. In this article, we will take a look over the tips to reduce your APK size in Android Studio.\n1. Remove unused sources\nThe size of APK depends on very small factors rather it may be code, images, and assets used in your app. To reduce the size of your APK remove unused sources which will help to reduce APK size up to a certain extent. Removing unused sources of APK such as unused pngs, jpegs, and many other assets. Small size images are also preferable for reducing APK size. It is advised to use vector drawables instead of other image formats like JPEG, PNG, and others. Vector drawables are small in size and the main advantage of vector drawables is they don\u2019t lose their quality even after increasing or decreasing size.\n2. Use of Vector Drawables\nAvoid using jpegs and pngs images because they consume very high memory in comparison with normal vector drawables. Vector drawables are easily scalable and their quality does not degrade in the change of size.\n3. Reuse your code\nReuse your code as much as possible instead of repeating the code. Object-Oriented Programming will help you a lot to solve this problem and this will also help to maintain your size of APK. Repetitive code will increase the size of that particular file and it will lead to an increase in APK size. \n4. Compress PNG and JPEG files\nIn most cases, images are the main purpose to degrade the performance in-app as well as on websites. So it is preferable to use compressed images to reduce its size and increase app performance. The size of the image will also affect the APK size so it is preferable to use compressed images in your app. You can use so many online platforms to compress your images for free.\n5. Use of Lint\nLint is one of the important tools which will help us to get the unused and repeated code inside your application. So this tool will help in removing repeated and unused code. \n6. Use images in WebP file format\nWebP is another one of the famous image formats which are developed by Google. This image format generally focuses on image quality and optimization. Rather than using images in PNG and JPEG format WebP image format is highly preferable because of its quality.\n7. Use of proguard\nProguard also plays an important role in adjusting the size of the Android APK. The main functions of using Proguard are given below:It makes the application difficult to reverse engineer.\nIt helps to reduce the size of the application by removing the unused classes and methods.Proguard in Android App can be found in Gradle Scripts > build.gradle file.proguardFiles getDefaultProguardFile(\u2018proguard-android-optimize.txt\u2019), \u2018proguard-rules.pro\u20198. Use of ShrinkResourcesshrinkResources trueShrinkResources method will be displayed in build.gradle file. This method will remove the resources which are not being used in the project. You have to enable it by specifying it to true. You can find this method in build.gradle file > buildTypes > release > shrinkResources. Enable it to true.\n9. Use of R8 to reduce the size of APK\nR8 works similar to that of proguard. R8 shrinking is the process in which we reduce the amount of code which helps to reduce APK size automatically. R8 works with proguard rules and shrinks code faster improvising the output size.\n10. Limit the usage of external libraries\nWhile adding many external features inside our app we prefer to use some external libraries. These external libraries will install the classes provided by them some of the classes are not required and of no use, they can consume storage and will lead to an increase in APK size. So it is preferable to limit the usage of external libraries to reduce APK size.\n11. Use the Android Size Analyzer tool\nIn Android Studio there is a plugin called Android Size Analyzer this tool will help to find the amount of memory consumed by different files of our APK. Along with this Size, the Analyzer tool will also provide us some tips which will be helpful for reducing the size of our APK. To analyze your APK size you just have to click on the build > Analyze APK option and then select your APK. You will get to see the actual size of files with distribution along with downloadable size. With the help of this tool, you can also compare the size of your previous APK with the new one.\n12. Generate App Bundles instead of APK\nAndroid App Bundle is a publishing format which is provided by Google. It consists of your app\u2019s code and resources which is different from APK generation and signing to Google Play. Google Play will handle your app\u2019s bundle, it will generate optimized APK for a specific device according to device configuration. When you are using app bundles you don\u2019t have to generate multiple APK files for different devices. To generate app bundles for your app you just have to click on Build>Build Bundle(s)/APK(s) and then click on Build Bundle(s). Your apps bundle will be generated.\n13. Use of Multiple APK files\nIf you don\u2019t want to create bundles for your application then you can opt for the option for creating multiple APK files. Multiple APK files can be used to support different device types and different CPU architectures.\n14. Reduce library size\nIf you are using the libraries for adding some custom views inside your project, then you can add the official libraries which are provided by Google. Generally adding libraries makes it easier to add new functionality easily inside our app but at the same time, it also affects the size of our app. It is preferable to reduce the usage of libraries while building any application.\n15. Use of Resconfigs\nWhile building an Android application it is having some default resources present inside them. All of these support libraries which we are using in our device are having local folders for other languages which we actually don\u2019t inside our app. These folders also take some memory location inside our app. We can remove these resources which are not required inside our APK using resConfigs and this will helps in reducing the app size by a certain amount. If you are building a specific app for targeting an only specific audience and this audience only uses a specific language like Hindi, then we will only keep resource for Hindi language and we will remove all other languages which are not required.\n16. Remove libraries that are only required for debugging\nMany developers used some specific libraries for debugging their APK files. These debugging libraries will also take some storage inside our APK file. We can use the method of debugImplementation() inside our app to use these debugging libraries only while debugging. So these libraries will be used only while debugging and will not be added inside your release APK files.\n"}, {"text": "\nHow to Build a Simple Augmented Reality Android App?\n\nAugmented Reality has crossed a long way from Sci-fi Stories to Scientific reality. With this speed of technical advancement, it\u2019s probably not very far when we can also manipulate digital data in this real physical world as Tony Stark did in his lab. When we superimpose information like sound, text, image to our real-world and also can interact with it through a special medium, that is Augmented Reality. The world-famous \u201cPokemon GO\u201d app is just another example of an Augmented Reality Application. Let\u2019s make a very simple Augmented Reality App in Android Studio using JAVA. This app shows a custom made or downloaded 3d model using the phone camera. A sample GIF is given below to get an idea about what we are going to do in this article.TerminologiesARCore: According to Google, ARCore is a platform for Augmented Reality. ARCore actually helps the phone to sense its environment and interact with the world. ARCore mainly uses 3 key principles \u2013 Motion Tracking, Understanding Environment, and Light Estimation. Here is a list provided by Google, of the phones that supports ARCore.\nSceneform: According to Google, Sceneform is a 3d framework, that helps the developers to build ARCore apps without knowing a lot about OpenGL. Sceneform comes with a lot of features like checking for camera permission, manipulating 3d assets, and a lot more.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.Note:Select Java as the programming language.\nNote the location where the app is getting saved because we need that path later.\nChoose \u2018Minimum SDK\u2018 as \u2018API 24: Android 7.0(Nougat)\u2018Step 2: Getting the 3D Model\nSceneform 1.16.0 supports only glTF files. glTF means GL Transmission Format. Now .glb files are a binary version of the GL Transmission Format. These types of 3d model files are used in VR, AR because it supports motion and animation.For the 3d model, you have to get a .glb file.\nThere are two ways, you can grab a 3d model, download from the web, or make one yourself.\nIf you want to download it from the web, go to this awesome 3d models repository by Google, poly, and search for any glb file. Download any one of them for your project.\nOR, get a 3D computer graphics software and make a 3d model yourself.\nI used Blender which is completely free to download and made a 3d model of GEEKS FOR GEEKS text. Get this file from here.\nExport the model as a .glb file to a specific folder and the filename must contain small_letters or numbers.Come back to Android Studio.\nOn the left panel, Right-Click on res directory. Go to the New > Android Resource Directory. A window will pop up.Change the Resource Type: to Raw. Click OK. A raw folder is generated, under the res directory.Copy the .glb file from that directory where you saved it and paste it under the raw folder.Step 3: Downloading and Setting up SceneForm 1.16.0\nWell, for AR apps we need Sceneform SDK. SceneForm 1.15.0 is very famous but recently, there are some plugin errors I faced while getting the \u201cGoogle Sceneform Tools (Beta)\u201d plugin in the latest Android Studio 4.1. So here I am, using the Sceneform 1.16.0 SDK and setting it up manually.Go to this GitHub link.\nDownload the \u201csceneform-android-sdk-1.16.0.zip\u201d file.\nExtract the \u2018sceneformsrc\u2018 and \u2018sceneformux\u2018 folders, where you created your project. (\u201cE:\\android\\ARApp\u201d for me)\nGo the Android Studio\nGo to Gradle Scripts > settings.gradle(Project Settings)\nAdd these lines:// this will add sceneformsrc folder into your project\ninclude \u2018:sceneform\u2019\nproject(\u2018:sceneform\u2019).projectDir = new File(\u2018sceneformsrc/sceneform\u2019)// this will add sceneformux folder into your project\ninclude \u2018:sceneformux\u2019\nproject(\u2018:sceneformux\u2019).projectDir = new File(\u2018sceneformux/ux\u2019)After that go to Gradle Scripts > build.gradle(Module:app)\nAdd this line inside the dependencies block.api project(\u201c:sceneformux\u201d)Also add the latest ARCore library as a dependency in your app\u2019s build.gradle file:dependencies { \u2026 implementation \u2018com.google.ar:core:1.32.0\u2019}Then in the same file inside the \u201candroid\u201d block and just after \u201cbuildTypes\u201d block add these lines (if it\u2019s not already there):// to support java 8 in your project\ncompileOptions {\n sourceCompatibility JavaVersion.VERSION_1_8\n targetCompatibility JavaVersion.VERSION_1_8\n}After all, these changes click \u2018Sync Now\u2018 on the pop-up above. Now the Android file structure will look like this.Then go to the app > manifests > AndroidManifest.xml\nAdd these lines before the \u201capplication\u201d block:XML \n \n \nAfter that add this line before the \u201cactivity\u201d block.XML \n Below is the complete code for the AndroidManifest.xml file.XML \n\n \n \n\n\n \n \n \n Step 4: Error Correction\nNow comes a little boring part. The downloaded folders sceneformsrc and sceneformux contains some java file, that imports the java classes from an older android.support. So, now if you build the project you will see a lot of errors because of that. What you can do now is to migrate your project to the new Androidx. Now, you can find a way to migrate your whole project to Androidx or you can change the imports manually one by one. I know this is boring, but good things come to those who wait, right?Go to Build > Rebuild Project\nYou\u2019ll find loads of errors. So down in the \u2018Build\u2019 section double-click on the package import error. A code will open with the error section highlighted.\nYou need to change only three types of import path, given below, whenever you see the first-one change it to second-one:android.support.annotation. -> androidx.annotation.\nandroidx.core.app -> androidx.fragment.app.\nandroid.support.v7.widget. -> androidx.appcompat.widget.You have to continue this till there are no more errors.Step 5: Working with the activity_main.xmlfileGo to the res > layout > activity_main.xml file.\nHere is the code of that XML file:XML \n\n ArFragment contains a lot of features itself like it asks you to download ARCore if it\u2019s already not installed in your phone or like it asks for the camera permission if it\u2019s not already granted. So ArFragment is the best thing to use here.\nAfter writing this code, the App UI will look like this:Step 6: Working with MainActivity.java fileGo to java > com.wheic.arapp(your\u2019s may differ) > MainActivity.java\nIn the MainActivity class, first, we have to make an object of ArFragment.Java // object of ArFragment Class\nprivate ArFragment arCam;Now, let\u2019s create a hardware check function outside the onCreate() function. This function will check whether your phone\u2019s hardware meets all the systemic requirements to run this AR App. It\u2019s going to check:Is the API version of the running Android >= 24 that means Android Nougat 7.0\nIs the OpenGL version >= 3.0Having these is mandatory to run AR Applications using ARCore and Sceneform. Here is the code of that function:Java public static boolean checkSystemSupport(Activity activity) {// checking whether the API version of the running Android >= 24\n// that means Android Nougat 7.0\nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {String openGlVersion = ((ActivityManager) Objects.requireNonNull(activity.getSystemService(Context.ACTIVITY_SERVICE))).getDeviceConfigurationInfo().getGlEsVersion();// checking whether the OpenGL version >= 3.0\nif (Double.parseDouble(openGlVersion) >= 3.0) {\nreturn true;\n} else {\nToast.makeText(activity, \"App needs OpenGl Version 3.0 or later\", Toast.LENGTH_SHORT).show();\nactivity.finish();\nreturn false;\n}\n} else {\nToast.makeText(activity, \"App does not support required Build Version\", Toast.LENGTH_SHORT).show();\nactivity.finish();\nreturn false;\n}\n}Inside the onCreate() function first, we need to check the phone\u2019s hardware. If it returns true, then the rest of the function will execute.\nNow the ArFragment is linked up with its respective id used in the activity_main.xml.Java // ArFragment is linked up with its respective id used in the activity_main.xml\narCam = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arCameraArea);An onTapListener is called, to show the 3d model, when we tap on the screen.\nInside the setOnTapArPlaneListener, an Anchor object is created. Anchor actually helps to bring virtual objects on the screen and make them stay at the same position and orientation in the space.\nNow a ModelRenderable class is used with a bunch of functions. This class is used to render the downloaded or created 3d model by attaching it to an AnchorNode.setSource() function helps to get the source of the 3d model.\nsetIsFilamentGltf() function checks whether it is a glb file.\nbuild() function renders the model.\nA function is called inside thenAccept() function to receive the model by attaching an AnchorNode with the ModelRenderable.\nexceptionally() function throws an exception if something goes wrong while building the model.Java arCam.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {clickNo++;// the 3d model comes to the scene only the first time we tap the screen\nif (clickNo == 1) {Anchor anchor = hitResult.createAnchor();\nModelRenderable.builder()\n.setSource(this, R.raw.gfg_gold_text_stand_2)\n.setIsFilamentGltf(true)\n.build()\n.thenAccept(modelRenderable -> addModel(anchor, modelRenderable))\n.exceptionally(throwable -> {\nAlertDialog.Builder builder = new AlertDialog.Builder(this);\nbuilder.setMessage(\"Something is not right\" + throwable.getMessage()).show();\nreturn null;\n});\n}\n});Now, let\u2019s see what\u2019s in the addModel() function:It takes two parameters, the first one is Anchor and the other one is ModelRenderable.\nAn AnchorNode object is created. It is the root node of the scene. AnchorNode automatically positioned in the world, based on the Anchor.\nTransformableNode helps the user to interact with the 3d model, like changing position, resize, rotate, etc.Java private void addModel(Anchor anchor, ModelRenderable modelRenderable) {// Creating a AnchorNode with a specific anchor\nAnchorNode anchorNode = new AnchorNode(anchor);// attaching the anchorNode with the ArFragment\nanchorNode.setParent(arCam.getArSceneView().getScene());\nTransformableNode transform = new TransformableNode(arCam.getTransformationSystem());// attaching the anchorNode with the TransformableNode\ntransform.setParent(anchorNode);// attaching the 3d model with the TransformableNode that is \n// already attached with the node\ntransform.setRenderable(modelRenderable);\ntransform.select();\n}Here is the complete code of the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.app.Activity;\nimport android.app.ActivityManager;\nimport android.app.AlertDialog;\nimport android.content.Context;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.widget.Toast;\nimport androidx.appcompat.app.AppCompatActivity;\nimport com.google.ar.core.Anchor;\nimport com.google.ar.sceneform.AnchorNode;\nimport com.google.ar.sceneform.rendering.ModelRenderable;\nimport com.google.ar.sceneform.ux.ArFragment;\nimport com.google.ar.sceneform.ux.TransformableNode;\nimport java.util.Objects;public class MainActivity extends AppCompatActivity {// object of ArFragment Class\nprivate ArFragment arCam;// helps to render the 3d model\n// only once when we tap the screen\nprivate int clickNo = 0; public static boolean checkSystemSupport(Activity activity) {// checking whether the API version of the running Android >= 24\n// that means Android Nougat 7.0\nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {\nString openGlVersion = ((ActivityManager) Objects.requireNonNull(activity.getSystemService(Context.ACTIVITY_SERVICE))).getDeviceConfigurationInfo().getGlEsVersion();// checking whether the OpenGL version >= 3.0\nif (Double.parseDouble(openGlVersion) >= 3.0) {\nreturn true;\n} else {\nToast.makeText(activity, \"App needs OpenGl Version 3.0 or later\", Toast.LENGTH_SHORT).show();\nactivity.finish();\nreturn false;\n}\n} else {\nToast.makeText(activity, \"App does not support required Build Version\", Toast.LENGTH_SHORT).show();\nactivity.finish();\nreturn false;\n}\n}@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);if (checkSystemSupport(this)) {// ArFragment is linked up with its respective id used in the activity_main.xml\narCam = (ArFragment) getSupportFragmentManager().findFragmentById(R.id.arCameraArea); \narCam.setOnTapArPlaneListener((hitResult, plane, motionEvent) -> {\nclickNo++;\n// the 3d model comes to the scene only \n// when clickNo is one that means once\nif (clickNo == 1) {\nAnchor anchor = hitResult.createAnchor();\nModelRenderable.builder()\n.setSource(this, R.raw.gfg_gold_text_stand_2)\n.setIsFilamentGltf(true)\n.build()\n.thenAccept(modelRenderable -> addModel(anchor, modelRenderable))\n.exceptionally(throwable -> {\nAlertDialog.Builder builder = new AlertDialog.Builder(this);\nbuilder.setMessage(\"Something is not right\" + throwable.getMessage()).show();\nreturn null;\n});\n}\n});\n} else {\nreturn;\n}\n}private void addModel(Anchor anchor, ModelRenderable modelRenderable) {// Creating a AnchorNode with a specific anchor\nAnchorNode anchorNode = new AnchorNode(anchor);// attaching the anchorNode with the ArFragment\nanchorNode.setParent(arCam.getArSceneView().getScene());// attaching the anchorNode with the TransformableNode\nTransformableNode model = new TransformableNode(arCam.getTransformationSystem());\nmodel.setParent(anchorNode);// attaching the 3d model with the TransformableNode \n// that is already attached with the node\nmodel.setRenderable(modelRenderable);\nmodel.select();\n}\n}Output: Run on a Physical Devicehttps://media.geeksforgeeks.org/wp-content/uploads/20201111233319/Build-a-Simple-Augmented-Reality-Android-App.mp4\nFinally, we built a simple Augmented Reality app using Android Studio. You can check this project in this GitHub link."}, {"text": "\nPoint Graph Series in Android\n\nWe have seen using a simple line graph and BarChart implementation in Android to represent data in the graphical format. Another graphical format for representing data is a point graph series. In this article, we will take a look at the implementation of the Point Graph Series in Android.\nWhat we are going to build in this article?\nWe will be building a simple application in which we will be displaying sample data in a point graph view in Android. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210127162950/Screenrecorder-2021-01-27-16-28-54-384.mp4\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add dependency to build.gradle(Module:app)\nNavigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation \u2018com.jjoe64:graphview:4.2.2\u2019After adding the above dependency now sync your project and we will now move towards the implementation of our GraphView. \nStep 3: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n \n Step 4: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.jjoe64.graphview.GraphView; \nimport com.jjoe64.graphview.series.DataPoint; \nimport com.jjoe64.graphview.series.PointsGraphSeries; public class MainActivity extends AppCompatActivity { \n@Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // initializing our variable for graph view. \nGraphView graphView = findViewById(R.id.idGraphView); // on below line we are creating a new data \n// point series for our point graph series. \n// we are calling get data point method to add \n// data point to our point graph series. \nPointsGraphSeries series = new PointsGraphSeries<>(getDataPoint()); // below line is to add series \n// to our graph view. \ngraphView.addSeries(series); // below line is to activate \n// horizontal scrolling. \ngraphView.getViewport().setScrollable(true); // below line is to activate horizontal \n// zooming and scrolling. \ngraphView.getViewport().setScalable(true); // below line is to activate vertical and \n// horizontal zoom with scrolling. \ngraphView.getViewport().setScalableY(true); // below line is to activate vertical scrolling. \ngraphView.getViewport().setScrollableY(true); // below line is to set shape \n// for the point of graph view. \nseries.setShape(PointsGraphSeries.Shape.TRIANGLE); // below line is to set \n// the size of our shape. \nseries.setSize(12); // below line is to add color \n// to our shape of graph view. \nseries.setColor(R.color.purple_200); \n} private DataPoint[] getDataPoint() { \n// creating a variable for data point. \nDataPoint[] dataPoints = new DataPoint[] \n{ \n// on below line we are adding a new \n// data point to our Data Point class. \nnew DataPoint(0, 1), \nnew DataPoint(1, 2), \nnew DataPoint(2, 3), \nnew DataPoint(3, 5), \nnew DataPoint(4, 1), \nnew DataPoint(4, 3), \nnew DataPoint(5, 3), \nnew DataPoint(6, 2) \n}; \n// at last we are returning \n// the data point class. \nreturn dataPoints; \n} \n}Now run your app and see the output of the app.\nOutput:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210127162950/Screenrecorder-2021-01-27-16-28-54-384.mp4"}, {"text": "\nHow to Create a Dynamic Audio Player in Android with Firebase Realtime Database?\n\nMany online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implementing a dynamic audio player in our Android app.\nWhat we are going to build in this article?\nIn this article, we will be building a simple application in which we will be playing an audio file from a web URL and we will be changing that audio file URL in runtime to update our audio file. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210113205758/Screenrecorder-2021-01-13-20-53-19-821.mp4\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Connect your app to Firebase \nAfter creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot. Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After completing this process you will get to see the below screen. Now verify that your app is connected to Firebase or not. Go to your build.gradle file. Navigate to the app > Gradle Scripts > build.gradle (app) file and make sure that the below dependency is added in your dependencies section. implementation \u2018com.google.firebase:firebase-database:19.6.0\u2019After adding this dependency add the dependency of ExoPlayer in your Gradle file. \nStep 3: Adding permission for the Internet \nAs we are loading our video from the internet so we have to add permissions for the Internet in the Manifest file. Navigate to the app > AndroidManifest.xml file and add the below permissions in it. XML \n \n Step 4: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n\n \n Step 5: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.media.AudioManager;\nimport android.media.MediaPlayer;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.firebase.database.DataSnapshot;\nimport com.google.firebase.database.DatabaseError;\nimport com.google.firebase.database.DatabaseReference;\nimport com.google.firebase.database.FirebaseDatabase;\nimport com.google.firebase.database.ValueEventListener;import java.io.IOException;public class MainActivity extends AppCompatActivity {// creating a variable for\n// button and media player\nButton playBtn, pauseBtn;\nMediaPlayer mediaPlayer;// creating a string for storing\n// our audio url from firebase.\nString audioUrl;// creating a variable for our Firebase Database.\nFirebaseDatabase firebaseDatabase;// creating a variable for our \n// Database Reference for Firebase.\nDatabaseReference databaseReference;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// below line is used to get the instance \n// of our Firebase database.\nfirebaseDatabase = FirebaseDatabase.getInstance();// below line is used to get reference for our database.\ndatabaseReference = firebaseDatabase.getReference(\"url\");// calling add value event listener method for getting the values from database.\ndatabaseReference.addValueEventListener(new ValueEventListener() {\n@Override\npublic void onDataChange(@NonNull DataSnapshot snapshot) {\n// this method is call to get the realtime updates in the data.\n// this method is called when the data is changed in our Firebase console.\n// below line is for getting the data from snapshot of our database.\naudioUrl = snapshot.getValue(String.class);\n// after getting the value for our audio url we are storing it in our string.\n}@Override\npublic void onCancelled(@NonNull DatabaseError error) {\n// calling on cancelled method when we receive any error or we are not able to get the data.\nToast.makeText(MainActivity.this, \"Fail to get audio url.\", Toast.LENGTH_SHORT).show();\n}\n});// initializing our buttons\nplayBtn = findViewById(R.id.idBtnPlay);\npauseBtn = findViewById(R.id.idBtnPause);// setting on click listener for our play and pause buttons.\nplayBtn.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {\n// calling method to play audio.\nplayAudio(audioUrl);\n}\n});\npauseBtn.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {\n// checking the media player \n// if the audio is playing or not.\nif (mediaPlayer.isPlaying()) {\n// pausing the media player if \n// media player is playing we are \n// calling below line to stop our media player.\nmediaPlayer.stop();\nmediaPlayer.reset();\nmediaPlayer.release();// below line is to display a message when media player is paused.\nToast.makeText(MainActivity.this, \"Audio has been paused\", Toast.LENGTH_SHORT).show();\n} else {\n// this method is called when media player is not playing.\nToast.makeText(MainActivity.this, \"Audio has not played\", Toast.LENGTH_SHORT).show();\n}\n}\n});\n}private void playAudio(String audioUrl) {\n// initializing media player\nmediaPlayer = new MediaPlayer();// below line is use to set the audio stream type for our media player.\nmediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);\ntry {\n// below line is use to set our \n// url to our media player.\nmediaPlayer.setDataSource(audioUrl);// below line is use to prepare \n// and start our media player.\nmediaPlayer.prepare();\nmediaPlayer.start();// below line is use to display a toast message.\nToast.makeText(this, \"Audio started playing..\", Toast.LENGTH_SHORT).show();\n} catch (IOException e) {\n// this line of code is use to handle error while playing our audio file.\nToast.makeText(this, \"Error found is \" + e, Toast.LENGTH_SHORT).show();\n}\n}\n}Step 6: Adding URL for your audio file in Firebase Console \nFor adding audio URL in Firebase Console. Browse for Firebase in your browser and Click on Go to Console option in the top right corner as shown in the below screenshot. After clicking on Go to Console option you will get to see your project. Click on your project name from the available list of projects.After clicking on your project. Click on the Realtime Database option in the left window. After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen. In this project, we are adding our rules as true for reading as well as write because we are not using any authentication to verify our user. So we are currently setting it to true to test our application. After changing your rules. Click on the publish button at the top right corner and your rules will be saved there. Now again come back to the Data tab. Now we will be adding our data to Firebase manually from Firebase itself.\nInside Firebase Realtime Database. Navigate to the Data tab. Inside this tab on the database section click on the \u201c+\u201d icon. After clicking on the \u201c+\u201d icon you will get to see two input fields which are the Name and Value fields. Inside the Name field, you have to add the reference for your video file which in our case is \u201curl\u201c. And in our value field, we have to add the URL for our audio file. After adding the value in this field. Click on the Add button and your data will be added to Firebase Console. After adding the URL for your video. Now run your app and see the output of the app below:\nOutput:\nYou can change the URL of your audio dynamically.\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210113205758/Screenrecorder-2021-01-13-20-53-19-821.mp4"}, {"text": "\nCreate an Expandable Notification Containing a Picture in Android\n\nNotification is a type of message that is generated by any application present inside the mobile phone, suggesting to check the application and this could be anything from an update (Low priority notification) to something that\u2019s not going right in the application (High priority notification). A basic notification consists of a title, a line of text, and one or more actions the user can perform in response. To provide even more information, one can also create large, expandable notifications by applying one of several notification templates as described in this article. Some daily life examples could be the notifications appended by Whatsapp, Gmail, SMS, etc in the notification drawer, where the user can expand it and can find some details about the message received such as sender name, subject and some part of the text in case of Gmail. In this article let\u2019s create a notification inside an application that contains a picture.Approach\nStep 1: Create a new project\nTo create a new project in android studio please refer to How to Create/Start a New Project in Android Studio.\nStep 2: Modify activity_main.xml file\nInside the XML file just add a button, which on click would build an expandable notification. By expanding the notification from the notification drawer would display a picture.activity_main.xml \n Step 3: Modify the MainActivity file\nNow, look at the code below which is in Kotlin. To start, build a notification with all the basic content as described in Create a Notification. Then, call setStyle() with a style object and supply information corresponding to each template, as shown below.MainActivity.kt package com.example.expandablenotification import android.app.* \nimport android.content.Context \nimport android.content.Intent \nimport android.graphics.BitmapFactory \nimport android.graphics.Color \nimport android.os.Build \nimport android.os.Bundle \nimport android.widget.Button \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // Assigning variables to Notification Manager, Channel and Builder \nlateinit var notifManager: NotificationManager \nlateinit var notifChannel: NotificationChannel \nlateinit var notifBuilder: Notification.Builder // Evaluating ChannelID and Description for the Custom Notification \nprivate val description = \"Some Description\"\nprivate val channelID = \"Some Channel ID\"override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Declaring the button which onclick generates a notification \nval btn = findViewById(R.id.btn) // Notification Service for the Manager \nnotifManager = getSystemService(Context.NOTIFICATION_SERVICE) \nas NotificationManager // Notifications are in the form of Intents \nval someintent = Intent(this, LauncherActivity::class.java) \nval pendingIntent = PendingIntent.getActivity( \nthis, 0, someintent, \nPendingIntent.FLAG_UPDATE_CURRENT \n) // Idea is to click the button and the notification appears \nbtn.setOnClickListener { \n// This is how an Image to be displayed in our Notification \n// is decoded and stored in a variable. I've added a picture \n// named \"download.jpeg\" in the \"Drawables\". \nval myBitmap = BitmapFactory.decodeResource(resources, \nR.drawable.download) // If Min. API level of the phone is 26, then notification could be \n// made asthetic \nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { \nnotifChannel = NotificationChannel( \nchannelID, description, \nNotificationManager.IMPORTANCE_HIGH \n) \nnotifChannel.enableLights(true) \nnotifChannel.lightColor = Color.RED \nnotifChannel.enableVibration(true) notifManager.createNotificationChannel(notifChannel) notifBuilder = Notification.Builder(this, channelID) \n.setContentTitle(\"Some Title\") \n.setContentText(\"Some Content Text\") \n.setSmallIcon(R.mipmap.ic_launcher_round) // Command to Insert Image in the Notification \n.setStyle( \nNotification.BigPictureStyle() // <---- Look here \n.bigPicture(myBitmap) \n) // <---- Look here \n.setContentIntent(pendingIntent) \n} \n// Else the Android device would give out default UI attributes \nelse { \nnotifBuilder = Notification.Builder(this) \n.setContentTitle(\"Some Title\") \n.setContentText(\"Some Content Text\") \n.setContentIntent(pendingIntent) \n} // Everything is done now and the Manager is to be notified about \n// the Builder which built a Notification for the application \nnotifManager.notify(1234, notifBuilder.build()) \n} \n} \n}Note: If you have previously searched for the code for expandable notifications, then you must have seen this particular line of code:\n\u201c.setStyle(NotificationCompat.BigPictureStyle().bigPicture(myBitmap)\u201d\nAs \u201cNotificationCompat\u201d is currently deprecated and your code would always crash whenever an attempt is made to build a notification (on button click in our case). Instead, just use \u201cNotification\u201d.Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200803103453/expandable-notification.mp4"}, {"text": "\nHow to Display Dynamic AlertDialog in Android using Firebase Firestore?\n\nDynamic AlertDialog is used in many different apps which are used to show different messages from dialog to the users. This type of dialog is also used for educating users with so many promotional banners. This type of alert dialog is generally dynamic and it displays images and texts which are dynamic in behavior and change after a certain interval. In this article, we will take a look at the implementation of the dynamic alert dialog box in Android.\nWhat we are going to build in this article?We will be building a simple alert dialog in Android. Inside that AlertDialog, we will be displaying our image and text from Firebase. The data inside our alert dialog can be changed according to our requirements. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step by Step ImplementationStep 1: Create a new Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. \nStep 2: Connect your app to Firebase\nAfter creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.\nimplementation \u2018com.google.firebase:firebase-firestore:22.0.1\u2019\nAfter adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. \nStep 3: Working with the AndroidManifest.xml file\nFor adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. XML\n \n Step 4: Working with the activity_main.xml file\nAs we are not displaying any UI inside our activity_main.xml file so we are not adding any UI component in our activity_main.xml because we are displaying the data in our custom layout file.\nStep 5: Creating a new layout file for our alert dialog\nAs we are displaying one image and text inside our alert dialog. So we will be building a custom layout for our Alert Dialog. For creating a new layout file four our custom dialog box. Navigate to the app > res > layout > Right-click on it > Click on New > layout resource file and name it as custom_pop_up_layout and add below code to it.XML\n \n \n \n \n Step 6: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Javaimport android.app.AlertDialog;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;import androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.firebase.firestore.DocumentReference;\nimport com.google.firebase.firestore.DocumentSnapshot;\nimport com.google.firebase.firestore.EventListener;\nimport com.google.firebase.firestore.FirebaseFirestore;\nimport com.google.firebase.firestore.FirebaseFirestoreException;\nimport com.squareup.picasso.Picasso;public class MainActivity extends AppCompatActivity { // initializing the variable for firebase firestore.\n FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n // creating a variable for our alert dialog builder.\n AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);\n \n // creating a layout inflater variable.\n LayoutInflater inflater = getLayoutInflater();\n \n // below line is for inflating a custom pop up layout.\n View dialoglayout = inflater.inflate(R.layout.custom_pop_up_layout, null);\n \n // initializing the textview and imageview from our dialog box.\n TextView notificationTV = dialoglayout.findViewById(R.id.idTVNotification);\n ImageView notificationIV = dialoglayout.findViewById(R.id.idIVNotification); // creating a variable for document reference.\n DocumentReference documentReference = db.collection(\"MyData\").document(\"Data\");\n \n // adding snapshot listener to our document reference.\n documentReference.addSnapshotListener(new EventListener() {\n @Override\n public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {\n // inside the on event method.\n if (error != null) {\n // this method is called when error is not null \n // and we get any error\n // in this case we are displaying an error message.\n Toast.makeText(MainActivity.this, \"Error found is \" + error, Toast.LENGTH_SHORT).show();\n return;\n }\n if (value != null && value.exists()) {\n // if the value from firestore is not null then we are\n // getting our data and setting that data to our text view.\n // after getting the value from firebase firestore\n // we are setting it to our text view and image view.\n notificationTV.setText(value.getData().get(\"NotificationMessage\").toString());\n Picasso.get().load(value.getData().get(\"NotificationImage\").toString()).into(notificationIV);\n }\n }\n });\n \n // after setting the text to our text view.\n // we are displaying our alert dialog.\n builder.setView(dialoglayout);\n builder.show();\n }\n}Step 7: Adding the data to Firebase Firestore Console in Android\nAfter adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. Inside that screen click n Firebase Firestore Database in the left window. After clicking on Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside Firebase Console. For adding the data click on the Start Collection option and add your collection Name as \u201cMyData\u201c. After adding this we have to add our Document ID as \u201cData\u201c. Inside the fields section, we have to add our field name as \u201cNotificationImage\u201d for displaying our image in the notification and enter the corresponding value of it (URL for the image). And create another file and name the field as \u201cNotificationMessage\u201d to display the message inside our notification. Also, enter the corresponding value of it. At last click on the Save button.After adding data the screen will look like the following. You can edit and delete those files.Now run the app and see the output of the app below :\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210114142312/Screenrecorder-2021-01-14-14-18-47-533.mp4\n"}, {"text": "\nResponsive UI Design in Android\n\nNowadays every Android UI designer is very serious about his UI design. The path of every project goes through UI design. UI design is the face of every project and every website, app & desktop application. UI is the wall between the User & Back-end where users can interact with the server through the UI design. There is a various aspect where UI designer need to consider while designing any software product, Such as What is the theme of the project? Which is the target audience? either it\u2019s 18+ or Old age audience, Does this UI support all types of screens or not?, and many more question arises in UI designer\u2019s mind. In this article, we will talk about the future of UI in Android.\nIn Android, there have various platforms where developers developed their Android application, such as Android Studio, Eclipse, React Native, etc. The Majority of the developer preferred. To make the android app responsive we need to make every individual screen for every type of screen size, Such as Large, X-large, Normal. Let\u2019s see these images.\nNormal ScreenLarge Screen SizeX-Large Screen SizeSmall Screen SizeThese are very troubling steps for every designer to redesign for every individual screen. Due to this time of the project will also be increased. To Overcome this type of issue google introduces the Material Component for android design, It Overcomes the responsiveness as much as possible. Material Components supports all screen sizes.\nUsing Material Component in Android Apps\nAdding a material component you need to simply add this dependency in your Gradle fileimplementation \u2018com.google.android.material:material:1.2.1\u2019After adding this dependency you will able to use the material component in your android project.XML To make our design more stylish and attractive as well as responsive you need to use Material Card View in your layout.XML Material Card View automatically manages the padding and margin as well as sizes sometimes. You can add gradient color inside the card by using a third-party library its looks so awesome. You can add a menu inside the card block, you can add a slider in the card.\nExample\nLet\u2019s Take One Example with android studio. Now we can design an android layout using XML. We can design a material card view component first. Material Card View with parent padding.XML \n Output UI:Material Card View without padding:XML \n If you use the material card view without padding then the material component can automatically add default padding and color. This can also be helpful for responsive UI design.If you use the normal card view then it can not provide any responsiveness in layout. Also, the normal components do not look as stylish as other material components.There are many aspects that were material component is easier & flexible than normal components such as shadow, border, etc.\nAdvantages of Material ComponentMaterial components are lightweight.\nThe material component looks great as compared to others.\nMaterial component very much as responsive.Disadvantages of material componentSome times component does not work properly in a real device."}, {"text": "\nRadioButtons in Android using Jetpack Compose\n\nRadioButtons are used to select only a specific option from the list of several options in a list or either. Radio buttons are used in many places for selecting only one option from the list of two or more options. In this article, we will take a look at the implementation of this Radio button in Android using Jetpack Compose.\nAttributes of Radio ButtonAttribute\nDescriptionsselected\nthis attribute is used to make a radio button selected.onClick\nthis is used when our radio button is clicked.modifier\nto add padding to our radio buttons.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.\nStep 2: Working with the MainActivity.kt file\nNavigate to the app > java > your app\u2019s package name and open the MainActivity.kt file. Inside that file add the below code to it. Comments are added inside the code to understand the code in more detail.Kotlin import android.graphics.drawable.shapes.Shape\nimport android.media.Image\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.compose.foundation.*\nimport androidx.compose.foundation.Text\nimport androidx.compose.foundation.layout.*\nimport androidx.compose.foundation.selection.selectable\nimport androidx.compose.foundation.shape.CircleShape\nimport androidx.compose.foundation.shape.RoundedCornerShape\nimport androidx.compose.foundation.text.KeyboardOptions\nimport androidx.compose.material.*\nimport androidx.compose.material.Icon\nimport androidx.compose.material.icons.Icons\nimport androidx.compose.material.icons.filled.AccountCircle\nimport androidx.compose.material.icons.filled.Info\nimport androidx.compose.material.icons.filled.Menu\nimport androidx.compose.material.icons.filled.Phone\nimport androidx.compose.runtime.*\nimport androidx.compose.runtime.savedinstancestate.savedInstanceState\nimport androidx.compose.ui.Alignment\nimport androidx.compose.ui.layout.ContentScale\nimport androidx.compose.ui.platform.setContent\nimport androidx.compose.ui.res.imageResource\nimport androidx.compose.ui.tooling.preview.Preview\nimport androidx.compose.ui.unit.dp\nimport com.example.gfgapp.ui.GFGAppTheme\nimport androidx.compose.ui.Modifier\nimport androidx.compose.ui.draw.clip\nimport androidx.compose.ui.graphics.Color\nimport androidx.compose.ui.graphics.SolidColor\nimport androidx.compose.ui.platform.ContextAmbient\nimport androidx.compose.ui.platform.testTag\nimport androidx.compose.ui.res.colorResource\nimport androidx.compose.ui.semantics.SemanticsProperties.ToggleableState\nimport androidx.compose.ui.text.TextStyle\nimport androidx.compose.ui.text.font.FontFamily\nimport androidx.compose.ui.text.input.*\nimport androidx.compose.ui.unit.Dp\nimport androidx.compose.ui.unit.TextUnitclass MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContent {\nColumn {\n// in below line we are calling\n// a radio button method.\nSimpleRadioButtonComponent()\n}\n}\n}\n}@Preview(showBackground = true)\n@Composable\nfun DefaultPreview() {\nGFGAppTheme {\nSimpleRadioButtonComponent();\n}\n}@Composable\nfun SimpleRadioButtonComponent() {\nval radioOptions = listOf(\"DSA\", \"Java\", \"C++\")\nval (selectedOption, onOptionSelected) = remember { mutableStateOf(radioOptions[2]) }\nColumn(\n// we are using column to align our \n// imageview to center of the screen.\nmodifier = Modifier.fillMaxWidth().fillMaxHeight(),// below line is used for \n// specifying vertical arrangement.\nverticalArrangement = Arrangement.Center,// below line is used for \n// specifying horizontal arrangement.\nhorizontalAlignment = Alignment.CenterHorizontally,\n) {\n// we are displaying all our\n// radio buttons in column.\nColumn {\n// below line is use to set data to\n// each radio button in columns.\nradioOptions.forEach { text ->\nRow(\nModifier\n// using modifier to add max \n// width to our radio button.\n.fillMaxWidth()\n// below method is use to add \n// selectable to our radio button.\n.selectable(\n// this method is called when \n// radio button is selected.\nselected = (text == selectedOption),\n// below method is called on \n// clicking of radio button.\nonClick = { onOptionSelected(text) }\n)\n// below line is use to add\n// padding to radio button.\n.padding(horizontal = 16.dp)\n) {\n// below line is use to get context.\nval context = ContextAmbient.current// below line is use to \n// generate radio button\nRadioButton(\n// inside this method we are \n// adding selected with a option.\nselected = (text == selectedOption),modifier = Modifier.padding(all = Dp(value = 8F)),\nonClick = {\n// inside on click method we are setting a \n// selected option of our radio buttons.\nonOptionSelected(text)// after clicking a radio button \n// we are displaying a toast message.\nToast.makeText(context, text, Toast.LENGTH_LONG).show()\n}\n)\n// below line is use to add \n// text to our radio buttons.\nText(\ntext = text,\nmodifier = Modifier.padding(start = 16.dp)\n)\n}\n}\n}\n}\n}Now run your app and see the output of the app.Output:https://media.geeksforgeeks.org/wp-content/uploads/20210118232236/Screenrecorder-2021-01-18-23-19-42-380.mp4"}, {"text": "\nAndroid Animations using Java\n\nThe animation is a method in which a collection of images is combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seems to be alive. Android has quite a few tools to help you create animations with relative ease. So in this article, let\u2019s learn to create android animations using Java.\nTable of AttributesXML ATTRIBUTES\nDESCRIPTIONandroid:id\nSets unique id of the viewandroid:duration\nUsed to specify the duration of the animationandroid:fromDegrees\nStarting angular position (in degrees)android:toDegrees\nEnding angular position (in degrees)android:fromXScale\nStarting X size offsetandroid:toXScale\nEnding of X size offsetandroid:fromYScale\nStarting Y size offsetandroid:toYScale\nEnding of Y size offsetandroid:fromAlpha\nStarting alpha value for the animation(1.0 means fully opaque and 0.0 means fully transparent)android:toAlpha\nEnding alpha valueandroid:fromYDelta\nChange in Y coordinate to be applied at the beginning of the animationandroid:toYDelta\nChange in Y coordinate to be applied at the end of the animationandroid:pivotX\nRepresents the X-axis coordinates to zoom from the starting pointandroid:pivotY\nRepresents the Y-axis coordinates to zoom from the starting pointandroid:interpolator\nIt defines the rate of change of an animationandroid:startOffset\nDelay occurs when an animation runs (in ms), once start time is reachedHow to add animation in Android using Java\nStep 1: Create a New ProjectStart Android Studio (version > 2.2)\nGo to File -> New -> New Project.\nSelect Empty Activity and click on next\nSelect minimum SDK as 21\nChoose the language as Java and click on the finish button.\nModify the following XML and java files.Step 2: Modify activity_main.xml file\nIn the XML file, we have added an ImageView, TextView, and Button inside the RelativeLayout.XML \n Step 3: Add these XML files to the anim directory\nAfter modifying the layout we will create XML files for animations. So we will first create a folder name anim. In this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right-click and then select Android Resource Directory and name it as anim.\nSome Common Types of Animations in Android are, Blink \u2013 Hides the object for 0.6 to 1 second.\nSlide \u2013 Move the object either vertically or horizontally to its axis.\nRotate \u2013 Rotate the object either clockwise or anti-clockwise.\nZoom \u2013 Zoom in or out the object in the X and Y-axis.blinks.xml \n \n \n rotate.xml \n \n \n slides.xml \n \n zoom.xml \n \n \n Step 4: Modify MainActivity.java\nTo perform animation in android, we have to call a static function loadAnimation() of the class AnimationUtils. We get the result in an instance of the Animation Object. Syntax to create animation object:Animation object = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.ANIMATIONFILE);To apply the above animation to an object(Let say in an image), we have to call the startAnimation() method of the object. Syntax to call the method:ImageView image = findViewById(R.id.imageID);\nimage.startAnimation(object);Methods of animation class:MethodDescriptionstartAnimation(object)\nStarts the animationsetDuration(long duration)\nSets the duration of animationgetDuration()\nGets the duration of animationend()\nEnds the animationcancel()\nCancels the animationJava import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.view.animation.Animation; \nimport android.view.animation.AnimationUtils; \nimport android.widget.Button; \nimport android.widget.ImageView; public class MainActivity extends AppCompatActivity { \nImageView logo; \nButton blink, slide, rotate, zoom; @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // GFG logo \nlogo = findViewById(R.id.imageView1); // blink button \nblink = findViewById(R.id.button1); // slide button \nslide = findViewById(R.id.button2); // rotate button \nrotate = findViewById(R.id.button3); // zoom button \nzoom = findViewById(R.id.button4); // blink button listener \nblink.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) \n{ \n// call a static function loadAnimation() \n// of the class AnimationUtils \nAnimation object \n= AnimationUtils \n.loadAnimation( \ngetApplicationContext(), // blink file is in anim folder \nR.anim.blinks); \n// call the startAnimation method \nlogo.startAnimation(object); \n} \n}); \n// slide button listener \nslide.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) \n{ \n// call a static function loadAnimation() \n// of the class AnimationUtils \nAnimation object \n= AnimationUtils \n.loadAnimation( getApplicationContext(), // slide file is in anim folder \nR.anim.slide); // call the startAnimation method \nlogo.startAnimation(object); \n} \n}); // rotate button listener \nrotate.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) \n{ \n// call a static function loadAnimation() \n// of the class AnimationUtils \nAnimation object \n= AnimationUtils \n.loadAnimation( \ngetApplicationContext(), // rotate file is in anim folder \nR.anim.rotate); // call the startAnimation method \nlogo.startAnimation(object); \n} \n}); // zoom button listener \nzoom.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) \n{ \n// call a static function loadAnimation() \n// of the class AnimationUtils \nAnimation object \n= AnimationUtils \n.loadAnimation( \ngetApplicationContext(), // zoom file is in anim folder \nR.anim.zoom); // call the startAnimation method \nlogo.startAnimation(object); \n} \n}); \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200702012037/20200702_011824.mp4"}, {"text": "\nIntroduction to Activities in Android\n\nActivity class is one of the very important parts of the Android Component. Any app, don\u2019t matter how small it is (in terms of code and scalability), has at least one Activity class. Unlike most programming languages, in which the main() method is the entry point for that program or application to start its execution, the android operating system initiates the code in an Activity instance by invoking specific callback methods that correspond to specific stages of its Lifecycle. So it can be said that An activity is the entry point for interacting with the user. Every activity contains the layout, which has a user interface to interact with the user. As we know that every activity contains a layout associated with it, so it can be said that the activity class is the gateway, through which a user can interact programmatically with the UI. Layout for a particular activity is set with the help of setContentView(). setContentView() is a function that takes View as a parameter. The view parameter basically contains the layout file for that activity. The code has been given in both Java and Kotlin Programming Language for Android.\nThe Following Code Indicates that activity_main is the Layout File of MainActivityKotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} \n}Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \n} \n}While activities are often presented to the user as the full-screen window, Multiwindow mode, or Picture in Picture mode, here are two methods almost all subclasses of Activity will implement:onCreate()\nonPause()1. onCreate() Method\nThe syntax for Kotlin:\noverride fun onCreate(savedInstanceState: Bundle?)\nThe syntax for Java:\nprotected void onCreate(Bundle savedInstanceState)onCreate(Bundle) method is the place, where the user initializes the activity. This method is called when the activity is starting. This is the method that is used to initialize most of the things in the android app. onCreate() method takes savedInstanceState as the parameter, which the object of type Bundle, i.e Bundle Object which contains the previously saved data of the activity. If the activity is newly created then the bundle won\u2019t be saving any data of the activity and would contain the null value.\nonCreate() method calls the setContentView() method to set the view corresponding to the activity. By default in any android application, setContentView point to activity_main.xml file, which is the layout file corresponding to MainActivity. The onCreate method uses the findViewById() method so that the user can interact programmatically with the widgets in android and then customize them according to need.Bundle: If the activity is being re-initialized or restarted after previously being closed, then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). onSaveInstanceState() method is the method that is called to save the data just before our activity is killed.\n2. onPause() Method\nThe syntax for Kotlin:\noverride fun onPause() {\n super.onPause()\n}\nThe syntax for Java:\nprotected void onPause() {\n super.onPause();\n}\nThis method is called part of the Activity Lifecycle when the user no longer actively interacts with the activity, but it is still visible on the screen. Let\u2019s suppose the user is running two apps simultaneously on a mobile phone, i.e when activity B is launched in front of activity A, activity A will go in the onPause() state, and activity B would go in the onStart() state of the activity lifecycle. One important point to be remembered is that for any activity to be accessed by a system, i.e. android here, that activity must be declared in a Manifest File. The Manifest File is an XML file included in the Application and is by default known as AndroidManifest.xml.\nDeclaring Activity in Manifest File\nOpen the app folder, and then open the subfolder manifest, and then open the AndroidManifest.xml file.Let\u2019s suppose the reader wants to have one more activity, apart from the MainActivity which is included by default in the project. Before adding one more activity and not doing any changes,\nLet\u2019s see what the AndroidManifest.xml File looks likeXML \n \n \n \n \n \n \n Now let\u2019s add another activity named SecondActivity, and see how to declare it in the manifest file. One must write the Declaration Code within the application tag, otherwise, the declaration will give the error, and SecondActitvity will not be detected by the System. The Declaration Code is given below.\n\n \nSo it can conclude that an application can have one or more activities without any restrictions. Every activity that the android app uses must be declared in the AndroidManifest.xml file. and the main activity for the app must be declared in the manifest with a that includes the MAIN action and LAUNCHER. Any activity whether it is MainActivity or any other activity must be declared within the of the AndroidManifest file. If the user forgets to declare any of the activity, then android will not be able to detect that activity in the app. If either the MAIN action or LAUNCHER category is not declared for the main activity, then the app icon will not appear in the Home screen\u2019s list of apps.\nAdding Permissions to Application\nFor any service that the Developer wants to use in the Android App, like Internet service, Bluetooth service, Google Maps, App Notification service, etc, the Developer needs to take the permission of the Android System. All those Permissions or Requests must be declared within the Manifest File. Open the AndroidManifest.xml file, with the procedure shown above. Let\u2019s say the user needs to add Internet permission, that needs to be accessed by the app. Add the below Internet Permission within the manifest tag.\n \nLet\u2019s say one needs to add Bluetooth permission within the app, then it must be declared like this:\n \nNote: Let\u2019s say that the MainActivity extends AppCompatActivity in the code snippet given at the top, internally the structure is as shown in the image given below. It can be seen that AppCompatActivity also extends the Activity Class."}, {"text": "\nCustom Snackbars in Android\n\nSnackBars plays a very important role in the user experience. The snack bar which may or may not contain the action button to do shows the message which had happened due to the user interaction immediately. So in this article, it\u2019s been discussed how the SnackBars can be implemented using custom layouts. Have a look at the following image to get an idea of how can the custom-made SnackBars can be differentiated from the regular(normal) SnackBars. Note that we are going toimplement this project using theJavalanguage.Steps to Implement the Custom SnackBars in Android\nStep 1: Create an empty activity projectCreate an empty activity Android Studio project. And select the JAVA as a programming language.\nRefer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android studio project.Step 2: Working with the activity_main.xml fileThe main layout here includes only one button which when clicked the custom SnackBar is to be shown.\nInvoke the following code, in the activity_main.xml file.XML \n Output UI: Run on EmulatorStep 3: Creating a custom layout for SnackbarUnder layout folder create a layout for SnackBar which needs to be inflated when building the SnackBar under the MainActivity.java file.XML \n \n \n Which produces the following view:Step 4: Working with the MainActivity.java fileJava import androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport com.google.android.material.snackbar.Snackbar;public class MainActivity extends AppCompatActivity {Button bShowSnackbar;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// register the button with appropriate ID\nbShowSnackbar = findViewById(R.id.showSnackbarButton);bShowSnackbar.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {// create an instance of the snackbar\nfinal Snackbar snackbar = Snackbar.make(v, \"\", Snackbar.LENGTH_LONG);// inflate the custom_snackbar_view created previously\nView customSnackView = getLayoutInflater().inflate(R.layout.custom_snackbar_view, null);// set the background of the default snackbar as transparent\nsnackbar.getView().setBackgroundColor(Color.TRANSPARENT);// now change the layout of the snackbar\nSnackbar.SnackbarLayout snackbarLayout = (Snackbar.SnackbarLayout) snackbar.getView();// set padding of the all corners as 0\nsnackbarLayout.setPadding(0, 0, 0, 0);// register the button from the custom_snackbar_view layout file\nButton bGotoWebsite = customSnackView.findViewById(R.id.gotoWebsiteButton);// now handle the same button with onClickListener\nbGotoWebsite.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {\nToast.makeText(getApplicationContext(), \"Redirecting to Website\", Toast.LENGTH_SHORT).show();\nsnackbar.dismiss();\n}\n});// add the custom snack bar layout to snackbar layout\nsnackbarLayout.addView(customSnackView, 0);snackbar.show();\n}\n});\n}\n}Kotlin import androidx.appcompat.app.AppCompatActivity;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;\nimport com.google.android.material.snackbar.Snackbar;class MainActivity : AppCompatActivity() {\nvar bShowSnackbar: Button? = null\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// register the button with appropriate ID\nbShowSnackbar = findViewById(R.id.showSnackbarButton)\nbShowSnackbar.setOnClickListener(object : OnClickListener() {\nfun onClick(v: View?) {// create an instance of the snackbar\nval snackbar = Snackbar.make(v, \"\", Snackbar.LENGTH_LONG)// inflate the custom_snackbar_view created previously\nval customSnackView: View =\nlayoutInflater.inflate(R.layout.custom_snackbar_view, null)// set the background of the default snackbar as transparent\nsnackbar.view.setBackgroundColor(Color.TRANSPARENT)// now change the layout of the snackbar\nval snackbarLayout = snackbar.view as SnackbarLayout// set padding of the all corners as 0\nsnackbarLayout.setPadding(0, 0, 0, 0)// register the button from the custom_snackbar_view layout file\nval bGotoWebsite: Button = customSnackView.findViewById(R.id.gotoWebsiteButton)// now handle the same button with onClickListener\nbGotoWebsite.setOnClickListener(object : OnClickListener() {\nfun onClick(v: View?) {\nToast.makeText(\napplicationContext,\n\"Redirecting to Website\",\nToast.LENGTH_SHORT\n).show()\nsnackbar.dismiss()\n}\n})// add the custom snack bar layout to snackbar layout\nsnackbarLayout.addView(customSnackView, 0)\nsnackbar.show()\n}\n})\n}\n}\n//This code is written by Ujjwal kumar BhardwajOutput: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201128201645/GFG_nexus_5.mp4"}, {"text": "\nEditText widget in Android using Java with Examples\n\nWidget refers to the elements of the UI (User Interface) that helps user interacts with the Android App. Edittext is one of many such widgets which can be used to retrieve text data from user.\nEdittext refers to the widget that displays an empty textfield in which a user can enter the required text and this text is further used inside our application.\nClass Syntax:\npublic class EditText\nextends TextView\nClass Hierarchy:\njava.lang.Object\n \u21b3android.view.View\n \u21b3 android.widget.TextView\n \u21b3 android.widget.EditText\nSyntax:\n\n .\n .\n \n .\n .\n \nHere the layout can be any layout like Relative, Linear, etc (Refer this article to learn more about layouts). And the attributes can be many among the table given below in this article.\nExample:\n > How to include a Edittext in an Android App:First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity.\nOpen the Activity file and include a Edittext field in the layout (activity_main.xml) file of the activity and also add a Button in activity_main.xml file too.\nNow in the Java file, link this layout file with the below code:@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n}\nwhere activity_main is the name of the layout file to be attached.Now we will add code in MainActivity.java file to make our layout interactive or responsive. Our application will generate a toast on clicking the button with the text \u201cWelcome to GeeksforGeeks [Name as entered by user]\u201c\nThe complete code of the layout file and the Java file is given below.Below is the implementation of the above approach:\nFilename: activity_main.xmlXML Filename: MainActivity.javaJava package com.project.edittext;import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;public class MainActivity extends AppCompatActivity {private EditText editText;\nprivate Button button;@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);editText\n= (EditText)findViewById(R.id.edittext_id);\nbutton\n= (Button)findViewById(R.id.button_id);button.setOnClickListener(\nnew View.OnClickListener() {@Override\npublic void onClick(View v)\n{\nString name\n= editText.getText()\n.toString();\nToast.makeText(MainActivity.this,\n\"Welcome to GeeksforGeeks \"\n+ name,\nToast.LENGTH_SHORT)\n.show();\n}\n});\n}\n}Output: Upon starting of the App and entering the name in EditText. The name in the EditText is then displayed:XML Attributes of Edittext in AndroidAttributes\nDescriptionandroid:id\nUsed to uniquely identify the controlandroid:gravity\nUsed to specify how to align the text like left, right, center, top, etc.android:hint\nUsed to display the hint text when text is emptyandroid:text\nUsed to set the text of the EditTextandroid:textSize\nUsed to set size of the text.android:textColor\nUsed to set color of the text.android:textStyle\nUsed to set style of the text. For example, bold, italic, bolditalic, etc.android:textAllCaps\nUsed this attribute to show the text in capital letters.android:width\nIt makes the TextView be exactly this many pixels wide.android:height\nIt makes the TextView be exactly this many pixels tall.android:maxWidth\nUsed to make the TextView be at most this many pixels wide.android:minWidth\nUsed to make the TextView be at least this many pixels wide.android:background\nUsed to set background to this View.android:backgroundTint\nUsed to set tint to the background of this view.android:clickable\nUsed to set true when you want to make this View clickable. Otherwise, set false.android:drawableBottom\nUsed to set drawable to bottom of the text in this view.android:drawableEnd\nUsed to set drawable to end of the text in this view.android:drawableLeft\nUsed to set drawable to left of the text in this view.android:drawablePadding\nUsed to set padding to drawable of the view.android:drawableRight\nUsed to set drawable to right of the text in this view.android:drawableStart\nUsed to set drawable to start of the text in this view.android:drawableTop\nUsed to set drawable to top of the text in this view.android:elevation\nUsed to set elevation to this view."}, {"text": "\nHow to Add a TextView with Rounded Corner in Android?\n\nTextView is an essential object of an Android application. It comes in the list of some basic objects of android and used to print text on the screen. In order to create better apps, we should learn that how can we create a TextView which have a background with rounded corners. We can implement this skill in a practical manner for any android application. For creating professional-looking user interfaces, we need to take care of these small things.\nIn this article, You will be learning how to create a TextView with Rounded Corners. First of all, we need to create a drawable resource file, which has a proper definition to make TextView corners rounded, and then we have to add a background attribute to that special TextView object. Let\u2019s do it in steps!\nStep by Step Implementation\nStep 1: Create a new android studio project, and select an empty activity. You can also refer to this GFG Tutorial for Creating a new android studio project.\nStep 2: Make sure that you have selected the Android option for project structure on the top left corner of the screen, then go to the res/drawable folder.Step 3: Here right-click on the drawable folder and click on new and select drawable resource file. Give it a name of your choice, we are giving it rounded_corner_view.Note: In android studio you can\u2019t give a name of a resource file (Layout file, Color File, Image File, or any XML file) in uppercase and camelCase, you have to follow the lowercase letters only and it\u2019s a good habit to use lowercase letters with underscores in place of spaces.Step 4: Now in the drawable resource file, which you have just created, remove all the default code and paste the following code.XML \n \n Step 5: Now go to the activity_main.xml file and add an attribute to that TextView, for which you want to add rounded corners. The attribute is android: background=\u201d@drawable/rounded_corner_view\u201d.Tip: Don\u2019t forget to replace your drawable resource file name if you have given a different name and you don\u2019t need to add xml extension after file name.Output UI:"}, {"text": "\nHow to Create an Alert Dialog Box in Android?\n\nAlert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response, the next step is processed. Android Alert Dialog is built with the use of three fields: Title, Message area, and Action Button.\nAlert Dialog code has three methods:setTitle() method for displaying the Alert Dialog box Title\nsetMessage() method for displaying the message\nsetIcon() method is used to set the icon on the Alert dialog box.Then we add the two Buttons, setPositiveButton and setNegativeButton to our Alert Dialog Box as shown below.\nExample:Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n Step 3: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.content.DialogInterface; \nimport android.os.Bundle; \nimport androidx.appcompat.app.AlertDialog; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \n} // Declare the onBackPressed method when the back button is pressed this method will call \n@Override\npublic void onBackPressed() { \n// Create the object of AlertDialog Builder class \nAlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // Set the message show for the Alert time \nbuilder.setMessage(\"Do you want to exit ?\"); // Set Alert Title \nbuilder.setTitle(\"Alert !\"); // Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show \nbuilder.setCancelable(false); // Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface. \nbuilder.setPositiveButton(\"Yes\", (DialogInterface.OnClickListener) (dialog, which) -> { \n// When the user click yes button then app will close \nfinish(); \n}); // Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface. \nbuilder.setNegativeButton(\"No\", (DialogInterface.OnClickListener) (dialog, which) -> { \n// If user click no then dialog box is canceled. \ndialog.cancel(); \n}); // Create the Alert dialog \nAlertDialog alertDialog = builder.create(); \n// Show the Alert Dialog box \nalertDialog.show(); \n} \n}Kotlin import android.os.Bundle \nimport androidx.appcompat.app.AlertDialog \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} // Declare the onBackPressed method when the back button is pressed this method will call \noverride fun onBackPressed() { \n// Create the object of AlertDialog Builder class \nval builder = AlertDialog.Builder(this) // Set the message show for the Alert time \nbuilder.setMessage(\"Do you want to exit ?\") // Set Alert Title \nbuilder.setTitle(\"Alert !\") // Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show \nbuilder.setCancelable(false) // Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface. \nbuilder.setPositiveButton(\"Yes\") { \n// When the user click yes button then app will close \ndialog, which -> finish() \n} // Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface. \nbuilder.setNegativeButton(\"No\") { \n// If user click no then dialog box is canceled. \ndialog, which -> dialog.cancel() \n} // Create the Alert dialog \nval alertDialog = builder.create() \n// Show the Alert Dialog box \nalertDialog.show() \n} \n}Output:"}, {"text": "\nHow to Install Genymotion Emulator and Add it\u2019s Plugin to Android Studio?\n\nGenymotion is an Android Emulator that is faster than the Android Studio Emulator. Genymotion emulator offers a wide range of virtual devices for development, test, and demonstration purpose. It has a very simple user interface and one can directly use it from Android Studio by installing its plugin only once. The Genymotion plugin for Android Studio allows testing the application developed with the Android Studio IDE. It uses ADB to connect to any active virtual device and push the application. So in this article let\u2019s discuss how to install the Genymotion Emulator and also installing its plugin in the Android Studio to run the program.\nStep by Step Implementation\nStep 1: First we have to install Genymotion in our own system. So to download Genymotion please go to this site. Then click on the \u201cDownload Genymotion Personal Edition\u201d button.Note: Please sign in yourself to Genymotion if you have already not an account on Genymotion.Step 2: In the next step click on the button as your requirement. If you have already installed VirtualBox on your system then go for the 2nd button and if not then go for the 1st button as shown in the below image. If you are using macOS or Linux then scroll below on that page and get your file.Step 3: Once the download is completed install the Genymotion in your system and open Genymotion. After opening Genymotion sign in yourself with your ID and password.Note: If a pop-up will arise on the screen then click on the Personal Use button.Step 4: Now click on the Genymotion and go to the Settings as shown in the below image.Step 5: Then go to ADB and choose \u201cUse custom Android SDK tools\u201d and select your Android SDK path as shown in the below image. And there is nothing to do with other widgets. Now close this screen.How to know the Android SDK path in your system?\nTo know the Android SDK path open your Android Studio and click on the Tools > SDK Manager as shown in the below image.Then a screen will arise as in the below image and you can locate your Android SDK path.Step 6: Now click on the \u2018pink +\u2018 screen as shown in the below image.Step 7: Now search your favorite virtual device name and click on the device name and at last click on the NEXT button as shown in the below image.Step 8: Choose an appropriate name for your emulator and then click on the INSTALL button. This will take a few times to download the required files.Step 9: After successfully downloaded the required files you can find your emulator on the main screen. Now click on the Start button as shown below image and your Genymotion emulator is ready for use.This is how Genymotion Emulator looks like.How to add Genymotion Plugin to Android Studio?In computing, a plug-in is a software component that adds a specific feature to an existing computer program. When a program supports plug-ins, it enables customization.Similarly, we have to add the Genymotion plug-in to Android studio to use the Genymotion Emulator for developing and testing the project. To do so follow the following steps:\nStep 1: Open the Android Studio and go to File > Settings and a pop-up will arise as seen in the below image. This will automatically select the Plugins section. Then search the Genymotion plugins and click on the Install button. This will download some files and it will ask to restart the Android studio and so click on the Restart Android Studio button.Note: We have already installed the Genymotion plugin so it\u2019s showing installed.Step 2: After successfully restart the Android Studio again go to File > Settings > Other Settings > Genymotion as shown in the below image.Step 3: Then select the path to the Genymotion folder. In most cases, you can find the path at C:\\Program Files\\Genymobile\\Genymotion. Then just click on OK and you are done.Make sure your Genymotion Emulator is started and you can see the Genymotion Emulator is active you can execute your program on that emulator as shown in the below image."}, {"text": "\nPull to Refresh with RecyclerView in Android with Example\n\nThe SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. Where the user uses the vertical swipe gesture to refresh the content of the views. The vertical swipe is detected by the SwipeRefreshLayout widget and it displays a distinct progress bar and triggers the callback methods in the app. In order to use this behavior, we need to use the SwipeRefreshLayout widget as the parent of a ListView or GridView. These Material Design UI Patterns are seen in applications like Gmail, Youtube, Facebook, Instagram, etc. It allows the user to refresh the application manually. SwipeRefreshLayout class contains a listener called OnRefreshListener. The classes which want to use this listener should implement SwipeRefreshLayout.OnRefreshListener interface. On vertical swipe-down gesture, this listener is triggered and onRefresh() method is called and can be overridden according to the needs.\nExample\nIn this example, we would store data into the ArrayList which is used for populating the RecyclerView. Whenever onRefresh() method is called the ArrayList data gets rearranged. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Adding dependencies\nWe are going to use RecyclerView and SwipeRefreshLayout. So, we need to add dependencies for them. For adding these dependencies Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now.dependencies {\n implementation \u201candroidx.recyclerview:recyclerview:1.1.0\u201d\n implementation \u201candroidx.swiperefreshlayout:swiperefreshlayout:1.1.0\u201d\n}Before moving further let\u2019s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.XML \n#0F9D58 \n#16E37F \n#03DAC5 \n Step 3: Working with the activity_main.xmlfile\nIn this step, we will create SwipeRefreshLayout and Add RecyclerView to it. Go to app > res > layout > activity_main.xml and add the following code snippet.XML \n Step 4: Create a new layout file list_item.xml for the list items of RecyclerView.Go to the app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml layout file contains an ImageView and a TextView which is used for populating the rows of RecyclerView.XML \n\n Step 5: Creating Adapter class for RecyclerViewNow, we will create an Adapter.java class that will extend the RecyclerView.Adapter with ViewHolder. Go to the app > java > package > right-click and create a new java class and name it as Adapter. In Adapter class we will override the onCreateViewHolder() method which will inflate the list_item.xml layout and pass it to View Holder. Then onBindViewHolder() method where we set data to the Views with the help of View Holder. Below is the code snippet for Adapter.java class.Java import android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.ArrayList;// Extends the Adapter class to RecyclerView.Adapter\n// and implement the unimplemented methods\npublic class Adapter extends RecyclerView.Adapter {\nArrayList images, text;\nContext context;// Constructor for initialization\npublic Adapter(Context context, ArrayList images, ArrayList text) {\nthis.context = context;\nthis.images = images;\nthis.text = text;\n}@NonNull\n@Override\npublic Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n// Inflating the Layout(Instantiates list_item.xml layout file into View object)\nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);// Passing view to ViewHolder\nAdapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);\nreturn viewHolder;\n}// Binding data to the into specified position\n@Override\npublic void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) {\n// TypeCast Object to int type\nint res = (int) images.get(position);\nholder.images.setImageResource(res);\nholder.text.setText((CharSequence) text.get(position));\n}@Override\npublic int getItemCount() {\n// Returns number of items currently available in Adapter\nreturn text.size();\n}// Initializing the Views\npublic class ViewHolder extends RecyclerView.ViewHolder {\nImageView images;\nTextView text;public ViewHolder(View view) {\nsuper(view);\nimages = (ImageView) view.findViewById(R.id.imageView);\ntext = (TextView) view.findViewById(R.id.textView);\n}\n}\n}Step 6: Working with MainActivity.java fileIn MainActivity.java class we create two ArrayList for storing images and text. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of this. And then we get the reference of SwipeRefreshLayout and RecyclerView and set the LayoutManager and Adapter to show items in RecyclerView and implement onRefreshListener. Below is the code for the MainActivity.java file.Java import android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport androidx.swiperefreshlayout.widget.SwipeRefreshLayout;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.Random;public class MainActivity extends AppCompatActivity {\nSwipeRefreshLayout swipeRefreshLayout;\nRecyclerView recyclerView;// Using ArrayList to store images and text data\nArrayList images = new ArrayList<>(Arrays.asList(R.drawable.facebook, R.drawable.twitter,\nR.drawable.instagram, R.drawable.linkedin, R.drawable.youtube, R.drawable.whatsapp));\nArrayList text = new ArrayList<>(Arrays.asList(\"Facebook\", \"Twitter\", \"Instagram\", \"LinkedIn\", \"Youtube\", \"Whatsapp\"));@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// Getting reference of swipeRefreshLayout and recyclerView\nswipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);\nrecyclerView = (RecyclerView) findViewById(R.id.recyclerView);// Setting the layout as Linear for vertical orientation to have swipe behavior\nLinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());\nrecyclerView.setLayoutManager(linearLayoutManager);// Sending reference and data to Adapter\nAdapter adapter = new Adapter(MainActivity.this, images, text);// Setting Adapter to RecyclerView\nrecyclerView.setAdapter(adapter);// SetOnRefreshListener on SwipeRefreshLayout\nswipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n@Override\npublic void onRefresh() {\nswipeRefreshLayout.setRefreshing(false);\nRearrangeItems();\n}\n});\n}public void RearrangeItems() {\n// Shuffling the data of ArrayList using system time\nCollections.shuffle(images, new Random(System.currentTimeMillis()));\nCollections.shuffle(text, new Random(System.currentTimeMillis()));\nAdapter adapter = new Adapter(MainActivity.this, images, text);\nrecyclerView.setAdapter(adapter);\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20201110002152/Pull-to-Refresh-with-RecyclerView-in-Android.mp4"}, {"text": "\nHow to Create Dynamic ListView in Android using Firebase Firestore?\n\nListView is one of the most used UI components in Android which you can find across various apps. So we have seen listview in many different apps. In the previous article, we have seen implementing ListView in Android using Firebase Realtime Database. Now in this article, we will take a look at the implementation of ListView using Firebase Firestore in Android. Now, let\u2019s move towards the implementation of this project.\nWhat we are going to build in this project?We will be building a simple ListView application in which we will be displaying a list of courses along with images in our ListView. We will fetch all the data inside our ListView from Firebase Firestore. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.\nStep by Step ImplementationStep 1: Create a new Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. \nStep 2: Connect your app to Firebase\nAfter creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.\nimplementation \u2018com.google.firebase:firebase-firestore:22.0.1\u2019\nAfter adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. \nStep 3: Working with the AndroidManifest.xml file\nFor adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. XML\n \n Step 4: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML\n Step 5: Now we will create a new Java class for storing our data \nFor reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app\u2019s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it. Javapublic class DataModal { // variables for storing our image and name.\n private String name;\n private String imgUrl; public DataModal() {\n // empty constructor required for firebase.\n } // constructor for our object class.\n public DataModal(String name, String imgUrl) {\n this.name = name;\n this.imgUrl = imgUrl;\n } // getter and setter methods\n public String getName() {\n return name;\n } public void setName(String name) {\n this.name = name;\n } public String getImgUrl() {\n return imgUrl;\n } public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n}Step 6: Create a layout file for our item of ListView\nNavigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_lv_item and add the below code to it. XML\n \n \n Step 7: Now create an Adapter class for our ListView\nFor creating a new Adapter class navigate to the app > java > your app\u2019s package name > Right-click on it and Click on New > Java class and name your java class as CoursesLVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.Javaimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;import com.squareup.picasso.Picasso;import java.util.ArrayList;public class CoursesLVAdapter extends ArrayAdapter { // constructor for our list view adapter.\n public CoursesLVAdapter(@NonNull Context context, ArrayList dataModalArrayList) {\n super(context, 0, dataModalArrayList);\n } @NonNull\n @Override\n public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {\n // below line is use to inflate the \n // layout for our item of list view.\n View listitemView = convertView;\n if (listitemView == null) {\n listitemView = LayoutInflater.from(getContext()).inflate(R.layout.image_lv_item, parent, false);\n }\n \n // after inflating an item of listview item\n // we are getting data from array list inside \n // our modal class.\n DataModal dataModal = getItem(position);\n \n // initializing our UI components of list view item.\n TextView nameTV = listitemView.findViewById(R.id.idTVtext);\n ImageView courseIV = listitemView.findViewById(R.id.idIVimage);\n \n // after initializing our items we are \n // setting data to our view.\n // below line is use to set data to our text view.\n nameTV.setText(dataModal.getName());\n \n // in below line we are using Picasso to \n // load image from URL in our Image VIew.\n Picasso.get().load(dataModal.getImgUrl()).into(courseIV); // below line is use to add item click listener\n // for our item of list view.\n listitemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // on the item click on our list view.\n // we are displaying a toast message.\n Toast.makeText(getContext(), \"Item clicked is : \" + dataModal.getName(), Toast.LENGTH_SHORT).show();\n }\n });\n return listitemView;\n }\n}Step 8: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Javaimport android.os.Bundle;\nimport android.widget.ListView;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.android.gms.tasks.OnFailureListener;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.firebase.firestore.DocumentSnapshot;\nimport com.google.firebase.firestore.FirebaseFirestore;\nimport com.google.firebase.firestore.QuerySnapshot;import java.util.ArrayList;\nimport java.util.List;public class MainActivity extends AppCompatActivity { // creating a variable for our list view, \n // arraylist and firebase Firestore.\n ListView coursesLV;\n ArrayList dataModalArrayList;\n FirebaseFirestore db; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n // below line is use to initialize our variables\n coursesLV = findViewById(R.id.idLVCourses);\n dataModalArrayList = new ArrayList<>(); // initializing our variable for firebase \n // firestore and getting its instance.\n db = FirebaseFirestore.getInstance();\n \n // here we are calling a method\n // to load data in our list view.\n loadDatainListview();\n } private void loadDatainListview() {\n // below line is use to get data from Firebase\n // firestore using collection in android.\n db.collection(\"Data\").get()\n .addOnSuccessListener(new OnSuccessListener() {\n @Override\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) {\n // after getting the data we are calling on success method\n // and inside this method we are checking if the received\n // query snapshot is empty or not.\n if (!queryDocumentSnapshots.isEmpty()) {\n // if the snapshot is not empty we are hiding \n // our progress bar and adding our data in a list.\n List list = queryDocumentSnapshots.getDocuments();\n for (DocumentSnapshot d : list) {\n // after getting this list we are passing \n // that list to our object class.\n DataModal dataModal = d.toObject(DataModal.class);\n \n // after getting data from Firebase we are\n // storing that data in our array list\n dataModalArrayList.add(dataModal);\n }\n // after that we are passing our array list to our adapter class.\n CoursesLVAdapter adapter = new CoursesLVAdapter(MainActivity.this, dataModalArrayList);\n \n // after passing this array list to our adapter \n // class we are setting our adapter to our list view.\n coursesLV.setAdapter(adapter);\n } else {\n // if the snapshot is empty we are displaying a toast message.\n Toast.makeText(MainActivity.this, \"No data found in Database\", Toast.LENGTH_SHORT).show();\n }\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n // we are displaying a toast message\n // when we get any error from Firebase.\n Toast.makeText(MainActivity.this, \"Fail to load data..\", Toast.LENGTH_SHORT).show();\n }\n });\n }\n}After adding the above code add the data to Firebase Firestore in Android.\nStep 9: Adding the data to Firebase Firestore in Android\nSearch for Firebase in your browser and go to that website and you will get to see the below screen. \nAfter clicking on Go to Console option. Click on your project which is shown below.\nAfter clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen. After clicking on the Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console.\nYou have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for \u201cname\u201d and one filed for \u201cimgUrl\u201d and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added.\nSimilarly, add more images by clicking on the \u201cAdd document\u201d button.\nAfter adding these images run your app and you will get to see the output on the below screen.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210111232141/1610387351551.mp4\n"}, {"text": "\nComponents of an Android Application\n\nThere are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the app\u2019s metadata, its hardware configuration, and platform requirements, external libraries, and required permissions. There are the following main components of an android app:\n1. Activities\nActivities are said to be the presentation layer of our applications. The UI of our application is built around one or more extensions of the Activity class. By using Fragments and Views, activities set the layout and display the output and also respond to the user\u2019s actions. An activity is implemented as a subclass of class Activity.Java public class MainActivity extends Activity {\n}Kotlin class MainActivity : AppCompatActivity() {\n}To read more, refer to the article: Introduction to Activities in Android\n2. Services\nServices are like invisible workers of our app. These components run at the backend, updating your data sources and Activities, triggering Notification, and also broadcast Intents. They also perform some tasks when applications are not active. A service can be used as a subclass of class Service:Java public class ServiceName extends Service {\n}Kotlin class ServiceName : Service() {\n}To read more, refer to the article: Services in Android with Example\n3. Content Providers\nIt is used to manage and persist the application data also typically interacts with the SQL database. They are also responsible for sharing the data beyond the application boundaries. The Content Providers of a particular application can be configured to allow access from other applications, and the Content Providers exposed by other applications can also be configured.A content provider should be a sub-class of the class ContentProvider. Java public class contentProviderName extends ContentProvider {\npublic void onCreate(){}\n}Kotlin class contentProviderName : ContentProvider() {\noverride fun onCreate(): Boolean {}\n}To read more, refer to the article: Content Providers in Android with Example\n4. Broadcast Receivers\nThey are known to be intent listeners as they enable your application to listen to the Intents that satisfy the matching criteria specified by us. Broadcast Receivers make our application react to any received Intent thereby making them perfect for creating event-driven applications.\nTo read more, refer to the article: Broadcast Receiver in Android With Example\n5. Intents\nIt is a powerful inter-application message-passing framework. They are extensively used throughout Android. Intents can be used to start and stop Activities and Services, to broadcast messages system-wide or to an explicit Activity, Service or Broadcast Receiver or to request action be performed on a particular piece of data.\nTo read more, refer to the article: Intent and Intent Filters\n6. Widgets\nThese are the small visual application components that you can find on the home screen of the devices. They are a special variation of Broadcast Receivers that allow us to create dynamic, interactive application components for users to embed on their Home Screen.\n7. Notifications\nNotifications are the application alerts that are used to draw the user\u2019s attention to some particular app event without stealing focus or interrupting the current activity of the user. They are generally used to grab user\u2019s attention when the application is not visible or active, particularly from within a Service or Broadcast Receiver. Examples: E-mail popups, Messenger popups, etc.\nTo read more, refer to the article: Notifications in Android with Example"}, {"text": "\nFloating Action Button (FAB) in Android with Example\n\nThe floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app\u2019s UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this article, it has been shown how to implement the Floating Action Button (FAB), and also the buttons under the FABs are handled with a simple Toast message. Note that we are going to implement this project using Java language.\nTypes of Floating Action Button\nThere are mainly four types of floating action buttons available on Android.Normal/Regular Floating Action Button\nMini Floating Action Button\nExtended Floating Action Button\nTheming Floating Action ButtonIn this article let\u2019s discuss the Normal/Regular Floating Action Button and Mini Floating Action Button with a sample example in Android.\nNormal/Regular Floating Action Button\nRegular FABs are FABs that are not expanded and are regular size. The following example shows a regular FAB with a plus icon.Step by Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Adding Dependency to the build.gradle File\nGo to Module build.gradle file and add this dependency and click on Sync Now button.\nimplementation 'com.google.android.material:material:1.3.0-alpha02'\nRefer to the below image if you can\u2019t get the steps mentioned above:Step 3: Add the FAB Icons to the Drawable File\nFor demonstration purposes will import 3 icons in the Drawable folder, and one can import the icons of his/her choice. One can do that by right-clicking the drawable folder > New > Vector Asset. Refer to the following image to import the vector Icon.Now select your vector iconStep 4: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.\nIn the activity_main.xml file add the floating action buttons and invoke the following code. Now invoke the normal FAB. Which is of 56dp radius. We have chained the sub-FABs to the parent FABs so that they are in a single key line. Comments are added inside the code to understand the code in more detail.XML \n \n\n\n \n\n \n\n \n\n \n\n \n Output UI:Step 5: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.\nNow, we handle all FABs using the setOnClickListener() method you may refer to Handling Click events in Button in Android. In this code, it\u2019s been shown that when sub FABs are to be visible with onClickListener. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.View; \nimport android.widget.TextView; \nimport android.widget.Toast; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.google.android.material.floatingactionbutton.FloatingActionButton; public class MainActivity extends AppCompatActivity { \n// Make sure to use the FloatingActionButton for all the FABs \nFloatingActionButton mAddFab, mAddAlarmFab, mAddPersonFab; // These are taken to make visible and invisible along with FABs \nTextView addAlarmActionText, addPersonActionText; // to check whether sub FAB buttons are visible or not. \nBoolean isAllFabsVisible; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Register all the FABs with their IDs This FAB button is the Parent \nmAddFab = findViewById(R.id.add_fab); // FAB button \nmAddAlarmFab = findViewById(R.id.add_alarm_fab); \nmAddPersonFab = findViewById(R.id.add_person_fab); // Also register the action name text, of all the FABs. \naddAlarmActionText = findViewById(R.id.add_alarm_action_text); \naddPersonActionText = findViewById(R.id.add_person_action_text); // Now set all the FABs and all the action name texts as GONE \nmAddAlarmFab.setVisibility(View.GONE); \nmAddPersonFab.setVisibility(View.GONE); \naddAlarmActionText.setVisibility(View.GONE); \naddPersonActionText.setVisibility(View.GONE); // make the boolean variable as false, as all the \n// action name texts and all the sub FABs are invisible \nisAllFabsVisible = false; // We will make all the FABs and action name texts \n// visible only when Parent FAB button is clicked So \n// we have to handle the Parent FAB button first, by \n// using setOnClickListener you can see below \nmAddFab.setOnClickListener(view -> { \nif (!isAllFabsVisible) { \n// when isAllFabsVisible becomes true make all \n// the action name texts and FABs VISIBLE \nmAddAlarmFab.show(); \nmAddPersonFab.show(); \naddAlarmActionText.setVisibility(View.VISIBLE); \naddPersonActionText.setVisibility(View.VISIBLE); // make the boolean variable true as we \n// have set the sub FABs visibility to GONE \nisAllFabsVisible = true; \n} else { \n// when isAllFabsVisible becomes true make \n// all the action name texts and FABs GONE. \nmAddAlarmFab.hide(); \nmAddPersonFab.hide(); \naddAlarmActionText.setVisibility(View.GONE); \naddPersonActionText.setVisibility(View.GONE); // make the boolean variable false as we \n// have set the sub FABs visibility to GONE \nisAllFabsVisible = false; \n} \n}); \n// below is the sample action to handle add person FAB. Here it shows simple Toast msg. \n// The Toast will be shown only when they are visible and only when user clicks on them \nmAddPersonFab.setOnClickListener( \nview -> Toast.makeText(MainActivity.this, \"Person Added\", Toast.LENGTH_SHORT \n).show()); // below is the sample action to handle add alarm FAB. Here it shows simple Toast msg \n// The Toast will be shown only when they are visible and only when user clicks on them \nmAddAlarmFab.setOnClickListener( \nview -> Toast.makeText(MainActivity.this, \"Alarm Added\", Toast.LENGTH_SHORT \n).show()); \n} \n}Kotlin import android.os.Bundle \nimport android.view.View \nimport android.widget.TextView \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity \nimport com.google.android.material.floatingactionbutton.FloatingActionButton class MainActivity : AppCompatActivity() { \n// Make sure to use the FloatingActionButton for all the FABs \nprivate lateinit var mAddFab: FloatingActionButton \nprivate lateinit var mAddAlarmFab: FloatingActionButton \nprivate lateinit var mAddPersonFab: FloatingActionButton // These are taken to make visible and invisible along with FABs \nprivate lateinit var addAlarmActionText: TextView \nprivate lateinit var addPersonActionText: TextView // to check whether sub FAB buttons are visible or not. \nprivate var isAllFabsVisible: Boolean? = nulloverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Register all the FABs with their IDs This FAB button is the Parent \nmAddFab = findViewById(R.id.add_fab) // FAB button \nmAddAlarmFab = findViewById(R.id.add_alarm_fab) \nmAddPersonFab = findViewById(R.id.add_person_fab) // Also register the action name text, of all the FABs. \naddAlarmActionText = findViewById(R.id.add_alarm_action_text) \naddPersonActionText = findViewById(R.id.add_person_action_text) // Now set all the FABs and all the action name texts as GONE \nmAddAlarmFab.visibility = View.GONE \nmAddPersonFab.visibility = View.GONE \naddAlarmActionText.visibility = View.GONE \naddPersonActionText.visibility = View.GONE // make the boolean variable as false, as all the \n// action name texts and all the sub FABs are invisible \nisAllFabsVisible = false// We will make all the FABs and action name texts \n// visible only when Parent FAB button is clicked So \n// we have to handle the Parent FAB button first, by \n// using setOnClickListener you can see below \nmAddFab.setOnClickListener(View.OnClickListener { \n(if (!isAllFabsVisible!!) { \n// when isAllFabsVisible becomes true make all \n// the action name texts and FABs VISIBLE \nmAddAlarmFab.show() \nmAddPersonFab.show() \naddAlarmActionText.visibility = View.VISIBLE \naddPersonActionText.visibility = View.VISIBLE // make the boolean variable true as we \n// have set the sub FABs visibility to GONE \ntrue\n} else { \n// when isAllFabsVisible becomes true make \n// all the action name texts and FABs GONE. \nmAddAlarmFab.hide() \nmAddPersonFab.hide() \naddAlarmActionText.visibility = View.GONE \naddPersonActionText.visibility = View.GONE // make the boolean variable false as we \n// have set the sub FABs visibility to GONE \nfalse\n}).also { isAllFabsVisible = it } \n}) \n// below is the sample action to handle add person FAB. Here it shows simple Toast msg. \n// The Toast will be shown only when they are visible and only when user clicks on them \nmAddPersonFab.setOnClickListener { \nToast.makeText(this, \"Person Added\", Toast.LENGTH_SHORT).show() \n} // below is the sample action to handle add alarm FAB. Here it shows simple Toast msg \n// The Toast will be shown only when they are visible and only when user clicks on them \nmAddAlarmFab.setOnClickListener { \nToast.makeText(this, \"Alarm Added\", Toast.LENGTH_SHORT).show() \n} \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200921191630/GFG_frame_nexus_5.mp4\nMini Floating Action Button\nMini FABs are used on smaller screens. Mini FABs can also be used to create visual continuity with other screen elements. The following example shows a mini FAB with a plus icon.Creating a Mini FAB\nNow invoke the mini FAB button. Which is of 40dp radius. All the other things are renamed the same. Only one attribute needs to be changed that is:\napp:fabSize=\"mini\"\nAfter doing the changes the output UI looks like this:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20200921193510/GFG_frame_nexus_5.mp4\napp:fabsize=\"auto\"Note: The FAB can also be made auto resizable by changing the fabSize attribute to auto. This will make FAB size automatically mini and normal according to the window size."}, {"text": "\nHistory of Android\n\nAndroid devices form a very essential part of a huge section of mobile phone users in today\u2019s world. With the global turmoil in the COVID-19 eras, the population has now entered a digital sphere. Android is the most used OS in smartphones during these days of transformation. But when did something like an android take birth in the first place and how did it decide its journey of growth? We did not know earlier than mother planet was to go on a social distancing strike in 2020, so how were we still prepared? Let\u2019s answer all these questions right here!\nWhen did it all start?\nThe story of Android dates back to 2003 when Andy Rubin, Rich Miner, Nick Sears, and Chris White co-founded a start-up Android Inc. in Palo Alto, California. However, the company was later faced with the insufficiency of funds which brought Google into the picture. Google could sense the potential the product carried within and sealed a deal worth $50 Million to acquire Android in 2005. All the four Co-founders soon moved to the Googleplex to continue to develop the OS further under their new owners. The first public Android Beta Version 1.0 was finally published on 5th November 2007.\nAndroid Version 1 Series\nAndroid 1.0 (API 1) and 1.1 (API 2)\nAndroid 1.0 (API 1) was launched on the 23rd Of September 2008. It was incorporated into the HTC Dream smartphone (aka T-mobile G1 in the US). It thus became the first-ever Android device. The features it offered included Google Maps, YouTube, an HTML browser, Gmail, camera, Bluetooth, Wi-Fi, and many more. The unique feature at that time was the presence of an Android Market (now Play Store) from where the users could download and update Android applications additional to what was already pre-installed. A few months later, in February 2009, Google released the Android 1.1 (API 2) update for HTC Dream. This time the aim was to make it more robust and user-friendly. There were four major updates in this version:Saving of attachments in messages\nAvailability of details and reviews for businesses on Google Maps\nLonger in-call screen timeout by default while the speakerphone was in use along with the ability to toggle the dial-pad.\nSupport was added for a marquee in the system layouts.Android 1.5 (API 3) aka Cupcake\nThis version came up in late April 2009 and was the first to have Google\u2019s dessert-themed naming scheme and be incorporated in the Samsung Galaxy phone series. It was introduced with a lot of functionalities that we take for granted today. These updates included new features and enhancements to the ones already present in the above versions, for example, some major updates included auto-rotation, third-party keyboard support, support for widgets, video recording, enabling copy-paste for browser, facility to upload videos on YouTube, check phone usage history, etc.\nAndroid 1.6 (API 4) aka Donut\nJust after a couple of months in September 2009, Donut was released. One of its most significant features was the inclusion of CDMA-based networks that made it possible for carriers across the globe to support it. Earlier only GSM technologies were in use. Other critical improvements such as support for devices having different screen sizes, quick search boxes and bookmarks on web browsers, fuller integration of Gallery, Camera, and Camcorder with faster camera access, expansion of the Gesture framework, text-to-speech, etc. were too introduced in this update.\nAndroid Version 2 Series\nAndroid 2.0 (API 5), 2.0.1 (API 6), and 2.1 (API 7) aka Eclair\nAlmost after a year of the Version 1 release, Version 2.0 was launched in October 2009. Key highlights of this update included the introduction of navigation in Google Maps with voice guidance, support for adding multiple accounts in one device, display of live wallpapers, a lock screen with drag and drop unlocking functionality, additions to camera services such as Flash and digital zoom, the inclusion of smarter dictionary for virtual keyboards that learned through word usages, support for further more screen sizes, enhanced ability to track multi-touch events, better Calendar agenda, support for HTML 5 view and so on and so forth. Within three months of 2.0\u2019s release, 2.0.1 and 2.1 were released in Dec 2009 and Jan 2010, respectively. These releases majorly dealt with minor amendments to the API and other bug fixes.\nAndroid 2.2 (API 8) aka Froyo\nFroyo is actually a combination of the words, \u201cfrozen Yogurt\u201d. This version was launched in May 2010. Some of its most significant features included Wi-Fi mobile hotspot support, push notifications through Android Cloud to Device Messaging, enhancement of device security through PIN/ Password protection, Adobe Flash support, USB tethering functionality, update in Android Market application with the automatic update of apps features, support for Bluetooth enabled car, etc.The other versions 2.2.1, 2.2.2, and 2.2.3 were all in total about bug fixes and other security updates all released in 2011. The latest of them, i.e. 2.2.3 was published in Nov 2011.\nAndroid 2.3 (API 9) aka Gingerbread\nGingerbread, released even before the later versions of Froyo, brought drastic changes to the look and feel of smartphones. The first phone to adopt this version was Nexus S, co-developed by Google and Samsung. In this version, the user interface design was updated to bring in more simplicity and speed. Support for extra-large screen sizes and resolutions was integrated. Support for NFC function, improved keyboard, enhanced support for multi-touch events, multiple cameras on the device including a front-facing camera, Enhanced copy/paste functionality were some other noteworthy features. Version 2.3.1 and 2.3.2 were released in Dec 2010 and Jan 2011 respectively. They majorly carried improvements and bug fixes for the Nexus S.\nAndroid Version 2.3.3 and further in the series Gingerbread (API 10).\nVersion 2.3.3 brought along some API improvements and bug fixes in Feb 2011. Further 2.3.4 in April the same year introduced support for voice and video chat using Google Talk. In this version, the default encryption for SSL was also changed from AES256-SHA to RC4-MD5. 2.3.5 and 2.3.6 were released dominantly with various kinds of bug fixes and improvements in July 2011 and Sept 2011 respectively. 2.3.7 got the Google wallet support for the Nexus S 4G in Sept 2011.\nAndroid Version 3 Series\nAndroid 3.0 (API 11) Honeycomb\nIn Feb 2011, Android 3.0 Honeycomb was released to be installed on tablets and phones with larger screens only and had functions that could not be managed on phones with smaller screens. The most important function brought by this version was to eliminate the need for the physical button and rather the introduction of virtual buttons for performing the start, back, and menu functions. This version was first launched along with the Motorola Xoom Tablet. Other refined UI advancements were made by adding a System Bar which resolved quicker access to notifications and status at the bottom. The inclusion of an Action Bar gave access to contextual options, navigation, widgets, and other types of content at the top of the screen. This version also enabled switching between tasks/applications easier. Another significant feature included the ability to encrypt all the user data.\nAndroid 3.1 (API 12) Honeycomb\nThis version released in May 2011 presented many other UI refinements. Its foremost feature was support for joysticks, gamepads, external keyboards, and pointing devices. It also had better connectivity for USB accessories.\nAndroid 3.2 series Honeycomb (API 13)\nVersion 3.2 released in July 2011, mainly improved the hardware support and increased the ability of various applications to access files on the SD card. Some displays support functions were also upgraded in this update to control the variation of display appearances on different Android devices more precisely.\n3.2.1 in Sept 2011 brought in various bug fixes and minor security, Wi-Fi, and stability improvements. Some other updates were too made to Google Books, Adobe Flash, and Android Market.\nOn Aug 30, 2011, 3.2.2 and 3.2.3 were released, and in Jan 2012, 3.2.5 was published. All of them were majorly about bug fixes and other minor improvements for the Motorola Xoom and Motorola Xoom 4G.\nIn Dec 2011, the 3.2.4 version introduced the Pay As you Go feature for 3G and 4G tablets. And the last version of this series, 3.2.6, published in Feb 2012 fixed the data connectivity issues faced when disabling the Airplane mode on the US 4G Motorola Xoom.\nAndroid Version 4 Series\nAndroid 4.0 (API 14) Icecream Sandwich\nAndroid 4.0 was released in October 2011. It was a combination of a lot of features of the Honeycomb Version and the Gingerbread. For the first time ever, the Face Unlock feature for smartphones was introduced with 4.0. Other prominent features included the possibility to monitor the use of mobile data and Wi-Fi, sliding gestures to reject notifications, tabs of a browser or even tasks, integration of screenshot capture using the Power and Volume button, real-time speech to text dictation, using certain apps without necessarily unlocking, pre-fed text responses to calls, and many more. Another important feature that greatly enhanced the accessibility of devices for the visually challenged people was a new explore-by-touch mode through which users could navigate through the screen with the help of audible feedback. This eliminated the need to actually view the device\u2019s screen. A lot of advanced camera capabilities were added in this version, including the Panorama mode. Live effects during the recording of videos were also introduced. The new technology of Wi-Fi peer-to-peer (P2P) that lets the users connect directly to nearby peer devices over Wi-Fi, without the need for internet or tethering was also introduced with this version. Android 4.0.1 and 4.0.2 introduced in October and November 2011 brought minor bug fixes to certain devices.\nAndroid 4.0.3 and 4.0.4 Ice Cream Sandwich (API 15)\n4.0.3, released in December 2011 brought various bug fixes, optimizations, and enhancements to certain functionalities including databases, Bluetooth, graphics, camera, Calendar provider. 4.0.4, released in March 2012, too brought minor improvements such as better camera performance and smoother screen rotation.\nAndroid 4.1 (API 16), 4.2 (API 17), and 4.3 (API 18) Jelly Bean\nAndroid 4.1 was the first version of Jelly bean and the fastest and smoothest by that time too. This version further enhanced the accessibility and extended assistance to international users by introducing Bi-directional text i.e. left to right or right to left scripts and support for various other international languages.From this version onwards, the notifications could be expanded, displaya greater variety of content, present options for multiple actions, etc. User-installable keyboard maps were also introduced. Shortcuts and widgets can automatically be re-arranged or re-sized to allow new items to fit on home screens. Android Beam, an NFC-based technology could let users instantly share media, just by touching two NFC-enabled phones together.\nVersion 4.2 was launched in Nov 2013. This was a faster smoother and more responsive version. This was the first version to introduce the feature of one tablet, \u2013 many users through which multiple users could use the same device but still have a separate system environment for each user data. Other prominent incorporations included Widget support (display any kind of content on the lock screen, however it was removed again in 2014), Daydream feature which is an interactive screensaver mode that starts when a user\u2019s device is docked or charging, presentation functionality that let user represent a window for their app\u2019s content on a specific external display, Wi-Fi Display that let users connect to an external display over Wi-Fi on the supported devices and full native support for RTL.\nVersion 4.3 released in July 2013 built further on the performance improvements already included in earlier versions of Jelly Bean. It introduced the platform support for Khronos OpenGL ES 3.0, which provided games and some other apps with the highest-performance 2D and 3D graphics capabilities on supported devices. This release further extended the multi-user feature for tablets, which made it even easier to manage users and their capabilities on a single device. Another prominent feature of this version would let apps observe the stream of notifications with the user\u2019s permission and then display them in any way they choose to. They could also send these notifications to nearby devices connected over Bluetooth.\nAndroid 4.4 (API 19) Kitkat\nThe launch of Android 4.4 KitKat took place in 2013 and had many distinct features such as the blue accents found in Ice Cream Sandwich and Jelly Bean had turned whiter and many storage applications displayed lighter color schemes. With the \u2018Ok Google\u2019 command, a user could access Google at any time and could work on phones with a minimum RAM memory of 512MB. The phone app could automatically prioritize user\u2019s contacts based on the numbers most frequently contacted. Google Hangouts was introduced in this version that could keep all the user\u2019s SMS and MMS messages together in the same app. Emoji was made also available on Google Keyboard.\nAndroid 4.4W (API 20) KitKat, with wearable extensions.\n3 Versions of Android KitKat exclusive to Android Wear devices were released between June 2014 to October 2014. These were primarily designed for smartwatches and other wearables and integrated with Google Assistant technology and mobile notifications features into a smartwatch form factor.\nAndroid Version 5 Series \nAndroid 5.0 (API 21) Lollipop\nAndroid 5.0 was launched in Nov 2014 with the Nexus 6 device. It was the first to feature Google\u2019s \u2018Material Design\u2019 Philosophy which brought tremendous improvements to the UI Design, for example, the Vector drawables which could be scaled indefinitely without losing their definition were introduced. Other significant features included the replacement of VM Dalvik with Android Runtime that improved the app performance and responsiveness considerably as some of the processing power for applications could now be provided before they were opened. Support for Android TV was integrated that provided a complete TV platform for any app\u2019s big-screen experience. The navigation bar had been renewed making it more visible, accessible, and configurable. A/V sync was improved noticeably. Quite some new concepts too were implemented in this release such as the \u2018Document-centric apps\u2018 that enabled users to take advantage of concurrent documents and provided them with instant access to their content/ services, \u2018Android in the workplace\u2019 that allowed apps in the launcher to display a Work badge over their icon which was an indication that a certain app and its data are administered inside of the work profile, and \u2018dumpsys batterystats\u2018 command that would generate battery usage statistics and help the users understand system-wide power use.\nAndroid 5.1 (API 21) Lollipop\nThis version of Android was launched in March 2015. Some notable features of the release included official support for multiple SIM cards, the Device protection policy that kept the device locked in case of theft/misplacement until the owner signs into their Google account, and the introduction of High-definition voice calls, available between compatible 4G LTE devices.\nAndroid Version 6.0 Marshmallow (API 23)\nAndroid Marshmallow was launched in October 2015 and it did bring along remarkable features such as support for biometric fingerprint unlocking and USB type C support, the introduction of Doze mode which reduced CPU speed while the display remains turned off to enhance the battery life, a search bar for easy access to applications and option to mark them as favorites, Android Pay, the introduction of the Memory Manager, Contextual search from keywords within apps, the possibility to set the volume for device, media, and alarms all separately, a refurbished vertically scrolling app drawer that could be accessed alphabetically, provisions for target-specific sharing between apps, MIDI support for musical instruments and a lot more. Google Nexus 6P and Nexus 5X were the first devices to have android Marshmallow preinstalled.\nAndroid Version 7 Series\nAndroid 7.0 (API 24) Nougat\nIn August 2016, Google released Android 7.0 Nougat. It presented improved multitasking features especially for devices with larger screens, for example, the split-screen mode was introduced along with provision for fast switching between applications. Other significant features included the integration of the Daydream virtual-reality platform and enhancement of the \u2018Doze now\u2018 mode. More characteristics such as rearranging the Quick Setting tiles for faster access, replying to conversations through notifications themselves, catching up with all the notifications from a specific app together through bundled notifications, limiting device data usage with Data Saver, and the possibility to change the size of the text as well as icons on the display screen were incorporated. Google Now was replaced with Google Assistant. The first phones to come with this version were Google Pixel, Pixel XL, and LG V20.\nAndroid 7.1, 7.1.1 and 7.1.2 Nougat (API 25)\nAndroid 7.1, released in October 2016 majorly brought changes and updates to the existing features and the ones introduced in 7.0, however, one fascinating design idea portrayed in 7.1 was the Circular app icon support.\nIn 7.1.1, launched in December 2016, a new set of emojis with different skin tones and haircuts to existing ones were added. Moreover, it now became possible to send GIFs directly from the default keyboard.\nIn April 2017, 7.1.2 was published that brought in battery usage alerts.\nAndroid Version 8 Series\nAndroid 8.0 (API 26) Oreo\nThis version appeared in Aug 2017 and brought a series of noteworthy changes to the existing ones. It turned out to be a more powerful and faster version as it had a 2x boot speed compared to Nougat when tested on Pixel devices, according to a claim by Google. This version was smarter as well which was evident through the introduction of functionalities such as Autofill, picture-in-picture mode (for example, the video calling window in WhatsApp while working with some other app), and the Notification dots through which user could quickly catch up with newer information. This update brought enhancements to the security aspect too by launching Google Play Protect that ensured the safety of the device and its data against misbehaving apps. Apart from these, attention was also driven towards visual details, e.g. the blob style for emojis was replaced with emojis that were consistent with other platforms, and Quick Settings and Settings were redesigned considerably.\nAndroid 8.1.0 (API 27) Oreo\nAndroid 8.1 released in December 2017, introduced a variety of new capabilities for users and developers. The most significant one for users was the development of Go Edition that provided configurations for Memory optimizations, Flexible targeting options (New hardware feature constants that let the users target the distribution of their apps to normal or low-RAM devices.), and Google Play Services. For Developers, a whole new bunch of APIs was added including the Neural Networks API, Shared memory API, and WallpaperColors API.\nAndroid Version 9 Pie (API 28)\nAndroid 9 was introduced in August 2018. It brought tremendous improvements to the visual aspect and made exceptional use of the power of artificial intelligence. The most noticeable ones included, replacement of traditional navigation buttons with an elongated button in the center that functioned as the new start button, swiping which up provided an overview of recently used applications, a search bar, and five application suggestions. Improvements were brought to the battery life, \u2018Shush\u2018 was introduced that automatically put the phone in \u2018Do not Disturb\u2018 mode by placing the phone face down, capabilities for adaptive Brightness and Battery were embedded, provision to avail details of screentime to grab a better idea of how often and for what purposes the phone device was used was introduced.\nAndroid Version 10 (API 29)\nWith Android 10 in Sept 2019, Google announced a rebranding of the operating system, eliminating the sweets-name based naming scheme that was being used for the earlier versions. With this version, a new logo and a different color scheme were announced. Facilities such as Live Captions for all media, smarter replies to text (automated text and actions suggestions), \u2018Focus mode\u2019 to block out distractions by selecting certain apps to pause temporarily, replacement of navigation buttons with the use of gestures, availability of the dark mode at the system level, provision for more control over permissions for applications, the introduction of support for foldable smartphones with flexible displays, and capabilities to see device location, set screen time limits and have better parental control over children\u2019s content were embedded.\nAndroid Version 11 (API 30)\nAndroid 11 was recently released on the 8th of September 2020. This version has come up with a tagline \u2018The OS that gets to what\u2019s important\u2018 and it\u2019s pretty much justified. Android 11 brings along capabilities to control conversations across multiple messaging apps all in the same spot, it allows the user to digitally select priorities for people they are conversing with and then show the most important conversations at the top and on the lock screen. Another distinguishing feature is the chat bubbles (similar to the Facebook messenger) through which users can pin conversations from various messaging apps so they always appear on their screens. The built-in screen recording feature has been introduced finally that avoids the installation of an extra app to record the screen. Enhancements have been brought to the smart reply features and the voice access functionalities. One more captivating feature is the Device control capability that allows controlling all the connected devices from one place. Google play security has also been updated remarkably. 11 major versions have been launched by Android till date and with each version, the OS promises to get better. Till the next release let\u2019s speculate what newer capabilities could an OS unleash!\nLet\u2019s Summarize the History of Android into a roadmap like structure"}, {"text": "\nDate and Time Formatting in Android\n\nDate and Time in Android are formatted using the SimpleDateFormat library from Java, using Calendar instance which helps to get the current system date and time. The current date and time are of the type Long which can be converted to a human-readable date and time. In this article, it\u2019s been discussed how the Date and Time values can be formatted in various formats and displayed. Have a look at the following image to get an idea of the entire discussion.Steps to Format the Date and Time in Android\nStep 1: Create an empty activity projectUsing Android Studio create an empty activity project. Refer to Android | How to Create/Start a New Project in Android Studio?Step 2: Working with the activity_main.xml fileThe main layout of the activity file containing 8 TextViews. One to show the current system date and time value in Long type, and others to display the same date and time value in a formatted human-readable way.\nTo implement the UI invoke the following code inside the activity_main.xml file.XML \n \n \n Step 3: Working with the MainActivity file\nUnderstanding the way of formatting the date and time in Android using SimpleDateFormatFirstly, the instance of the Calendar is created and the desired format of the date and time to be shown is passed to the SimpleDateFormat method. The String should include the following characters and one may include the separators like -, / etc.\nThe below table includes the characters to be used to generate the most used common pattern of date and time.Character to be usedOutputdd\nDate in numeric valueE\nDay in String (short form. Ex: Mon)EEEE\nDay in String (full form. Ex: Monday)MM\nMonth in numeric valueyyyy\nYear in numeric valueLLL\nMonth in String (short form. Ex: Mar)LLLL\nMonth in String (full form. Ex: March)HH\nHour in numeric value (24hrs timing format)KK\nHour in numeric value (12hrs timing format)mm\nMinute in numeric valuess\nSeconds in numeric valueaaa\nDisplays AM or PM (according to 12hrs timing format)z\nDisplays the time zone of the regionRefer to the following code and its output to get a better idea of the above table.Kotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.widget.TextView \nimport java.text.SimpleDateFormat \nimport java.util.* class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) var dateTime: String \nvar calendar: Calendar \nvar simpleDateFormat: SimpleDateFormat // register all the text view with appropriate IDs \nval dateTimeInLongTextView: TextView = findViewById(R.id.dateTimeLongValue) \nval format1: TextView = findViewById(R.id.format1) \nval format2: TextView = findViewById(R.id.format2) \nval format3: TextView = findViewById(R.id.format3) \nval format4: TextView = findViewById(R.id.format4) \nval format5: TextView = findViewById(R.id.format5) \nval format6: TextView = findViewById(R.id.format6) \nval format7: TextView = findViewById(R.id.format7) // get the Long type value of the current system date \nval dateValueInLong: Long = System.currentTimeMillis() \ndateTimeInLongTextView.text = dateValueInLong.toString() // different format type to format the \n// current date and time of the system \n// format type 1 \ncalendar = Calendar.getInstance() \nsimpleDateFormat = SimpleDateFormat(\"dd.MM.yyyy HH:mm:ss aaa z\") \ndateTime = simpleDateFormat.format(calendar.time).toString() \nformat1.text = dateTime // format type 2 \ncalendar = Calendar.getInstance() \nsimpleDateFormat = SimpleDateFormat(\"dd-MM-yyyy HH:mm:ss aaa z\") \ndateTime = simpleDateFormat.format(calendar.time).toString() \nformat2.text = dateTime // format type 3 \ncalendar = Calendar.getInstance() \nsimpleDateFormat = SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss aaa z\") \ndateTime = simpleDateFormat.format(calendar.time).toString() \nformat3.text = dateTime // format type 4 \ncalendar = Calendar.getInstance() \nsimpleDateFormat = SimpleDateFormat(\"dd.LLL.yyyy HH:mm:ss aaa z\") \ndateTime = simpleDateFormat.format(calendar.time).toString() \nformat4.text = dateTime // format type 5 \ncalendar = Calendar.getInstance() \nsimpleDateFormat = SimpleDateFormat(\"dd.LLLL.yyyy HH:mm:ss aaa z\") \ndateTime = simpleDateFormat.format(calendar.time).toString() \nformat5.text = dateTime // format type 6 \ncalendar = Calendar.getInstance() \nsimpleDateFormat = SimpleDateFormat(\"E.LLLL.yyyy HH:mm:ss aaa z\") \ndateTime = simpleDateFormat.format(calendar.time).toString() \nformat6.text = dateTime // format type 7 \ncalendar = Calendar.getInstance() \nsimpleDateFormat = SimpleDateFormat(\"EEEE.LLLL.yyyy KK:mm:ss aaa z\") \ndateTime = simpleDateFormat.format(calendar.time).toString() \nformat7.text = dateTime \n} \n}Java import android.os.Bundle; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport java.text.SimpleDateFormat; \nimport java.util.Calendar; public class MainActivity extends AppCompatActivity { TextView dateTimeInLongTextView, format1, format2, \nformat3, format4, format5, format6, format7; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); String dateTime; \nCalendar calendar; \nSimpleDateFormat simpleDateFormat; // register all the text view with appropriate IDs \ndateTimeInLongTextView = (TextView) findViewById(R.id.dateTimeLongValue); \nformat1 = (TextView) findViewById(R.id.format1); \nformat2 = (TextView) findViewById(R.id.format2); \nformat3 = (TextView) findViewById(R.id.format3); \nformat4 = (TextView) findViewById(R.id.format4); \nformat5 = (TextView) findViewById(R.id.format5); \nformat6 = (TextView) findViewById(R.id.format6); \nformat7 = (TextView) findViewById(R.id.format7); // get the Long type value of the current system date \nLong dateValueInLong = System.currentTimeMillis(); \ndateTimeInLongTextView.setText(dateValueInLong.toString()); // different format type to format the \n// current date and time of the system \n// format type 1 \ncalendar = Calendar.getInstance(); \nsimpleDateFormat = new SimpleDateFormat(\"dd.MM.yyyy HH:mm:ss aaa z\"); \ndateTime = simpleDateFormat.format(calendar.getTime()).toString(); \nformat1.setText(dateTime); // format type 2 \ncalendar = Calendar.getInstance(); \nsimpleDateFormat = new SimpleDateFormat(\"dd-MM-yyyy HH:mm:ss aaa z\"); \ndateTime = simpleDateFormat.format(calendar.getTime()).toString(); \nformat2.setText(dateTime); // format type 3 \ncalendar = Calendar.getInstance(); \nsimpleDateFormat = new SimpleDateFormat(\"dd/MM/yyyy HH:mm:ss aaa z\"); \ndateTime = simpleDateFormat.format(calendar.getTime()).toString(); \nformat3.setText(dateTime); // format type 4 \ncalendar = Calendar.getInstance(); \nsimpleDateFormat = new SimpleDateFormat(\"dd.LLL.yyyy HH:mm:ss aaa z\"); \ndateTime = simpleDateFormat.format(calendar.getTime()).toString(); \nformat4.setText(dateTime); // format type 5 \ncalendar = Calendar.getInstance(); \nsimpleDateFormat = new SimpleDateFormat(\"dd.LLLL.yyyy HH:mm:ss aaa z\"); \ndateTime = simpleDateFormat.format(calendar.getTime()).toString(); \nformat5.setText(dateTime); // format type 6 \ncalendar = Calendar.getInstance(); \nsimpleDateFormat = new SimpleDateFormat(\"E.LLLL.yyyy HH:mm:ss aaa z\"); \ndateTime = simpleDateFormat.format(calendar.getTime()).toString(); \nformat6.setText(dateTime); // format type 7 \ncalendar = Calendar.getInstance(); \nsimpleDateFormat = new SimpleDateFormat(\"EEEE.LLLL.yyyy KK:mm:ss aaa z\"); \ndateTime = simpleDateFormat.format(calendar.getTime()).toString(); \nformat7.setText(dateTime); \n} \n}Output:"}, {"text": "\n7 Tips to Improve Your Android Development Skills\n\nAndroid is an operating system which is built basically for Mobile phones. It is based on the Linux Kernel and other open-source software and is developed by Google. It is used for touchscreen mobile devices like smartphones and tablets. But nowadays these are utilized in Android Auto cars, TV, watches, camera, etc. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. Various applications like games, music player, camera, etc. are built for these smartphones for running on Android. Google Play store features quite 3.3 million apps.Today, Android remains to dominate on a global scale. Approximately 75% of the world population prefers using Android as against the 15% of iOS. It is an operating system that has a huge market for apps. In the article 8 Must-Have Skills for Becoming an Android App Developer, we have discussed the necessary skills to become an Android App developer but its a good habit to improve your skills at regular intervals. So in this article let\u2019s discuss \u201cTips to improve your Android Development Skills\u201c.\nImprove Android Development Skills\n1. Follow The Trend But Think Unique\nYou have to follow the ongoing trend. But remember, millions of people are following the same trend too. So you, definitely need to think out of the box about the same that how can you make it attractive. You need to learn to increase the engagement with your app user. To know the current trend explore apps that have already been featured on the play store. Do some research on the Play Store, pick some apps with labels like Editors\u2019 Pick and Top Developer, and install them on your Android phone. Then, analyze the apps, giving attention to what characteristics they have in common. In particular, check thoroughly the apps\u2019 design, functionality, and everything that makes them stand out from similar apps in the category.\n2. Get Over the FOMO (Fear of Missing Out)\nAndroid is a very huge domain. One can\u2019t learn it completely end to end in a month. As a beginner, it\u2019s quite common to be worried that you\u2019re missing out on learning essential information by trying to build things while still in a state of greatconfusion but try to get over it. Just start with basics fundamentals Android concepts and slowly build your command on it.\n3. Give Priority to Security\nIn the era of internet security plays the most important role. Whether it may be a website or an Android app if there is no security guarantee then there is no use of that. So while building an app development, make sure that the user\u2019s data is safe and secure if they are using your app. Beware of the hackers in the market and find a solution to what problems they can create.\n4. Focus on Reading More Codes\nMost Android developers don\u2019t spend the time to read what other developers are writing. And they paymost of their time writing what they already know. But this is not going to help you to become a perfect Android developer. The only way to become a more expert developer is to read the excellent code of more skilled developers. The more you read, the more you learn. If you are developing something it is possible that you code everything on your own. But, if you start reading other\u2019s codes, it helps in raising your vision and might also result in giving some new ideas.\n5. Start Contributing to Open Source\nIf you have developed a library, plugin, or other helpful pieces of code and you\u2019re utilizing it in your app, consider open-sourcing it. There\u2019s enough to discover in the process of contributing to open-source projects. Even the least bit of contribution like fixing some grammatical errors in the docs will be beneficial for the project maintainer to keep the project running. And this will surely help you to improve your Android Development skill.\n6. Do Test Your Creation\nBefore, releasing your product, you must test whether it works on the smartphone efficiently and effectively and observe if it is going to impress the users. Most importantly accommodate low-end devices and smaller screens that mean in the emerging markets, many devices tend to have small screens, so make sure you optimize your UI by testing on multiple screen sizes. You should also adapt your app to low-end devices, which may have low memory, low processing power, and low resolution. Also, consider backward compatibility to jelly bean, and where practical, back to ice cream sandwich.\n7. Observe The Feedback\nYou must observe the feedback that the users make and keep in mind the good and bad in your application. One of the most important things about an app is to maintain the app regularly. Keep your app up-to-date. Track the problems users are facing with your app and provide them solutions regarding the issues through regular updates. So that the next time you can deliver the best to your users.\n"}, {"text": "\nWhat is Toast and How to Use it in Android with Examples?\n\nPre-requisites:Android App Development Fundamentals for Beginners\nGuide to Install and Set up Android Studio\nAndroid | Starting with the first app/android project\nAndroid | Running your first Android appWhat is Toast in Android?\nA Toast is a feedback message. It takes a very little space for displaying while the overall activity is interactive and visible to the user. It disappears after a few seconds. It disappears automatically. If the user wants a permanently visible message, a Notification can be used. Another type of Toast is custom Toast, in which images can be used instead of a simple message.Example: Toast class provides a simple popup message that is displayed on the current activity UI screen (e.g. Main Activity).\nConstants of Toast classConstants\nDescriptionpublic static final int LENGTH_LONG\ndisplays for a long timepublic static final int LENGTH_SHORT\ndisplays for a short timeMethods of Toast classMethods\nDescriptionpublic static Toast makeText(Context context, CharSequence text, int duration)\nmakes the toast message consist of text and time durationpublic void show()\ndisplays a toast messagepublic void setMargin (float horizontalMargin, float verticalMargin)\nchanges the horizontal and vertical differencesHow to Create an Android App to Show a Toast Message?\nIn this example \u201cThis a simple toast message\u201d is a Toast message which is displayed by clicking on the \u2018CLICK\u2019 button. Every time when you click your toast message appears.Step-By-Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.Step 2: Working with the XML Files\nOpen the \u201cactivity_main.xml\u201d file and add a Button to show the Toast message in a Constraint Layout. Also, Assign an ID to the button component as shown in the image and the code below. The assigned ID to the button helps to identify and to use files.\nandroid:id=\"@+id/id_name\"\nHere the given ID is Button01 This will make the UI of the Application:Step 3: Working with the MainActivity File\nNow, after the UI, this step will create the Backend of the App. For this, Open the \u201cMainActivity\u201d file and instantiate the component (Button) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.\nGeneral Syntax:\nComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);\nThe syntax for the used component (Click Button):\nButton btn = (Button)findViewById(R.id.Button01);\nStep 4: Operations to Display the Toast Message\nAdd the listener on the Button and this Button will show a toast message.\nbtn.setOnClickListener(new View.OnClickListener() {});\nNow, Create a toast message. The Toast.makeText() method is a pre-defined method that creates a Toast object. Syntax:\npublic static Toast makeText (Context context, CharSequence text, int duration)\nParameters: This method accepts three parameters:\nA. context: A first parameter is a Context object which is obtained by calling getApplicationContext().\nContext context = getApplicationContext(); \nB. text: The second parameter is your text message to be displayed.\nCharSequence text=\u201dYour text message here\u201d\nC. duration: The last parameter is the time duration for the message.\nint duration=Toast.LENGTH_LONG;\nDisplay the created Toast Message using the show() method of the Toast class.\nSyntax:\npublic void show ()\nThe code to show the Toast message:\nToast.makeText(getApplicationContext(), \"This a toast message\", Toast.LENGTH_LONG).show();\nStep 5: Now Run the App\nOperate it as follows:When the app is opened, it displays a \u201cClick\u201d button.\nClick the Click button.\nThen \u201cThis a toast message\u201d will be displayed on the screen as a Toast Message.Complete the Code to display a simple Toast Message:XML \n \n \n Java import android.support.v7.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.Toast; public class MainActivity extends AppCompatActivity { \n// Defining the object for button \nButton btn; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Bind the components to their respective objects by assigning \n// their IDs with the help of findViewById() method \nButton btn = (Button)findViewById(R.id.Button01); btn.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// Displaying simple Toast message \nToast.makeText(getApplicationContext(), \"This a toast message\", Toast.LENGTH_LONG).show(); \n} \n}); \n} \n}Kotlin import android.os.Bundle \nimport android.widget.Button \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Bind the components to their respective objects by assigning \n// their IDs with the help of findViewById() method \nval btn = findViewById(R.id.Button01) \nbtn.setOnClickListener { // Displaying simple Toast message \nToast.makeText(applicationContext, \"This a toast message\", Toast.LENGTH_LONG).show() \n} \n} \n}Output:How to Change the position of a Toast Message?\nIf there is a need to set the position of a Toast message, then setGravity() method can be used.\npublic void setGravity (int gravity, int xOffset, int yOffset)\nParameters: This method accepts three parameters:\ngravity: This sets the position of the Toast message. The following constants can be used to specify the position of a Toast:\n1.TOP\n2.BOTTOM\n3.LEFT\n4.RIGHT\n5.CENTER\n6.CENTER_HORIZONTAL\n7.CENTER_VERTICALEvery constant specifies the position in the X and Y axis, except the CENTER constant which sets the position centered for both horizontal and vertical directions.\nxOffset: This is the offset value that tells how much to shift the Toast message horizontally on the x-axis.\nyOffset: This is the offset value that tells how much to shift the Toast message vertically on the y-axis.For example:To display the Toast at the center: toast.setGravity(Gravity.CENTER, 0, 0);\nTo display the Toast at the top, centered horizontally: toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 0);\nTo display the Toast at the top, centered horizontally, but 30 pixels down from the top: toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTALLY, 0, 30);\nTo display the Toast at the bottom, rightmost horizontally: toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);Example: Here, in the below example, the Toast is displayed at the Bottom-Right position.\nSyntax:\nToast t = Toast.makeText(getApplicationContext(), \"This a positioned toast message\", Toast.LENGTH_LONG);\nt.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);\nt.show();\nComplete Code:XML \n \n \n Java import android.support.v7.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.Gravity; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.Toast; public class MainActivity extends AppCompatActivity { \n// Defining the object for button \nButton btn; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Binding the components to their respective objects by assigning \n// their IDs with the help of findViewById() method \nButton btn = (Button)findViewById(R.id.Button01); btn.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// Displaying posotioned Toast message \nToast t = Toast.makeText(getApplicationContext(), \"This a positioned toast message\", Toast.LENGTH_LONG); \nt.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0); \nt.show(); \n} \n}); \n} \n}Kotlin import android.os.Bundle \nimport android.view.Gravity \nimport android.widget.Button \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Binding the components to their respective objects by assigning \n// their IDs with the help of findViewById() method \nval btn = findViewById(R.id.Button01) \nbtn.setOnClickListener { // Displaying positioned Toast message \nval t = Toast.makeText(applicationContext, \"This a positioned toast message\", Toast.LENGTH_LONG) \nt.setGravity(Gravity.BOTTOM or Gravity.RIGHT, 0, 0) \nt.show() \n} \n} \n}Output:"}, {"text": "\nParticleView in Android with Examples\n\nParticleView is an animation library and animations help to gain the attention of the user so it is best to learn it. It is the custom android view that helps to display a large number of fairies.Why ParticleView?ParticleView provides a predefined layout type and animation.\nParticleView can be used in Splash Screen.\nIt is better to use ParticleView because of its UI because a good UI plays a very important role in an app.ApproachStep 1: Add the support library in the root build.gradle file (not in the module build.gradle file).\nallprojects {\n repositories {\n maven { url \u2018https://dl.bintray.com/wangyuwei/maven\u2019 }\n }\n}\n Step 2: Add the support library in build.gradle file and add dependency in the dependencies section.implementation \u2018me.wangyuwei:ParticleView:1.0.4\u2019Step 3: Add the following code in activity_main.xml file. In this file add the ParticleView to the layout.activity_main.xml \n Step 4: Add the following code in MainActivity.java file. In this file add ParticleAnimationListner() which will get invoked automatically when animation ends.MainActivity.java package org.geeksforgeeks.particleView import android.os.Bundle; \nimport android.view.View; \nimport android.widget.Toast; \nimport androidx.annotation.Nullable; \nimport androidx.appcompat.app.AppCompatActivity; \nimport me.wangyuwei.particleview.ParticleView; public class MainActivity extends AppCompatActivity { ParticleView particleView; \n@Override\nprotected void onCreate(@Nullable Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); particleView = findViewById(R.id.particleView); \nparticleView.startAnim(); // this listner will get invoked automatically \n// when animaion ends. \nparticleView.setOnParticleAnimListener( \nnew ParticleView.ParticleAnimListener() { \n@Override\npublic void onAnimationEnd() { \nToast.makeText(MainActivity.this, \n\"Animation is End!!\", \nToast.LENGTH_SHORT).show(); \n} \n}); \n} \n} Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200723030131/VID_202007230258461.mp4"}, {"text": "\nMaterial Design Buttons in Android with Example\n\nMaterial Design Components (MDC Android) offers designers and developers a way to implement Material Design in their Android application. Developed by a core team of engineers and UX designers at Google, these components enable a reliable development workflow to build beautiful and functional Android applications. If you like the way how the UI elements from Google Material Design Components for android which are designed by Google are pretty awesome, then here are some steps that need to be followed to get them, and one of them is Google Material Design Components (MDC) Buttons. A Button is a user interface that is used to perform some action when clicked or tapped. Under the Button category, there are mainly 4 types of buttons in Google material design components:Contained Button\nOutlined Button\nText Button\nToggle ButtonBelow is a demo for all types of Buttons that we are going to create in this project.Why MDC Buttons in Android?\nBefore going to implement all types of Button let\u2019s understand why choosing these material components over ordinary inbuilt components in android? Please refer to the following points to understand this.Choosing these material components saves time and these make the app look more like materially designed, and makes the way for user interactions hassle-free for developers.\nIf we take the buttons as an example we need to create a ripple as root element in custom_button.xml inside the drawable and then we need to set the background of the button as custom_button.xml, then only it will create the ripple effect for the ordinary button. But in Google MDCs there is no need of creating the manual ripple layout for the buttons.\nAnd the main thing about the Google Material Design Components is that these are open source and free. If you wish to contribute to the Google MDCs Click Here.\nOne more thing great about the Google Material Design Components is that they support for cross-platform that includes Android, IOS, Flutter, Web applications.\nIf the user wants to switch their system theme to Dark Theme, then the Google MDCs will automatically adapt and change their color and background to match the Dark Theme. But in the case of ordinary widgets, they won\u2019t get adapt to the system theme change. The differences between the normal button and the Google MDC button when the dark theme is enabled is shown below:Normal Contained Button behavior under dark theme.Google MDC button behavior under dark theme.\nApproach\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.\nStep 2: Add Required Dependency\nInclude google material design components dependency in the build.gradle file. After adding the dependencies don\u2019t forget to click on the \u201cSync Now\u201d button present at the top right corner. implementation \u2018com.google.android.material:material:1.3.0-alpha02\u2019Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below.Step 3: Change the Base application theme\nGo to app -> src -> main -> res -> values -> styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles.\nWhy the theme needs to be changed:\nLet\u2019s discuss why we need to change the action bar theme to the material theme of the app to invoke all the Google MDC widgets in our android application:Because all the Google material design components are built and packaged inside the MaterialTheme for Android.\nIf you are invoking the AppCompat action bar theme you will not end up with the error, but the application crashes immediately after launching it. Below is the code for the styles.xml file.styles.xml \n If you are unable to get the things in the step mentioned above you may refer to this image.Step 4: Change the colors of the application\nOne can change the color combination of the application and it\u2019s an optional step. Go to app -> src -> main -> res -> colors.xml file and choose your color combination.colors.xml \n \n#0f9d58 \n#006d2d \n#55cf86 \n If you are unable to get the things in the step mentioned above you may refer to this image.Step 5: Adding Google MDC buttons to the activity_main.xml file\nNow in this file, we are going to design the material button as the user requirements. Note that for each of the Button styles the \u201cstyle\u201d attribute is different.\nA. Button Style 1: Contained Button\nContained buttons are high-emphasis, distinguished by their use of elevation and fill. They contain actions that are primary to the app. Note that the contained button is the default style if the style is not set. Below is the XML code for the contained button.XML \n \n Output UI:B. Button Style 2: Outlined Button\nOutlined buttons are medium-emphasis buttons. They contain actions that are important but aren\u2019t the primary action in an app. These are used for more emphasis than text buttons due to the stroke. Below is the XML code for the Outlined button.XML \n \n Output UI:C. Button Style 3: Text Button\nText buttons are typically used for less-pronounced actions, including those located in dialogs and cards. In cards, text buttons help maintain an emphasis on card content. These are typically used for less important actions. Below is the XML code for the Text button.XML \n \n Output UI:D. Button Style 4: Toggle Button\nToggle buttons group a set of actions using layout and spacing. They\u2019re used less often than other button types. There are 2 types of Toggle Buttons in Google Material Design Components.Toggle Button\nToggle Button with iconsBefore going to the design part do some pre-task to implement these two buttons. As now the styles and the attributes like padding and margin of the buttons in the toggle group needs to be changed so in the values folder open styles.xml and invoke the following code:XML \n \n Toggle Button:\nTo emphasize groups of related toggle buttons, a group should share a common container. Below is the XML code for the Toggle button.XML \n \n Output UI:Toggle Button with icons:\nTo implement the toggle button with icons only import the icons in the drawable folder. In this example, we have imported format_black, format_italic, format_underline icons. To import the icons right-click on the drawable folder, goto new, and select Vector Asset as shown below.After clicking on Vector Asset select the icon you want to import to the drawable folder as shown below.After importing the desired icons invoke the code in the activity_main.xml file. Below is the XML code for the Toggle buttonwith icons.XML \n \n Output UI:For more information and more components like alert dialogue, SnackBars, etc., you may refer to the official documentation here. For more other resources and for more themes and customization you may visit and refer this."}, {"text": "\nHow to Create a Custom AlertDialog in Android?\n\nSometimes in AlertDialog, there is a need to get input from the user or customize it according to our requirements. So we create custom AlertDialogs. This post will show how to customize the AlertDialogs and take input from it.Below is the step-by-step implementation of the above approach:\nStep 1: Create an XML file custom_layout.xml\nAdd the below code in custom_layout.xml. This code defines the alert dialog box dimensions and adds an edit text to it.XML \n \n Step 2: Add a Button in activity_main.xml\nThe button when clicked will show the AlertDialog box.XML \n \n Step 3: Add custom_layout.xml file\nAdd custom_layout.xml in that activity in which you want to show a custom alert dialog here it is added in MainActivity.Java import android.os.Bundle; \nimport android.view.View; \nimport android.widget.EditText; \nimport androidx.appcompat.app.AlertDialog; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { \n@Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \n} public void showAlertDialogButtonClicked(View view) { \n// Create an alert builder \nAlertDialog.Builder builder = new AlertDialog.Builder(this); \nbuilder.setTitle(\"Name\"); // set the custom layout \nfinal View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null); \nbuilder.setView(customLayout); // add a button \nbuilder.setPositiveButton(\"OK\", (dialog, which) -> { \n// send data from the AlertDialog to the Activity \nEditText editText = customLayout.findViewById(R.id.editText); \nsendDialogDataToActivity(editText.getText().toString()); \n}); \n// create and show the alert dialog \nAlertDialog dialog = builder.create(); \ndialog.show(); \n} // Do something with the data coming from the AlertDialog \nprivate void sendDialogDataToActivity(String data) { \nToast.makeText(this, data, Toast.LENGTH_SHORT).show(); \n} \n}Kotlin import android.content.DialogInterface \nimport android.os.Bundle \nimport android.view.View \nimport android.widget.EditText \nimport android.widget.Toast \nimport androidx.appcompat.app.AlertDialog \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} fun showAlertDialogButtonClicked() { \n// Create an alert builder \nval builder = AlertDialog.Builder(this) \nbuilder.setTitle(\"Name\") // set the custom layout \nval customLayout: View = layoutInflater.inflate(R.layout.custom_layout, null) \nbuilder.setView(customLayout) // add a button \nbuilder.setPositiveButton(\"OK\") { dialog: DialogInterface?, which: Int -> \n// send data from the AlertDialog to the Activity \nval editText = customLayout.findViewById(R.id.editText) \nsendDialogDataToActivity(editText.text.toString()) \n} \n// create and show the alert dialog \nval dialog = builder.create() \ndialog.show() \n} // Do something with the data coming from the AlertDialog \nprivate fun sendDialogDataToActivity(data: String) { \nToast.makeText(this, data, Toast.LENGTH_SHORT).show() \n} \n}Output:https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200601161357/Custom-AlertDialog-in-Android.mp4"}, {"text": "\nHow to Extract Data from JSON Array in Android using Volley Library?\n\nIn the previous article on JSON Parsing in Android using Volley Library, we have seen how we can get the data from JSON Object in our android app and display that JSON Object in our app. In this article, we will take a look at How to extract data from JSON Array and display that in our app.JSON Array: JSON Array is a set or called a collection of data that holds multiple JSON Objects with similar sort of data. JSON Array can be easily identified with \u201c[\u201d braces opening and \u201c]\u201d braces closing. A JSON array is having multiple JSON objects which are having similar data. And each JSON object is having data stored in the form of key and value pair.What we are going to build in this article? \nWe will be building a simple application in which we will be displaying a list of CardView in which we will display some courses which are available on Geeks for Geeks. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210124132302/Screenrecorder-2021-01-24-13-21-47-357.mp4\nBelow is our JSON array from which we will be displaying the data in our Android App.[\n {\n \u201ccourseName\u201d:\u201dFork CPP\u201d,\n \u201ccourseimg\u201d:\u201dhttps://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png\u201d,\n \u201ccourseMode\u201d:\u201dOnline Batch\u201d,\n \u201ccourseTracks\u201d:\u201d6 Tracks\u201d\n },\n {\n \u201ccourseName\u201d:\u201dLinux & Shell Scripting Foundation\u201d,\n \u201ccourseimg\u201d:\u201dhttps://media.geeksforgeeks.org/img-practice/banner/linux-shell-scripting-thumbnail.png\u201d,\n \u201ccourseMode\u201d:\u201dOnline Batch\u201d,\n \u201ccourseTracks\u201d:\u201d8 Tracks\u201d\n },\n {\n \u201ccourseName\u201d:\u201d11 Weeks Workshop on Data Structures and Algorithms\u201d,\n \u201ccourseimg\u201d:\u201dhttps://media.geeksforgeeks.org/img-practice/banner/Workshop-DSA-thumbnail.png\u201d,\n \u201ccourseMode\u201d:\u201dOnline Batch\u201d,\n \u201ccourseTracks\u201d:\u201d47 Tracks\u201d\n },\n {\n \u201ccourseName\u201d:\u201dData Structures and Algorithms\u201d,\n \u201ccourseimg\u201d:\u201dhttps://media.geeksforgeeks.org/img-practice/banner/dsa-self-paced-thumbnail.png\u201d,\n \u201ccourseMode\u201d:\u201dOnline Batch\u201d,\n \u201ccourseTracks\u201d:\u201d24 Tracks\u201d\n }\n]Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add the below dependency in your build.gradle file\nBelow is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL. // below line is used for volley library\nimplementation \u2018com.android.volley:volley:1.1.1\u2019\n// below line is used for image loading library\nimplementation \u2018com.squareup.picasso:picasso:2.71828\u2019After adding this dependency sync your project and now move towards the AndroidManifest.xml part. \nStep 3: Adding permissions to the internet in the AndroidManifest.xml file\nNavigate to the app > AndroidManifest.xml and add the below code to it.XML \nStep 4: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n \n \n Step 5: Creating a Modal class for storing our data\nFor storing our data we have to create a new java class. For creating a new java class, Navigate to the app > java > your app\u2019s package name > Right-click on it > New > Java class and name it as CourseModal and add the below code to it. Comments are added inside the code to understand the code in more detail.Java public class CourseModal { // variables for our course \n// name and description. \nprivate String courseName; \nprivate String courseimg; \nprivate String courseMode; \nprivate String courseTracks; // creating constructor for our variables. \npublic CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) { \nthis.courseName = courseName; \nthis.courseimg = courseimg; \nthis.courseMode = courseMode; \nthis.courseTracks = courseTracks; \n} // creating getter and setter methods. \npublic String getCourseName() { \nreturn courseName; \n} public void setCourseName(String courseName) { \nthis.courseName = courseName; \n} public String getCourseimg() { \nreturn courseimg; \n} public void setCourseimg(String courseimg) { \nthis.courseimg = courseimg; \n} public String getCourseMode() { \nreturn courseMode; \n} public void setCourseMode(String courseMode) { \nthis.courseMode = courseMode; \n} public String getCourseTracks() { \nreturn courseTracks; \n} public void setCourseTracks(String courseTracks) { \nthis.courseTracks = courseTracks; \n} \n}Step 6: Creating a layout file for each item of our RecyclerView\nNavigate to the app > res > layout > Right-click on it > New > layout resource file and give the file name as course_rv_item and add the below code to it. Comments are added in the code to get to know in more detail.XML \n \n \n \n \n \n Step 7: Creating an Adapter class for setting data to our RecyclerView item\nFor creating a new Adapter class navigate to the app > java > your app\u2019s package name > Right-click on it > New > Java class and name it as CourseAdapter and add the below code to it.Java import android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.ImageView; \nimport android.widget.TextView; import androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; import com.squareup.picasso.Picasso; import java.util.ArrayList; public class CourseAdapter extends RecyclerView.Adapter { // creating a variable for array list and context. \nprivate ArrayList courseModalArrayList; \nprivate Context context; // creating a constructor for our variables. \npublic CourseAdapter(ArrayList courseModalArrayList, Context context) { \nthis.courseModalArrayList = courseModalArrayList; \nthis.context = context; \n} @NonNull\n@Override\npublic CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \n// below line is to inflate our layout. \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); \nreturn new ViewHolder(view); \n} @Override\npublic void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) { \n// setting data to our views of recycler view. \nCourseModal modal = courseModalArrayList.get(position); \nholder.courseNameTV.setText(modal.getCourseName()); \nholder.courseTracksTV.setText(modal.getCourseTracks()); \nholder.courseModeTV.setText(modal.getCourseMode()); \nPicasso.get().load(modal.getCourseimg()).into(holder.courseIV); \n} @Override\npublic int getItemCount() { \n// returning the size of array list. \nreturn courseModalArrayList.size(); \n} public class ViewHolder extends RecyclerView.ViewHolder { \n// creating variables for our views. \nprivate TextView courseNameTV, courseModeTV, courseTracksTV; \nprivate ImageView courseIV; public ViewHolder(@NonNull View itemView) { \nsuper(itemView); // initializing our views with their ids. \ncourseNameTV = itemView.findViewById(R.id.idTVCourseName); \ncourseModeTV = itemView.findViewById(R.id.idTVBatch); \ncourseTracksTV = itemView.findViewById(R.id.idTVTracks); \ncourseIV = itemView.findViewById(R.id.idIVCourse); \n} \n} \n}Step 8: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.View; \nimport android.widget.ProgressBar; \nimport android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; import com.android.volley.Request; \nimport com.android.volley.RequestQueue; \nimport com.android.volley.Response; \nimport com.android.volley.VolleyError; \nimport com.android.volley.toolbox.JsonArrayRequest; \nimport com.android.volley.toolbox.Volley; import org.json.JSONArray; \nimport org.json.JSONException; \nimport org.json.JSONObject; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for \n// our ui components. \nprivate RecyclerView courseRV; // variable for our adapter \n// class and array list \nprivate CourseAdapter adapter; \nprivate ArrayList courseModalArrayList; // below line is the variable for url from \n// where we will be querying our data. \nString url = \"https://jsonkeeper.com/b/WO6S\"; \nprivate ProgressBar progressBar; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // initializing our variables. \ncourseRV = findViewById(R.id.idRVCourses); \nprogressBar = findViewById(R.id.idPB); // below line we are creating a new array list \ncourseModalArrayList = new ArrayList<>(); \ngetData(); // calling method to \n// build recycler view. \nbuildRecyclerView(); \n} private void getData() { \n// creating a new variable for our request queue \nRequestQueue queue = Volley.newRequestQueue(MainActivity.this); \n// in this case the data we are getting is in the form \n// of array so we are making a json array request. \n// below is the line where we are making an json array \n// request and then extracting data from each json object. \nJsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener() { \n@Override\npublic void onResponse(JSONArray response) { \nprogressBar.setVisibility(View.GONE); \ncourseRV.setVisibility(View.VISIBLE); \nfor (int i = 0; i < response.length(); i++) { \n// creating a new json object and \n// getting each object from our json array. \ntry { \n// we are getting each json object. \nJSONObject responseObj = response.getJSONObject(i); // now we get our response from API in json object format. \n// in below line we are extracting a string with \n// its key value from our json object. \n// similarly we are extracting all the strings from our json object. \nString courseName = responseObj.getString(\"courseName\"); \nString courseTracks = responseObj.getString(\"courseTracks\"); \nString courseMode = responseObj.getString(\"courseMode\"); \nString courseImageURL = responseObj.getString(\"courseimg\"); \ncourseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks)); \nbuildRecyclerView(); \n} catch (JSONException e) { \ne.printStackTrace(); \n} \n} \n} \n}, new Response.ErrorListener() { \n@Override\npublic void onErrorResponse(VolleyError error) { \nToast.makeText(MainActivity.this, \"Fail to get the data..\", Toast.LENGTH_SHORT).show(); \n} \n}); \nqueue.add(jsonArrayRequest); \n} private void buildRecyclerView() { // initializing our adapter class. \nadapter = new CourseAdapter(courseModalArrayList, MainActivity.this); // adding layout manager \n// to our recycler view. \nLinearLayoutManager manager = new LinearLayoutManager(this); \ncourseRV.setHasFixedSize(true); // setting layout manager \n// to our recycler view. \ncourseRV.setLayoutManager(manager); // setting adapter to \n// our recycler view. \ncourseRV.setAdapter(adapter); \n} \n}Now run your app and see the output of the app.\nOutput:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210124132302/Screenrecorder-2021-01-24-13-21-47-357.mp4"}, {"text": "\nHow to Convert Java Code to Kotlin Code in Android Studio?\n\nIn Google I/O 2017, Kotlin has been declared as an official language for Android app development. This language gains popularity among developers very quickly because of its similarities as well as interoperable with Java language. One can mix code of Java and Kotlin while designing an Android project. Some of the major challenges faced by developers like avoiding null pointer exceptions are easily handled by Kotlin. Because of all these reasons, it became essential to learn Kotlin. However, Android Studio takes care of this need. Developers can easily convert their Java code into Kotlin in Android Studio. There can be 2 scenarios in front of developers:Converting a complete Java File/Class into Kotlin File/Class\nAdd a new Kotlin file/class in the project and convert a piece of Java code.This article broadly describes the steps involved in performing code conversion in both cases.Code Conversion\nMethod 1: Converting a Complete Class/File into Kotlin\nStep 1: Open source code file\nOpen the java source code file that is to be converted. Consider the given code of the MainActivity file that is to be converted into Kotlin.Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.TextView; public class MainActivity extends AppCompatActivity { // declaring variable for TextView component \nprivate TextView textView; // declaring variable to store \n// the number of button click \nprivate int count; @Override\nprotected void onCreate( Bundle savedInstanceState ) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // assigning ID of textView2 to the variable \ntextView = findViewById(R.id.textView2); // initializing the value of count with 0 \ncount = 0; \n} // function to perform operations \n// when button is clicked \npublic void buttonOnClick( View view){ // increasing count by one on \n// each tap on the button \ncount++; // changing the value of the \n// textView with the current \n// value of count variable \ntextView.setText(Integer.toString(count)); \n} \n}Step 2: Select the option\nFrom the left-hand side Option menu, select Android Project and right-click on the source code file. Select the option \u201cConvert Java File to Kotlin File\u201d. One can also use the shortcut command \u201cCtrl+Alt+Shift+K\u201d while the file is opened in Android Studio.A dialog box will appear that asks permission to configure Kotlin in Project. To carry out the code conversion it is necessary to grant this permission. Further, select the \u201cAll modules\u201d option and choose the latest Kotlin compiler installed on the computer. After clicking \u201cOK\u201d, Android Studio will make some changes in the app module build.gradle file to perform code conversion successfully.Step 3: Produce Kotlin file\nAgain select the \u201cConvert Java File to Kotlin File\u201d option by right click on the java class/file. This time the required conversion will happen and the file extension will get changed from .java to .kt. Below is the equivalent Kotlin code produced on converting the above mentioned MainActivity.java file.Kotlin import android.os.Bundle \nimport android.view.View \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // declaring variable for TextView component \nprivate var textView: TextView? = null// declaring variable to store \n// the number of button click \nprivate var count = 0override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // assigning ID of textView2 to the variable \ntextView = findViewById(R.id.textView2) // initializing the value of count with 0 \ncount = 0\n} // function to perform operations \n// when button is clicked \nfun buttonOnClick(view: View?) { // increasing count by one on \n// each tap on the button \ncount++ // changing the value of the \n// textView with the current \n// value of count variable \ntextView!!.text = Integer.toString(count) \n} \n}Method 2: Adding a Separate Kotlin File into the Project\nAndroid Studio allows the mixing of Java and Kotlin code in a project. If there is a requirement to reuse a piece of Java code by writing it in Kotlin, one can follow the below-mentioned steps.\nStep 1: Create a Kotlin Class/File\nCreate a new Class/File of Kotlin extension inside the java folder of the application\u2019s project file. Give it a desired name. Once the file is created, Android Studio will show an alert message that \u201cKotlin is not configured\u201d.Step 2: Configure Kotlin into the Project\nClick on the \u201cconfigure\u201d option present on the alert message. A dialog box will appear, select \u201cAll modules\u201d and choose the latest Kotlin compiler installed on the computer. Click \u201cOK\u201d and let the changes take place in build.gradle files.Step 3: Copy and Paste\nOnce Android Studio finished the build of project files, open the created Kotlin Class/File. Copy the Java code which is to be converted. Paste that code in the created file/class having Kotlin extension. That Java code will get converted automatically into Kotlin by the Android Studio.\nAdvantages of Kotlin Over JavaKotlin codes are more concise than Java.\nIt is interoperable(compatible) with Java.\nKotlin resolves nullability issues by placing \u201cNull\u201d in its type system.\nCleaner and safer code."}, {"text": "\nHow to Use Glide Image Loader Library in Android Apps?\n\nGlide, like Picasso, can load and display images from many sources, while also taking care of caching and keeping a low memory impact when doing image manipulations. Official Google apps (like the app for Google I/O 2015) are using Glide. In this article, we\u2019re going to explore the functionalities of Glide and why it\u2019s superior in certain aspects.\nGlide is an Image Loader Library for Android developed by bumptech and is a library that is recommended by Google. It has been used in many Google open source projects including Google I/O 2014 official application. It provides animated GIF support and handles image loading/caching. Animated GIF support is currently not implemented in Picasso. Yes, images play a major role in making the UI of an App more interactive and user-friendly too. So, as an Android Developer, we should take care of using images in App. We should handle the different aspects of an image like the slow unresponsive image, memory issues, loading errors, and many more. If you are not handling these aspects in your application, then your app will make a bad impression on your users.\nHow to Use Glide Android Library?\n1. For using Glide in the android project, we have to add the dependency in gradle file. So, For adding dependency open app/build.gradle file in the app folder in your Android project and add the following lines inside it.dependencies {\n implementation \u2018com.github.bumptech.glide:glide:4.11.0\u2019\n annotationProcessor \u2018com.github.bumptech.glide:compiler:4.11.0\u2019\n}Glide also needs Android Support Library v4, please don\u2019t forget to import support-v4 to your project like above as well. But it is not kind of a problem since Android Support Library v4 is basically needed in every single new-age Android project. Now sync your gradle once again. If you get any type of error then you may check the error on stackoverflow.\n2. Now add InternetPermission inside the AndroidManifest.xml file. Open the manifest.xml file and add the following line.3. Open the layout file for the main Activity. We need to add an ImageView to the layout. It doesn\u2019t need to be fancy. The following code snippet shows you what I mean.ImageView\n android:layout_width=\u201dwrap_content\u201d\n android:layout_height=\u201dwrap_content\u201d\n android:id=\u201d@+id/imageView\u201d\n android:layout_alignParentTop=\u201dtrue\u201d\n android:layout_centerHorizontal=\u201dtrue\u201d4. Now Navigate to the main Activity file and Add the following code block to the onCreate() method.ImageView imageView = (ImageView) findViewById(R.id.imageView);\n Glide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .into(imageView)\n .error(R.drawable.imagenotfound);In the first line, we are getting the ImageView instance from the layout. And then load the image from the above remote URL using Glide library.\nAdvanced Usage\nFor any real-time application, we must think of all possible cases. In the above code, we just store the image from the server link into the imageView.There are some more cases.ResizeGlide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .override(300, 200)\n .error(R.drawable.imagenotfound)\n .into(imageView);Here we are using Glide to fetch a remote image and overriding(resizing) it using before displaying it in an image view.PlaceholderGlide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .placeholder(R.drawable.placeholder)\n .into(imageView);If your application relies on remote assets, then it\u2019s important to add a fallback in the form of a placeholder image. The placeholder image is shown immediately and replaced by the remote image when Glide has finished fetching it.Handling errorsGlide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .placeholder(R.drawable.placeholder)\n .error(R.drawable.imagenotfound)\n .into(imageView);We already saw how the placeholder method works, but there\u2019s also an error method that accepts a placeholder image. Glide will try to download the remote image three times and display the error placeholder image if it was unable to fetch the remote asset.GIFS SupportGlideDrawableImageViewTarget imagePreview = new GlideDrawableImageViewTarget(imageView);\nGlide.with(this).load(url).listener(new RequestListener() { \n @Override \n public boolean onException(Exception e, String model, Target target, boolean isFirstResource) { \n return false; \n } \n @Override \n public boolean onResourceReady(GlideDrawable resource, String model, Target target,\n boolean isFromMemoryCache, boolean isFirstResource) {\n return false; \n } \n }).into(imagePreview);EffectsBlur image:Glide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .bitmapTransform(new BlurTransformation(context))\n .into(imageView);Multiple Transform:Glide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .bitmapTransform(new BlurTransformation(context, 25), new CropCircleTransformation(context))\n .into(imageView);Circle crop:Glide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .bitmapTransform(new CropCircleTransformation(context))\n .into(imageView);Rounded Corners:int radius = 50; \nint margin = 20;\nGlide.with(context)\n .load(\u201cYOUR IMAGE URL HERE\u201d)\n .bitmapTransform(new RoundedCornersTransformation(context, radius, margin))\n .into(imageView);"}, {"text": "\nKey Properties of Material Design EditText in Android\n\nIn the previous article Material Design EditText in Android with Examples its been discussed how to implement the Material design EditText and how they differ from the normal EditText. In this article its been discussed on how to customize MDC edit text fields with their key properties. Have a look at the following image to get the idea about the key properties of the MDC edit text fields.Customizing the MDC EditText by using Key Properties\nKey Property 1: Box stroke color and widthInvoke the following code inside activity_main.xml file.\nThe attributes need to be concentrated are boxStrokeColor, boxStrokeWidth, boxStrokeWidthFocused. Inside the TextInputLayout.XML \n \n \n Output UI: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201102132758/Untitled-Project.mp4\nKey Property 2: Adding the end icon mode and start icon mode\nThere are 4 types of end icon modes for MDC EditTexts. Those are:clear text.\npassword toggle.\ncustom.\ndropdown menu.Note: For password toggle, the input type is required for the MDC EditText.For the start icon, there is a need for a vector icon. So import vector icon by right click on the drawable -> new -> Vector asset. Then select the desired vector icons.\nRefer to the following image if unable to locate the vector asset dialog in Android Studio.Invoke the following code into activity_main.xml file.XML \n \n\n\n \n\n\n Output UI: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201102140338/Untitled-Project.mp4\nKey Property 3: Helper textThis is the small text which can be invoked to inform the user what type of data to be entered to the EditText.\nInvoke the following to inside the activity_main.xml file. Comments are added inside the code for better understanding.XML \n \n\n \n\n Output UI: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201102141319/Untitled-Project.mp4"}, {"text": "\nHow to Generate API Key for Using Google Maps in Android?\n\nFor using any Google services in Android, we have to generate an API key or we have to generate some unique key for using that service provided by Google. So Maps is one of the famous and most used services provided by Google. Maps can be seen in each and every app provided by Google and we also can use that service to add maps to our app. So in this article, we will take a look at the process of generating an API key for using Google Maps.\nStep by Step Implementation\nStep 1: Browse the below site on your browser\nClick on this link to go to the Google Maps developer platform. You will get to see the below page. After click on the above link, you will get to see the below screen. Inside this click on the Go to Credentials page to go to the Credentials page for API key generation.After clicking on this option a new page will open inside that screen click on create a new project option in the top bar.\nStep 2: Creating a new project\nTo create a new project click on Create Project option as shown below. After clicking on create project option. You will get to see the below screen for creating a new project.\nStep 3: Add your name and organization for your project\nAdd your project name and organization name in the fields present on the screen. For testing, you can use you can provide a no organization option to proceed further.After adding your project name and organization name. Click on Create option to proceed further.\nStep 4: Create credentials for your API keyTo create an API key for Maps click on Create credentials option and then select the API key option as shown below.Click on the API key option to generate your API key. After clicking on this option your API key will be generated which is shown below.Now you can use this API for using maps. But this key is used by anyone in any of the projects. So we have to restrict the API key for our own project so that anyone cannot use this API key inside their app.\nStep 5: Restrict your API key\nTo restrict your API click on Restrict key option. After clicking on this option you will get to see the below screen.Inside this screen click on Android apps and click on Add an item option and after that, you will get to see the below screen.Inside this option, you have to add your app\u2019s package name, the app\u2019s SHA-1 certificate fingerprint, and click on the save option which is given below. After clicking on the save option your key is now restricted. Now you can use your key in google maps to add Google Maps to your app. You can refer to this article on How to Generate SHA-1 key for Android App in Android Studio.\n"}, {"text": "\nFirebase \u2013 Introduction\n\nFirebase is a product of Google which helps developers to build, manage, and grow their apps easily. It helps developers to build their apps faster and in a more secure way. No programming is required on the firebase side which makes it easy to use its features more efficiently. It provides services to android, ios, web, and unity. It provides cloud storage. It uses NoSQL for the database for the storage of data.Brief History of Firebase:\nFirebase initially was an online chat service provider to various websites through API and ran with the name Envolve. It got popular as developers used it to exchange application data like a game state in real time across their users more than the chats. This resulted in the separation of the Envolve architecture and it\u2019s chat system. The Envolve architecture was further evolved by it\u2019s founders James Tamplin and Andrew Lee,to what modern day Firebase is in the year 2012.\nFeatures of Firebase:\nMainly there are 3 categories in which firebase provides its services.Build better applications\nThis feature mainly includes backend services that help developers to build and manage their applications in a better way. Services included under this feature are :Realtime Database: The Firebase Realtime Database is a cloud-based NoSQL database that manages your data at the blazing speed of milliseconds. In simplest term, it can be considered as a big JSON file.Cloud Firestore: The cloud Firestore is a NoSQL document database that provides services like store, sync, and query through the application on a global scale. It stores data in the form of objects also known as Documents. It has a key-value pair and can store all kinds of data like, strings, binary data, and even JSON trees.Authentication: Firebase Authentication service provides easy to use UI libraries and SDKs to authenticate users to your app. It reduces the manpower and effort required to develop and maintain the user authentication service. It even handles tasks like merging accounts, which if done manually can be hectic.Remote Config: The remote configuration service helps in publishing updates to the user immediately. The changes can range from changing components of the UI to changing the behavior of the applications. These are often used while publishing seasonal offers and contents to the application that has a limited life.Hosting: Firebase provides hosting of applications with speed and security. It can be used to host Stati or Dynamic websites and microservices. It has the capability of hosting an application with a single command.\nFirebase Cloud Messaging(FCM): The FCM service provides a connection between the server and the application end users, which can be used to receive and send messages and notifications. These connections are reliable and battery-efficient.Improve app quality:\nHere majorly all the application performance and testing features are provided. All the features required to check and manage before launching your application officially are provided in this section. Services included are:Crashlytics: It is used to get real-time crash reports. These reports can further be used to improve the quality of the application. The most interesting part of this service is that it gives a detailed description of the crash which is easier to analyze for the developers.\nPerformance monitoring: This service gives an insight to the performance characteristics of the applications. The performance monitoring SDK can be used to receive performance data from the application, review them, and make changes to the application accordingly through the Firebase console.\nTest lab: This service helps to test your applications on real and virtual devices provided by Google which are hosted on the Google Datacenters. It is a cloud-based app-testing infrastructure which supports testing the application on a wide variety of devices and device configurations\nApp Distribution:This service is used to pre-release applications that can be tested by trusted testers. It comes in handy as decreases the time required to receive feedback from the testers.Grow your app:\nThis feature provides your application analytics and features that can help you to interact with your user and make predictions that help you to grow your app. Services provided are:Google analytics: It is a Free app measurement service provided by Google that provides insight on app usage and user engagement. It serves unlimited reporting for up to 500 distinct automatic or user-defined events using the Firebase SDK.\nPredictions: Firebase Predictions uses machine learning to the application\u2019s analytics data, further creating dynamic user segments that are based on your user\u2019s behavior. These are automatically available to use for the application through Firebase Remote Config, the Notifications composer, Firebase In-App Messaging, and A/B Testing.\nDynamic Links: Deeps Links are links that directly redirects user to specific content. Firebase provides a Dynamic linking service that converts deep links into dynamic links which can directly take the user to a specified content inside the application. Dynamic links are used for converting web users to Native app users. It also increases the conversion of user-to-user sharing. In addition, it can also be used to integrate social media networks, emails, and SMS to increase user engagement inside the application.\nA/B Testing: It is used to optimize the application\u2019s experience by making it run smoothly, scaling the product, and performing marketing experiments.Pros and Cons of Using Firebase:\nBelow listed are the advantages and disadvantages of using a Firebase backend:\nPros:Free plans for beginners.\nReal-time database is available.\nGrowing Community.\nNumerous services are available.Cons:It uses NoSQL so, people migrating from SQL might feel difficulty.\nIt is still growing so, it is not tested to an extent.Companies using Firebase\nBelow are some reputable organizations that rely on a firebase backend for its functioning:The New York Times\nAlibaba.com\nGameloft\nDuolingo\nTrivago\nVenmo\nLyftPricing:\nThere are 2 plans available. Spark plan is initially free but as your user base grows you might need to upgrade to blaze plan. Firebase asks you to pay as you go. For most developers who are just getting started and are on a learning path, they are covered by spark plan."}, {"text": "\nNotifications in Android Oreo (8+)\n\nAndroid Oreo has brought in a ton of changes. This also includes the way in which a user issue notifications in an app. In this article, we will discuss the changes required to be made in the notification department. The following things are to be kept in mind while issuing notifications:Designing a Notification Channel\nImportance of each notification channel\nNotification ID (different from channel id) should not be set to zero.Before going forward, make sure this line is added to the build.gradle (Module: app) dependencies:\nimplementation 'com.android.support:appcompat-v7:26.1.0'\nLet\u2019s start with making a notification channel. The method below creates a notification channel:Java // Import necessary classes\nimport android.app.Notification;\nimport android.app.NotificationChannel;\nimport android.app.NotificationManager;\nimport android.content.Context;\nimport android.os.Build;\nimport androidx.core.app.NotificationCompat;public class Example {private void issueNotification()\n{\n// Create the notification channel for Android 8.0+\nif (Build.VERSION.SDK_INT\n>= Build.VERSION_CODES.O) {\nmakeNotificationChannel(\n\"CHANNEL_1\", \"Example channel\",\nNotificationManager.IMPORTANCE_DEFAULT);\n}// Creating the notification builder\nNotificationCompat.Builder notificationBuilder\n= new NotificationCompat.Builder(this,\n\"CHANNEL_1\");// Setting the notification's properties\nnotificationBuilder\n.setSmallIcon(R.mipmap.ic_launcher)\n.setContentTitle(\"Notification!\")\n.setContentText(\"This is an Oreo notification!\")\n.setNumber(3);// Getting the notification manager and send the\n// notification\nNotificationManager notificationManager\n= (NotificationManager)getSystemService(\nContext.NOTIFICATION_SERVICE);// it is better to not use 0 as notification id, so\n// used 1.\nnotificationManager.notify(\n1, notificationBuilder.build());\n}// Helper method to create a notification channel for\n// Android 8.0+\nprivate void makeNotificationChannel(String channelId,\nString channelName,\nint importance)\n{\nNotificationChannel channel\n= new NotificationChannel(\nchannelId, channelName, importance);\nNotificationManager notificationManager\n= (NotificationManager)getSystemService(\nNOTIFICATION_SERVICE);\nnotificationManager.createNotificationChannel(\nchannel);\n}\n}Let\u2019s see what this method does in detail.The method accepts String id, String name, int importance.String id: This is the id with which you issue a notification in the notification channel. You use this exact id for multiple notifications in the same channel.\nString name: This is the name of the channel visible when someone taps and navigate to Settings -> Apps & Notifications -> [your_app_name] -> App notifications.\nint importance: This is the importance level of the channel. The levels are as follows:NotificationManager.IMPORTANCE_MIN \u2013 shows only in the notification shade, no sound or peek.\nNotificationManager.IMPORTANCE_LOW \u2013 shows everywhere, doesn\u2019t make sound, doesn\u2019t peek.\nNotificationManager.IMPORTANCE_DEFAULT \u2013 shows everywhere, makes sound but doesn\u2019t peek.\nNotificationManager.IMPORTANCE_HIGH \u2013 shows everywhere, makes sound and peeks (visual interruption).\nNotificationManager.IMPORTANCE_MAX \u2013 this importance level is usually not used. Works similar to IMPORTANCE_HIGH.The method then creates the channel with the parameters.\nThe setShowBadge(true) makes the notification available by the Oreo notification dot feature.\nFinally, the notification channel is created by the createNotificationChannel() method of NotificationManager.First, the above method initially creates a notification channel with id = \u201cCHANNEL_1\u201d and the name \u201cExample channel\u201d. The id isn\u2019t visible anywhere but the name can be viewed by opening the \u201cApp notifications\u201d option of the App Info page. \nThen a NotificationCompat.Builder object is made specifying the context and id as \u201cCHANNEL_1\u201d. A different channel id can be mentioned provided it is made with the makeNotificationChannel() method. The rest is self-explanatory. The setNumber() method shows a number in the notification dot of the app. \nFinally, the notification id (here 1) is better to not set 0 as in cases where the notification is used for a Foreground service, it will fail to display if the id is 0. On executing the issueNotification() method, we get the following notification: "}, {"text": "\nHow to Use Proguard to Reduce APK Size in Android?\n\nApp size matters a lot when building any application. If the app size is larger most of the users will not download your app due to its huge size. The large app size will cost your user huge data and he will also require disk space to install your application. So to reduce the size of APK proguard is one of the important java tools which is used to reduce the size of your APK. In this article we will take a look at the topics mentioned below:What is Proguard?\nWhat are the uses of Proguard?\nHow to use proguard inside your app?\nWhat are the disadvantages of using Proguard?\nCustom rules in Proguard.What is Proguard?\nProguard is a java tool that is present in Android and it is used to reduce your app size. It is a free tool that will help you to reduce your app size by 8.5 %. Proguard will convert your app\u2019s code into optimized Dalvik bytecode. The process for conversion is as follows:What are the Uses of Proguard?Proguard will obfuscate your code and rename your code. In this process, it will rename your files of different java classes. This will make your app more secure and difficult to reverse engineer.\nIt will remove unused code snippets inside your code and optimize your code.\nUsing proguard will reduce your app size by 8.5 %.\nProguard will shrink the resources inside your app which is not being used in your app.\nThe usage of proguard will reduce your app size and make your code inline. This will make your app faster and less in size.How to use Proguard inside your app?\nTo enable proguard inside your app, navigate to the app > gradle Scripts > Open build.gradle file. Inside that gradle file you will get to see below lines of code in your file inside the release section. Change minifyEnabled from false to true. This will activate your proguard with the proguard file.buildTypes {\n release {\n // make change here\n minifyEnabled true\n proguardFiles getDefaultProguardFile(\u2018proguard-android-optimize.txt\u2019), \u2018proguard-rules.pro\u2019\n }\n }You will find this set of code inside your release block. This means that Proguard will be activated for your release app only. \nCustom Rules in Proguard\nWhen we use proguard inside our application it will automatically remove some modal classes which are required inside our app. So to avoid removing these files we have to add some custom rules inside our application.\n1. Keeping our class\nWhile using libraries for networking or while implementing a RecyclerView or ListView. We have to create a Data class for storing all our Data. So while using the Proguard it will remove the variables of the class which is of no usage. So to avoid the removal of variables of this class we have to add @Keep annotation to that class. For example, we are creating a data class for storing studentName and StudentId inside our class and we don\u2019t want proguard to obfuscate our class. So in this case we will add @Keep annotation to it. So in the below code snippet @Keep will prevent this class from obfuscating. Along with \u201c@keep\u201d we can also use -keep to prevent our class obfuscating. If we have to preserve any variable of our class then we will annotate that variable with \u201c@SerializableName\u201d. This type of annotation is mostly used when we have to parse data from a JSON file or from a server. Java /*package whatever //do not write package name here */import java.io.*; \n@Keep\nclass GFG { \nstring StudentName; \nint studentID; \n}2. Keeping names of our Class and its members\nSuppose if we have to keep the name of our class and its member variables then we will use annotation as \u2018-keepnames\u2019. This annotation will keep the name of that class as well as its member variables. Although proguard will shrink this class it will not obfuscate your class. Below code snippet will tell us that How we have to use \u201c-keepnames\u201d to keep our class members.Java /*package whatever //do not write package name here */import java.io.*; -keepnames class GFG { \nstring studentName; \nint studentId; \n}3. Keeping the members of our class\nIf we want to keep only the members of the class and not the class from obfuscating by Proguard. Then we will annotate that class with \u201c-keepclassmembers\u201d. This annotation will prevent the obfuscating of our class members. Below is the code snippet in which we will see the implementation of this method.Java /*package whatever //do not write package name here */import java.io.*; -keepclassmembers class GFG { \nstring studentName; \nint studentId; \n}4. Keeping annotations\nWhen using Proguard it will remove all the annotations which we add in our class provided by libraries. In any case, this code works fine without any issue. But it may cause issues if removed. If you are using a Retrofit library for fetching data from web servers in your app then you use so many annotations such as \u201c@GET\u201d, \u201c@POST\u201d,\u201d@PUSH\u201d and many more. If these annotations will get removed Retrofit may cause issues to get the data from the server. So to avoid the removal of these annotations we will use \u201c-keepattributes \u201d keyword. Below is the code snippet of its usage.Java /*package whatever //do not write package name here */import java.io.*; -keepattributes @GET\nclass GFG { \nstring studentName; \nint studentID; \n}5. Using external libraries\nWhen we are using some external libraries. They provide specific rules which we can add to our proguard rules. But if the library is not having any rules present in it. Then in that case we can get to see warnings in our logs. To avoid the warnings of this library we have to add the library with \u201c-dontwarn\u201d annotation in our proguard.-dontwarn \u201cyour library\u201dDisadvantages of Using Proguard\nSometimes while using Proguard it will remove a huge set of code that is required and this might cause crashes in your application. So to avoid removing this code from our application code. We have to add some custom rules inside our Proguard to keep that specific file so that removal of that files will be avoided and our app will not crash even after using proguard.\nConclusion\nSo Proguard is very helpful in reducing the size of our app and it will also make our app more secure and difficult to reverse engineer. So we should use this for optimization of our app\u2019s size."}, {"text": "\nHow to Restore Data on Configuration Changed in Android using Bundles?\n\nIn Android, if the configuration of the application changes, for example when the android screen is rotated, then some data is lost and reset. Especially, the data from the variables. So this issue can be solved by overriding the functions onSaveInstanaceState() and onRestoreInstanceState(). So in this article, it\u2019s been discussed how this issue can be resolved in detail using the flow chart, so as to understand when these above functions are called. Note that we are going toimplement this project using theKotlinlanguage.\nBelow is a flow chart represents how the methods are called and data is restored and updated in the UI:Step by Step Implementation\nStep 1: Create an empty activity projectUsing Android Studio create a new empty activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?, to know how to create an empty activity Android Studio project.Step 2: Working with the activity_main.xml fileThe main layout of the application containing EditText, and one TextView, and two Buttons, which increment and decrement the value of the TextView.\nTo implement the UI invoke the following code inside the activity_main.xml file.XML \n Output:Step 3: Working with the MainActivity.kt fileIn the MainActivity,kt file the two functions onSaveInstanceState(outState: Bundle) and onRestoreInstanceState(savedInstanceState: Bundle) has to be overridden, the onSaveInstanceState function puts the data to bundle named outState, and onRestoreInstanceState function receives the data using Bundle named savedInstanceState. Refer to the flow chart provided above to get clear flow.\nTo implement the same invoke the following code inside the MainActivity.kt file.\nComments are added inside the code to understand the code in more detail.Kotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.widget.Button \nimport android.widget.EditText \nimport android.widget.TextView class MainActivity : AppCompatActivity() { // instances of all the UI elements \nlateinit var editText: EditText \nlateinit var counterText: TextView \nlateinit var incrementB: Button \nlateinit var decrementB: Button // counter to increment or \n// decrement the counter text \nvar countInt: Int = 0override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // register all the UI elements with \n// their appropriate IDs \neditText = findViewById(R.id.editText) \nincrementB = findViewById(R.id.incrementB) \ndecrementB = findViewById(R.id.decrementB) \ncounterText = findViewById(R.id.counterText) // handle the increment button \nincrementB.setOnClickListener { \nif (countInt >= 0) { \ncountInt++ \ncounterText.text = countInt.toString() \n} \n} // handle the decrement button \ndecrementB.setOnClickListener { \nif (countInt > 0) { \ncountInt-- \ncounterText.text = countInt.toString() \n} \n} \n} override fun onSaveInstanceState(outState: Bundle) { \nsuper.onSaveInstanceState(outState) // put the unique key value with the data \n// to be restored after configuration changes \noutState.putInt(\"counterData\", countInt) \n} override fun onRestoreInstanceState(savedInstanceState: Bundle) { \nsuper.onRestoreInstanceState(savedInstanceState) // get the stored data from the bundle using the unique key \ncountInt = savedInstanceState.getInt(\"counterData\") // update the UI \ncounterText.text = countInt.toString() \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20210123181531/Untitled.mp4"}, {"text": "\nShimmerLayout in Android with Examples\n\nShimmerLayout can be used to add a Shimmer Effect (like the one on Facebook or LinkedIn) to the Android Application. This layout is mainly used when an app fetched data from API but the task is a long-running task. Therefore it is better to add ShimmerLayout rather than showing the blank screen as it notifies the user that the layout is in the loading state. The code has been given in both Java and Kotlin Programming Language for Android.\nAdvantages:ShimmerLayout is memory efficient.\nIt can be customized according to the need of the application.Disadvantage:It is deprecated.Approach:\n1. Add the support library in the App-level build.gradle file and add dependency in the dependencies section. It allows the developer to use the inbuilt function directly.\ndependencies { \n implementation 'io.supercharge:shimmerlayout:2.1.0'\n}\n2. Create circle.xml file in the drawable folder and add the following code. This will be used in the ShimmerLayout along with the text view.XML \n \n \n \n \n 3. Add the following code in the activity_main.xml file. In this file, add ShimmerLayout and its child view. Add circle.XML in the src tag in ImageView.XML \n \n \n \n 4. Add the following code to the MainActivity File. In this file, the startShimmerAnimation method is used to start the animation on ShimmerLayout.Java import android.os.Bundle; \nimport androidx.appcompat.app.AppCompatActivity; \nimport io.supercharge.shimmerlayout.ShimmerLayout; public class MainActivity extends AppCompatActivity { \n@Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); ShimmerLayout layout = findViewById(R.id.shimmer_layout); \nlayout.startShimmerAnimation(); \n} \n}Kotlin import android.os.Bundle \nimport androidx.appcompat.app.AppCompatActivity \nimport io.supercharge.shimmerlayout.ShimmerLayout class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) val layout: ShimmerLayout = findViewById(R.id.shimmer_layout) \nlayout.startShimmerAnimation() \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200719214545/Record_2020-07-19-21-23-01_69fa71ed7e998de6cab47c8740bea3c11.mp4"}, {"text": "\nAndroid | build.gradle\n\nGradle is a build system (open source) that is used to automate building, testing, deployment, etc. \u201cbuild.gradle\u201d are script where one can automate the tasks. For example, the simple task of copying some files from one directory to another can be performed by the Gradle build script before the actual build process happens.\nWhy is Gradle Needed?Every Android project needs a Gradle for generating an apk from the .java and .xml files in the project. Simply put, a Gradle takes all the source files (java and XML) and applies appropriate tools, e.g., converts the java files into dex files and compresses all of them into a single file known as apk that is actually used. There are two types of build.gradle scripts\nTop-level build.gradleModule-level build.gradleTop-level build.gradle:\nIt is located in the root project directory and its main function is to define the build configurations that will be applied to all the modules in the project. It is implemented as:Gradle// Top-level build file where you can add configuration\n// options common to all sub-projects/modules.buildscript {\n repositories {\n google()\n mavenCentral() }\n dependencies {\n classpath 'com.android.tools.build:gradle:3.4.3'\n }\n}allprojects {\n repositories {\n google()\n mavenCentral()\n }\n}task clean(type: Delete) {\n delete rootProject.buildDir\n}The top-level build.gradle supports various build configurations like:\nbuildscript: This block is used to configure the repositories and dependencies for Gradle.\nNote: Don\u2019t include dependencies here. (those will be included in the module-level build.gradle)\ndependencies: This block in buildscript is used to configure dependencies that the Gradle needs to build during the project.Gradleclasspath 'com.android.tools.build:gradle:3.0.1' This line adds the plugins as a classpath dependency for gradle 3.0.1.\nallprojects: This is the block where one can configure the third-party plugins or libraries. For freshly created projects android studio includes mavenCentral() and Google\u2019s maven repository by default.task clean(type:Delete): This block is used to delete the directory every time the project is run. This way the projects keep clean when someone modifies some config files like, during settings.gradle which requires a complete clean.Module-level build.gradle:\nLocated in the project/module directory of the project this Gradle script is where all the dependencies are defined and where the SDK versions are declared. This script has many functions in the project which include additional build types and override settings in the main/app manifest or top-level build.gradle file. It is implemented as:Gradle// The first line in this file indicates\n// the Android plugin is applied for Gradle to\n// this buildapply plugin : 'com.android.application'android\n{\n compileSdkVersion 30\n buildToolsVersion \"30.0.3\"\n {\n applicationId \"example.mehakmeet.geeksforgeeks\"\n minSdkVersion 19\n targetSdkVersion 30\n versionCode 1\n versionName \"1.0\"\n }\n buildTypes\n {\n release\n {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}dependencies\n{\n implementation fileTree(include\n : [ '*.jar' ], dir\n : 'libs')\n implementation 'com.android.support:appcompat-v7:26.1.0'\n}The Module-level build.gradle supports various build configurations like:\nandroid: This block is used for configuring the specific android build options.compileSdkVersion \u2013 This is used to define the API level of the app and the app can use the features of this and lower level.defaultConfig:applicationId\u2013 This is used for identifying unique id for publishing of the app.minSdkVersion\u2013 This defines the minimum API level required to run the application.targetSdkVersion\u2013 This defines the API level used to test the app.versionCode\u2013 This defines the version code of the app. Every time an update needs to be of the app, the version code needs to be increased by 1 or more.versionName\u2013 This defines the version name for the app. this could be increased by much while creating an update.buildTypes(release):minifyEnabled\u2013 this will enable code shrinking for release build.proguardFiles\u2013 this will specify the progaurd settings file.dependencies: This specifies the dependencies that are needed to build the project.Both the top-level and module-level build.gradle files are the main script files for automating the tasks in an android project and are used by Gradle for generating the APK from the source files."}, {"text": "\n6 Most Useful Android Studio Plugins\n\nAndroid Studio provides a platform where one can develop android apps for Android phones, tablets, Android Wear, Android TV. Android Studio is the official IDE for Android application development, and it is based on the IntelliJ IDEA. One can develop Android Applications using Kotlin or Java as the Backend Language and XML for developing frontend UI.In computing, a plug-in is a software component that adds a particular characteristic to an existing computer program. When a program supports plug-ins, it enables customization. Plugins are a great way to increase productivity and overall programming experience.\u2063\u2063 Some tasks are boring and not fun to do, by using plugins in the android studio you can get more done in less time. \u2063\u2063 So in this article, we will share with you 7 useful android studio plugins that will help to become a better android developer.\u2063\u2063\n1. Key Promoter X\nKey Promoter X helps to get the necessary shortcuts while working on android projects. When the developers utilize the mouse on a button inside the IDE, the Key Promoter X presents the keyboard shortcut that you should have used alternatively. Key Promoter X provides a simple way to study how to replace tiresome mouse work with keyboard keys and helps to transition to faster, mouse-free development. The Key Promoter X tool window gives a hit-list of the mouse actions that are utilized by the developers most and it quickly provides the shortcut that developers can use alternatively. Buttons having no shortcut, the Key Promoter X prompts with the opportunity to directly create one.\n2. ButterKnifeZelezny\nButterKnifeZelezny is an android studio plug-in for creating ButterKnife injections from selected layout XML. It is a very simple plug-in for Android Studio/IDEA that supports one-click creation of Butterknife view injections. The fun fact is ButterKnifeProgrammers are lazy, and programmers who are not lazy are not good programmers. Almost Android developers should know @JakeWharton\u2019s ButterKnife annotation library. The developer can implement this library without writing a lot of boring findViewById() and setOnClickListener(). The main purpose is to make it easy for developers to quickly generate the code of the control binding view and enhance coding efficiency.\n3. Json To Kotlin Class\nJson to kotlin Class is a plugin to create Kotlin data class from JSON string, in other words, a plugin that changes JSON string to Kotlin data class. With this, you can generate a Kotlin data class from the JSON string programmatically. Supporting (almost) all kinds of JSON libs\u2019 annotation(Gson, Jackson, Fastjson, MoShi and LoganSquare, kotlinx.serialization(default custom value)). Some of the important features are:Customizing the own annotations\nInitializing properties with default values\nAllowing properties to be nullable(?)\nDetermining property nullability automatically\nRenaming field names to be camelCase style when selecting a target JSON lib annotation\uff0e\nGenerating Kotlin class as individual classes\nGenerating Kotlin class as inner classes\nFormatting any legal JSON string\nGenerating Map Type when json key is the primitive type\nOnly create annotation when needed\nCustom define data class parent class\nSort property order by Alphabetical\nMake keyword property valid\nSupport Loading JSON From Paster/Local File/Http URL\nSupport customize your own plugin by Extension Module\nNormal Class support\nDynamic plugin load support\nSupport generating ListClass from JSONArray\nComplex json schema supportingJson to kotlin Class is a an excellent tool for Kotlin developers and it can convert a JSON string to Kotlin data class. The tool could not only understand the primitive types but also auto-create complex types. It\u2019s simply accessible. We provide shortcut keymap ALT + K for Windows and Option + K for Mac, have a try and you are going to fall in love with it! JsonToKotlinClass just makes programming more delightful.\n4. Rainbow Brackets\nRainbow Brackets adds rainbow brackets and rainbows parentheses to the code. Color coding the brackets makes it simpler to obtain paired brackets so that the developers don\u2019t get lost in a sea of identical brackets. This is a very helpful tool and saves the confusion of selecting which bracket needs to be closed. Each pair of brackets/parentheses has a different color. Pretty simple, but an excellent plugin.\n5. CodeGlance\nCodeglance plugin illustrates a zoomed-out overview or minimap similar to the one found in Sublime into the editor pane. The minimap enables fast scrolling letting you jump straight to sections of code. Some of the important features are:Codeglance operates with both light and dark themes using the customized colors for syntax highlighting.\nWorker thread for rendering\nColor rendering using IntelliJ\u2019s tokenizer\nScrollable!\nEmbedded into the editor window\nComplete replacement for Code Outline that helps new Intellij builds.6. ADB Idea\nADB Idea is a plugin for Android Studio and Intellij IDEA that speeds up the usual android development. It allows shortcuts for various emulator functionalities that are normally very time consuming, like resetting the app data, uninstalling the app, or initializing the debugger. The following commands are provided:ADB Uninstall App\nADB Kill App\nADB Start App\nADB Restart App\nADB Clear App Data\nADB Clear App Data and Restart\nADB Start App With Debugger\nADB Restart App With Debugger\nADB Grant/Revoke Permissions\nADB Enable/Disable Wi-Fi\nADB Enable/Disable Mobile Data"}, {"text": "\nImageView in Android using Jetpack Compose\n\nImages, Graphics, and vectors attract so many users as they tell so much information in a very informative way. ImageView in Android is used to display different types of images from drawable or in the form of Bitmaps. In this article, we will take a look at the implementation of an ImageView in Android using Jetpack Compose.\nAttributes of ImageView WidgetAttributesDescriptionimageVector\nto add an image from Drawable resource inside our imageviewbitmap\nto add a bitmap for your image inside imageview.modifier\nto add padding to imageviewcontentScale\nto add scaling to our image to fit our image inside imageviewalpha\nto add alpha to our imageview.colorFilter\nto add colors to our imageview.blendMode\nto add color effects to our imageview.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.\nStep 2: Add an Image to the drawable folder\nAfter creating a new project we have to add an image inside our drawable folder for displaying that image inside our ImageView. Copy your image from your folder\u2019s location and go inside our project. Inside our project Navigate to the app > res > drawable > Right-click on the drawable folder and paste your image there.\nStep 3: Working with the MainActivity.kt file\nAfter adding this image navigates to the app > java > MainActivity.kt and add the below code to it. Comments are added inside the code for a detailed explanation.Kotlin package com.example.edittext import android.os.Bundle \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.compose.foundation.Image \nimport androidx.compose.foundation.layout.* \nimport androidx.compose.material.MaterialTheme \nimport androidx.compose.material.Surface \nimport androidx.compose.runtime.Composable \nimport androidx.compose.ui.Alignment \nimport androidx.compose.ui.layout.ContentScale \nimport androidx.compose.ui.platform.setContent \nimport androidx.compose.ui.res.imageResource \nimport androidx.compose.ui.tooling.preview.Preview \nimport androidx.compose.ui.Modifier \nimport androidx.compose.ui.unit.Dp import com.example.edittext.ui.EditTextTheme class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContent { \nEditTextTheme { \n// A surface container using the \n// 'background' color from the theme \nSurface( \n// to add background color for our screen. \ncolor = MaterialTheme.colors.background, \n) { \n// at below line we are calling \n// our function for image view. \nImg(); \n} \n} \n} \n} \n} @Composable\nfun Img() { Column( \n// we are using column to align our \n// imageview to center of the screen. \nmodifier = Modifier.fillMaxWidth().fillMaxHeight(), // below line is used for specifying \n// vertical arrangement. \nverticalArrangement = Arrangement.Center, // below line is used for specifying \n// horizontal arrangement. \nhorizontalAlignment = Alignment.CenterHorizontally, \n) { \n// below line is used for creating a variable \n// for our image resource file. \nval img = imageResource(id = R.drawable.gfgimage) // below line is used for creating a modifier for our image \n// which includes image width and image height \nval modifier = Modifier.preferredHeight(height = Dp(200F)).preferredWidth(width = Dp(200F)) \n// below is the widget for image. \nImage( \n// first parameter of our Image widget \n// is our image path which we have created \n// above and name it as img. \nimg, // below line is used to give \n// alignment to our image view. \nalignment = Alignment.Center, // below line is used to scale our image \n// we are using center crop for it. \ncontentScale = ContentScale.Crop, // below line is used to add modifier \n// to our image. we are adding modifier \n// which we have created above and name \n// it as modifier. \nmodifier = modifier \n) } \n} // @Preview function is use to see preview \n// for our composable function in preview section. \n@Preview\n@Composable\nfun DefaultPreview() { \nMaterialTheme { \n// we are passing our composable \n// function to display its preview. \nImg() \n} \n}Output:"}, {"text": "\nDifference Between Proguard and R8 in Android\n\nProguard and R8 both are similar tools that are used for reducing the size of our APK and increase the performance of our APK by shrinking the unused resources. In this article, we will take a look at:What is Proguard?\nWhat is R8?\nDifference between Proguard and R8.What is Proguard?\nProguard is a java tool in Android that helps to do the following things such as:It removes the unused classes and methods from your app which helps to reduce the size of your APK.\nIt makes your application difficult to reverse engineer by obfuscating the code.\nIt reduces the size of your application.How to enable Proguard in your Application?\nTo enable proguard in your application Navigate to the Gradle Scripts > build.gradle(:app) and then you will get to see a method called buildTypes.buildTypes {\n release {\n minifyEnabled true\n proguardFiles getDefaultProguardFile(\u2018proguard-android-optimize.txt\u2019), \u2018proguard-rules.pro\u2019\n }\n}In this block of code, we have to change minifyEnabled to true to activate our Proguard. This code of Proguard is written under the release block so it will only work on the release build of your APK. It will activate the proguard which will take it from the file named as\u2018proguard-android.txt\u2019. What is R8?\nR8 is another tool that will convert your java byte code into an optimized format of dex code. It will check the whole application and will remove the unused classes and methods. It helps us to reduce the size of our APK and to make our app more secure. R8 uses similar proguard rules to modify its default behavior.\nHow to enable R8 in your Application?\nR8 is already present in your application you just have to enable it. To enable it just Navigate to the Gradle Scripts > build.gradle(:app) and then you will get to see a method called buildTypes.buildTypes {\n release {\n minifyEnabled true\n }\n}In this block of code, we have to change minifyEnabled to true to activate R8. This code for R8 is written under the release block which is only working on the release build of your APK.\nDifference Between Proguard and R8.R8 has more Kotlin support than that of Proguard.\nR8 is having a faster processing time than Proguard which reduces build time.\nR8 gives better output results than Proguard.\nR8 reduces the app size by 10 % whereas Proguard reduces app size by 8.5 %.\nThe android app having a Gradle plugin above 3.4.0 or above then the project uses R8 by default with Proguard rules only.ProguardIn Proguard java compiler converts Apps code into JAVA bytecode and proguard will converts this bytecode into the optimized java bytecode. This java bytecode is then optimized by dex into Optimized Dalvik bytecode. The conversion process of apps code to optimized Dalvik bytecode is a four steps process. \nR8In R8 java compiler converts Apps code in JAVA bytecode and then R8 will directly convert JAVA bytecode into Optimized Dalvik bytecode. The conversion process of apps code to Optimized Dalvik bytecode is a three steps process that is faster in comparison with proguard.\nDifference TableProguardR8Proguard is having lesser speed in comparison with R8 which affects the build time.\nR8 is having a faster processing time which helps developers in reducing build time.The output quality by using proguard is not superior.\nThe output quality using R8 is superior.Proguard reduces app size by 8.5 %.\nR8 reduces app size by 10 %.The conversion process of converting apps code to Optimized Dalvik bytecode is as follows :\nApps Code > Java bytecode > Optimized java bytecode > Optimized Dalvik bytecode.The conversion process of converting apps code to Optimized Dalvik bytecode is as follows :\nApps code > Java bytecode > Optimized Dalvik bytecode.Proguard is only supported for the gradle plugin which is below 3.4.0\nR8 is only supported for the gradle plugin of 3.4.0 and above.Peephole Optimizations in Proguard is around 520.\nPeephole Optimizations in R8 is around 6.No of the steps in converting of Apps code to Optimized Dalvik code is 4.\nNo of the steps in converting Apps code to Optimized Dalvik bytecode is 3.Proguard is not having Kotlin specific optimizations.\nR8 is having Kotlin specific optimizations.Proguard does not propagate constant arguments.\nR8 propagate constant arguments.Conclusion\nWhile R8 is faster than proguard as there are fewer number steps. It reduces the size of the app in an optimized manner with a default compile-time optimizer.\n"}, {"text": "\nTextView widget in Android using Java with Examples\n\nWidget refers to the elements of the UI (User Interface) that help the user interact with the Android App. TextView is one of many such widgets which can be used to improve the UI of the app. TextView refers to the widget which displays some text on the screen based on the layout, size, colour, etc set for that particular TextView. It optionally allows us to modify or edit itself as well. \nClass Syntax:\npublic class TextView extends View implements ViewTreeObserver.OnPreDrawListenerClass Hierarchy:\njava.lang.Object \u21b3 android.view.View \u21b3 android.widget.TextViewSyntax:\n . . android:SomeAttribute1 = \"Value of attribute1\" android:SomeAttribute2 = \"Value of attribute2\" . . android:SomeAttributeN = \"Value of attributeN\" . . Here the layout can be any layout like Relative, Linear, etc (Refer this article to learn more about layouts). And the attributes can be many among the table given below in this article. \nExample:\n XML Attributes of TextView in AndroidAttributesDescriptionandroid:textSets text of the Textviewandroid:idGives a unique ID to the Textview android:cursorVisibleUse this attribute to make cursor visible or invisible. Default value is visible.android:drawableBottomSets images or other graphic assets to below of the Textview.android:drawableEndSets images or other graphic assets to end of Textview.android:drawableLeftSets images or other graphic assets to left of Textview.android:drawablePaddingSets padding to the drawable(images or other graphic assets) in the Textview.android:autoLinkThis attribute is used to automatically detect url or emails and show it as clickable link.android:autoTextAutomatically correct spelling errors in text of the Textview.android:capitalizeIt automatically capitalize whatever the user types in the Textview.android:drawableRightSets drawables to right of text in the Textview.android:drawableStartSets drawables to start of text in the Textview.android:drawableTopSets drawables to top of text in the Textview.android:ellipsizeUse this attribute when you want text to be ellipsized if it is longer than the Textview width.android:emsSets width of the Textview in ems.android:gravityWe can align text of the Textview vertically or horizontally or both.android:heightUse to set height of the Textview.android:hintUse to show hint when there is no text.android:inputTypeUse to set input type of the Textview. It can be Number, Password, Phone etc.android:linesUse to set height of the Textview by number of lines.android:maxHeightSets maximum height of the Textview.android:minHeightSets minimum height of the Textview.android:maxLengthSets maximum character length of the Textview.android:maxLinesSets maximum lines Textview can have.android:minLinesSets minimum lines Textview can have.android:maxWidthSets maximum width Textview can have.android:minWidthSets minimum lines Textview can have.android:textAllCapsShow all texts of the Textview in capital letters.android:textColorSets color of the text.android:textSizeSets font size of the text.android:textStyleSets style of the text. For example, bold, italic, bolditalic.android:typefaceSets typeface or font of the text. For example, normal, sans, serif etcandroid:widthSets width of the TextView.How to include a TextView in an Android App:Step 1: First of all, create a new Android app, or take an existing app to edit it. In both the case, there must be an XML layout activity file and a Java class file linked to this activity. \nStep 2: Open the Activity file and include a TextView in this file. The code for the TextView will be: \n Step 3: Now in the Java file, link this layout file with the below code:\n@Overrideprotected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);}where activity_main is the name of the layout file to be attached.\nStep 4: In the Java file, we will try to change the Text displayed on the TextView upon touching along with a Toast message. \nStep 5: The complete code of the layout file and the Java file is given below.\nBelow is the implementation of the above approach: \nMainActivity.javapackage com.project.textview;import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.Toast;public class MainActivity extends AppCompatActivity { // Creating the instance of the TextView created\n private TextView textView; @Override\n protected void onCreate(Bundle savedInstanceState)\n {\n super.onCreate(savedInstanceState); // Linking the activity file to this Java file\n setContentView(R.layout.activity_main); // Get the TextView with the id\n // mentioned in the layout file\n textView = (TextView)findViewById(R.id.textview); // Try to change the text of the Textview upon touch\n // and also display a Toast message\n textView.setOnClickListener(new View.OnClickListener() { @Override\n public void onClick(View v)\n { // Changing text\n textView.setText(\"GeeksforGeeks\"); // Displaying Toast message\n Toast\n .makeText(MainActivity.this,\n \"Welcome to GeeksforGeeks\",\n Toast.LENGTH_SHORT)\n .show();\n }\n });\n }\n}activity_main.xml Output:"}, {"text": "\nHow to Save ArrayList to SharedPreferences in Android?\n\nSharedPreferences in Android is local storage that is used to store strings, integers, and variables in phone storage so that we can manage the state of the app. We have seen storing simple variables in shared prefs with key and value pair. In this article, we will see How we can store ArrayList to shared preferences in our Android app. \nWhat we are going to build in this article?\nWe will be building a simple application in which we will be displaying course names with its description in a simple RecyclerView and we will be storing all this data in our shared preferences. So when we close our app and reopens our app all the data will be saved in shared preferences and the state of our recycler view is maintained. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210124105228/Screenrecorder-2021-01-24-10-25-32-939.mp4\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Adding dependency for gson in build.gradle\nNavigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.implementation \u2018com.google.code.gson:gson:2.8.5\u2019After adding this dependency sync your project.\nStep 3: Creating a modal class for storing our data\nNavigate to the app > java > your app\u2019s package name > Right-click on it > New > Java class and name your class as CourseModal and add the below code to it.Java public class CourseModal { // variables for our course \n// name and description. \nprivate String courseName; \nprivate String courseDescription; // creating constructor for our variables. \npublic CourseModal(String courseName, String courseDescription) { \nthis.courseName = courseName; \nthis.courseDescription = courseDescription; \n} // creating getter and setter methods. \npublic String getCourseName() { \nreturn courseName; \n} public void setCourseName(String courseName) { \nthis.courseName = courseName; \n} public String getCourseDescription() { \nreturn courseDescription; \n} public void setCourseDescription(String courseDescription) { \nthis.courseDescription = courseDescription; \n} \n}Step 4: Creating a layout file for our item of RecyclerView\nNavigate to the app > res > layout > Right-click on it > New > layout resource file and name your layout as course_rv_item and add the below code to it.XML \n \n \n Step 5: Creating an adapter class for setting data to items of our RecyclerView\nNavigate to the app > java > your app\u2019s package name > Right-click on it > New > Java class and name it as CourseAdapter and add the below code to it.Java import android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; import androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class CourseAdapter extends RecyclerView.Adapter { // creating a variable for array list and context. \nprivate ArrayList courseModalArrayList; \nprivate Context context; // creating a constructor for our variables. \npublic CourseAdapter(ArrayList courseModalArrayList, Context context) { \nthis.courseModalArrayList = courseModalArrayList; \nthis.context = context; \n} @NonNull\n@Override\npublic CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \n// below line is to inflate our layout. \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false); \nreturn new ViewHolder(view); \n} @Override\npublic void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) { \n// setting data to our views of recycler view. \nCourseModal modal = courseModalArrayList.get(position); \nholder.courseNameTV.setText(modal.getCourseName()); \nholder.courseDescTV.setText(modal.getCourseDescription()); \n} @Override\npublic int getItemCount() { \n// returning the size of array list. \nreturn courseModalArrayList.size(); \n} public class ViewHolder extends RecyclerView.ViewHolder { // creating variables for our views. \nprivate TextView courseNameTV, courseDescTV; public ViewHolder(@NonNull View itemView) { \nsuper(itemView); // initializing our views with their ids. \ncourseNameTV = itemView.findViewById(R.id.idTVCourseName); \ncourseDescTV = itemView.findViewById(R.id.idTVCourseDescription); \n} \n} \n}Step 6: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n \n \n \n \n \n Step 7: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.content.SharedPreferences; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.EditText; \nimport android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; import com.google.gson.Gson; \nimport com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; \nimport java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating variables for our ui components. \nprivate EditText courseNameEdt, courseDescEdt; \nprivate Button addBtn, saveBtn; \nprivate RecyclerView courseRV; // variable for our adapter class and array list \nprivate CourseAdapter adapter; \nprivate ArrayList courseModalArrayList; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // initializing our variables. \ncourseNameEdt = findViewById(R.id.idEdtCourseName); \ncourseDescEdt = findViewById(R.id.idEdtCourseDescription); \naddBtn = findViewById(R.id.idBtnAdd); \nsaveBtn = findViewById(R.id.idBtnSave); \ncourseRV = findViewById(R.id.idRVCourses); // calling method to load data \n// from shared prefs. \nloadData(); // calling method to build \n// recycler view. \nbuildRecyclerView(); // on click listener for adding data to array list. \naddBtn.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// below line is use to add data to array list. \ncourseModalArrayList.add(new CourseModal(courseNameEdt.getText().toString(), courseDescEdt.getText().toString())); \n// notifying adapter when new data added. \nadapter.notifyItemInserted(courseModalArrayList.size()); \n} \n}); \n// on click listener for saving data in shared preferences. \nsaveBtn.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// calling method to save data in shared prefs. \nsaveData(); \n} \n}); \n} private void buildRecyclerView() { \n// initializing our adapter class. \nadapter = new CourseAdapter(courseModalArrayList, MainActivity.this); // adding layout manager to our recycler view. \nLinearLayoutManager manager = new LinearLayoutManager(this); \ncourseRV.setHasFixedSize(true); // setting layout manager to our recycler view. \ncourseRV.setLayoutManager(manager); // setting adapter to our recycler view. \ncourseRV.setAdapter(adapter); \n} private void loadData() { \n// method to load arraylist from shared prefs \n// initializing our shared prefs with name as \n// shared preferences. \nSharedPreferences sharedPreferences = getSharedPreferences(\"shared preferences\", MODE_PRIVATE); // creating a variable for gson. \nGson gson = new Gson(); // below line is to get to string present from our \n// shared prefs if not present setting it as null. \nString json = sharedPreferences.getString(\"courses\", null); // below line is to get the type of our array list. \nType type = new TypeToken>() {}.getType(); // in below line we are getting data from gson \n// and saving it to our array list \ncourseModalArrayList = gson.fromJson(json, type); // checking below if the array list is empty or not \nif (courseModalArrayList == null) { \n// if the array list is empty \n// creating a new array list. \ncourseModalArrayList = new ArrayList<>(); \n} \n} private void saveData() { \n// method for saving the data in array list. \n// creating a variable for storing data in \n// shared preferences. \nSharedPreferences sharedPreferences = getSharedPreferences(\"shared preferences\", MODE_PRIVATE); // creating a variable for editor to \n// store data in shared preferences. \nSharedPreferences.Editor editor = sharedPreferences.edit(); // creating a new variable for gson. \nGson gson = new Gson(); // getting data from gson and storing it in a string. \nString json = gson.toJson(courseModalArrayList); // below line is to save data in shared \n// prefs in the form of string. \neditor.putString(\"courses\", json); // below line is to apply changes \n// and save data in shared prefs. \neditor.apply(); // after saving data we are displaying a toast message. \nToast.makeText(this, \"Saved Array List to Shared preferences. \", Toast.LENGTH_SHORT).show(); \n} \n}Now run your app and see the output of the app.\nOutput:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210124105228/Screenrecorder-2021-01-24-10-25-32-939.mp4"}, {"text": "\nMemory Leaks in Android\n\nA memory leak is basically a failure of releasing unused objects from the memory. As a developer one does not need to think about memory allocation, memory deallocation, and garbage collection. All of these are the automatic process that the garbage collector does by itself, but the situation becomes difficult for the garbage collector when the user is referencing the object, which is in not use anymore, but since that object is being referenced by another object, garbage collector feels that the unused object is being used by another object and due to this garbage collector does not free-up the memory of that object, due to which available heap memory get decreases leading to memory shortage and memory leak. The unfreed object is basically called as leaks.\nMemory leaks are the common causes of application crashes in android apps. Every developer must know how to avoid memory leaks and what are the circumstances which can lead to memory leaks in android applications. When the RAM resources are not released when they are no longer needed and if this is done several times, the part of the memory that the operating system has assigned to that particular application may exceed the upper limit and the system can terminate the application causing the application to crash. Holding the references of the object and resources that are no longer needed is the main cause of the memory leaks in android applications. As it is known that the memory for the particular object is allocated within the heap and the object point to certain resources using some object reference. But when the work is completed, the object references should be freed. But when it is not done, the heap space increases continuously and the rest of the application has to run on whatever heap space that is left, and ultimately there are high chances that it can lead to memory leaks in the application. Thus it can be said that memory leaks are a term used when our app goes short of the memory because some object which is not used but still there are being pointed out by the references and continually occupying the heap space, which ultimately leads to a shortage of space for the other components of the application and thus eventually causing the app to crash.Note: One needs to remember that whenever there is a shortage of space in the heap and the system needs to allocate space for some new objects, the garbage collector is being called in the frequent intervals, causing to slow down of the application or sometime the application may crash.Causes of Memory Leaks and Their Solutions\n1. Using Static Views\nOne should not use static views while developing the application, as static views are never destroyed.\n2. Using Static Context\nOne should never use the Context as static, because that context will be available through the life of the application, and will not be restricted to the particular activity.public class MainActivity extends AppCompatActivity {\n // this should not be done\n private static Button button;\n}3. Using Code Abstraction Frequently\nDevelopers often take the advantage of the abstraction property because it provides the code maintenance and flexibility in code, but using abstraction might cost a bit to the developer, as while using abstraction one needs to write more code, more code means more time to execute the space and more RAM. So whenever one can avoid the abstraction in the code, it is code as it can lead to fewer memory leaks.\n4. Unregistered Listeners\nWhen the developer uses any kind of listener in his application code, then the developer should not forget to unregister the listener.\n5. Unregistered Receivers\nMany times the developer needs to register the local broadcast receiver in an activity. However, if the developer does not unregisters the broadcast receiver there is a strong chance that our app can lead to the memory leak problem as the receiver will hold a strong reference to the activity. So even if the activity is of no use, it will prevent the garbage collector to collect the activity for garbage collection, which will ultimately cause the memory leak.Kotlin // sample kotlin program for broadcast receiver \nimport android.app.Activity \nimport android.content.BroadcastReceiver \nimport android.content.Context \nimport android.content.Intent \nimport android.content.IntentFilter \nimport android.os.Bundle \nimport com.example.myapplication.R class LocalBroadcastReceiverActivity : Activity() { private var localBroadcastReceiver: BroadcastReceiver? = nulloverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} private fun registerBroadCastReceiver() { \nlocalBroadcastReceiver = object : BroadcastReceiver() { \noverride fun onReceive(context: Context, intent: Intent) { \n// Write your code here \n} \n} \nregisterReceiver(localBroadcastReceiver, IntentFilter(\"android.net.conn.CONNECTIVITY_CHANGE\")) \n} override fun onStart() { \nsuper.onStart() \n// registering the broadcast receiver \nregisterBroadCastReceiver() \n} override fun onStop() { \nsuper.onStop() // Broadcast receiver holds the implicit reference of Activity. \n// Therefore even if activity is destroy, \n// garbage collector will not be able to remove its instance. \nif (localBroadcastReceiver != null) { \nunregisterReceiver(localBroadcastReceiver) \n} \n} \n}6. Inner class Reference\nAn inner class is often used by the android developers within their code. However, the nonstatic class will hold the implicit reference of the parent class which can cause the memory leak problem. So there can be two solutions that can be proposed to solve this problem:One can make the inner class static\nIf one wants to pass the reference of the non-static inner class, then it can be passed using weak reference.Tools to Detect Memory Leak\nAs it is known that when something cannot be seen, it is very difficult to fix it, same is the case with the memory leak, it cannot be seen, so it is very difficult to fix. But there are some tools that help us to detect the memory leaks in the android application and helps us to fix it. Let\u2019s see some of the most popular tools:\n1. Leak Canary\nLeak Canary is a memory detection library in Android. It is developed by a square cup company. This library has a unique ability to decrease down the memory leak and helping developers to get less \u201cMemoryOutOfError\u201d. Leak canary even helps us to notify where the leak is actually happening. To use Leak-Canary, add the following dependency in the build.gradle(app level file).dependencies {\n// debugImplementation because LeakCanary should only run in debug builds.\ndebugImplementation \u2018com.squareup.leakcanary:leakcanary-android:2.4\u2019\n}Once the leak canary is installed it automatically detects and reports memory leaks in 4 steps:Detecting retained objects.\nDumping the heap.\nAnalyzing the heap.\nCategorizing leaks.If one wants to dig deeper and learn how to leak canary report memory leaks can refer to the official documentation of leak canary.\n2. Android Profiler\nIt is basically a tool that helps to keep track of memory usage of every application in android. It replaced Android Monitor in the android version 3.0 and higher. The Android Profiler is compatible with Android 5.0 (API level 21) and higher. Android Profiler detects the performance of the application in the real-time on the parameters like:Battery\nMemory (In MB)\nCPU Usage (In %)\nNetwork Rate(Rate of uploading and receiving)To open the android profiler within the Android project in android studio, perform the following steps: Choose View > Tool Windows > Profiler > Select deployment target and choose the device. The performance of the app will be listed as shown as in the image below:To know more about how the android profiler works, refer to the official documentation of the android profiler."}, {"text": "\nHow to create customized Buttons in Android with different shapes and colors\n\nA Button is a user interface that are used to perform some action when clicked or tapped. \nDefault Shape of Button\nIn this article, we will try to change the shape and color of Button to various designs, like:Oval Button\nRectangular Button\nCylindrical ButtonApproach:\nBelow are the various steps to created customized Buttons:\nStep 1: Start a new Android Studio project\nPlease refer to this article to see in detail about how to create a new Android Studio project.\nStep 2: Add the Button\nSince we only need to customize Buttons, we will just add Buttons in our layout. We don\u2019t need any other widget. This can be done either by writing the code in XML or using the Design Tab. Here, we will do so by adding its XML code.\nNow since we need to customize the Button as per 3 shapes (as shown above), we will add 3 buttons and add the customization of each separately, lets say the buttons be \u2013 oval, rectangle and cylindrical.activity_main.xml \n \n \n \n Initially, all three buttons have default values and will look as per the default look shown above.\nStep 3: Customizing the button\nIn order to customize the button, as shown above, we will be needing few attributes of Button in particular:shape: This defines the shape of the widget that is being used. For example: oval, rectangle, etc.\ncolor This attribute takes the Hexadecimal color code as parameter and sets the color as per the code\ncorner::radius: This attribute defines how much curved corners of the button has to be. For example, no curve will lead to rectangle and increasing the curve can result in circle as well.\nstroke: This attribute refers to the thickness of the outline of the button. The more the stroke, the thicker the outline will be.These attributes can be set for a widget with the help of a Drawable resource file.Creating a new drawable resource file:\nWe will be creating a new drawable file which will contain the customizations such as shape, color, and gradient which we want to set on our button. To create a drawable file, click on: app -> res -> drawable(right click) -> New -> Drawable resource file and name it anything you want.Adding code to the resource file:\nNow that we have this drawable resource file, we can customize our button by adding tags like shape, color, stroke, or any other attribute which we want.custom_button.xml \n \n \n \n custom_button2.xml \n \n \n \n \n custom_button3.xml \n \n \n \n \n Adding these customizations to our original button:\nWe can now add these customizations to the default button which we created previously. To do this, we just change the background attribute of our Button to the drawable resource file we just created.android:background=\u201d@drawable/custom_button\u201dThis is how our activity_main.xml file will look now:activity_main.xml \n \n \n \n Step 4: Running the project to see the output\nOutput:"}, {"text": "\nServices in Android with Example\n\nServices in Android are a special component that facilitates an application to run in the background in order to perform long-running operation tasks. The prime aim of a service is to ensure that the application remains active in the background so that the user can operate multiple applications at the same time. A user-interface is not desirable for android services as it is designed to operate long-running processes without any user intervention. A service can run continuously in the background even if the application is closed or the user switches to another application. Further, application components can bind itself to service to carry out inter-process communication(IPC). There is a major difference between android services and threads, one must not be confused between the two. Thread is a feature provided by the Operating system to allow the user to perform operations in the background. While service is an android component that performs a long-running operation about which the user might not be aware of as it does not have UI.\nTypes of Android Services1. Foreground Services:\nServices that notify the user about its ongoing operations are termed as Foreground Services. Users can interact with the service by the notifications provided about the ongoing task. Such as in downloading a file, the user can keep track of the progress in downloading and can also pause and resume the process.\n2. Background Services:\nBackground services do not require any user intervention. These services do not notify the user about ongoing background tasks and users also cannot access them. The process like schedule syncing of data or storing of data fall under this service.\n3. Bound Services:\nThis type of android service allows the components of the application like activity to bound themselves with it. Bound services perform their task as long as any application component is bound to it. More than one component is allowed to bind themselves with a service at a time. In order to bind an application component with a service bindService() method is used.\nThe Life Cycle of Android ServicesIn android, services have 2 possible paths to complete its life cycle namely Started and Bounded.\n1. Started Service (Unbounded Service):By following this path, a service will initiate when an application component calls the startService() method. Once initiated, the service can run continuously in the background even if the component is destroyed which was responsible for the start of the service. Two option are available to stop the execution of service:\nBy calling stopService() method,The service can stop itself by using stopSelf() method.2. Bounded Service:It can be treated as a server in a client-server interface. By following this path, android application components can send requests to the service and can fetch results. A service is termed as bounded when an application component binds itself with a service by calling bindService() method. To stop the execution of this service, all the components must unbind themselves from the service by using unbindService() method.\nTo carry out a downloading task in the background, the startService() method will be called. Whereas to get information regarding the download progress and to pause or resume the process while the application is still in the background, the service must be bounded with a component which can perform these tasks.\nFundamentals of Android ServicesA user-defined service can be created through a normal class which is extending the class Service. Further, to carry out the operations of service on applications, there are certain callback methods which are needed to be overridden. The following are some of the important methods of Android Services:\nMethods\nDescription\nonStartCommand()The Android service calls this method when a component(eg: activity)\nrequests to start a service using startService(). Once the service is started,\nit can be stopped explicitly using stopService() or stopSelf() methods.\nonBind()This method is mandatory to implement in android service and is invoked\nwhenever an application component calls the bindService() method in order to\nbind itself with a service. User-interface is also provided to communicate\nwith the service effectively by returning an IBinder object.\nIf the binding of service is not required then the method must return null.\nonUnbind()The Android system invokes this method when all the clients\nget disconnected from a particular service interface.\nonRebind()Once all clients are disconnected from the particular interface of service and\nthere is a need to connect the service with new clients, the system calls this method.\nonCreate()Whenever a service is created either using onStartCommand() or onBind(),\nthe android system calls this method. This method is necessary to perform\na one-time-set-up.\nonDestroy()When a service is no longer in use, the system invokes this method\njust before the service destroys as a final clean up call. Services must\nimplement this method in order to clean up resources like registered listeners,\nthreads, receivers, etc.\nExample of Android ServicesPlaying music in the background is a very common example of services in android. From the time when a user starts the service, music play continuously in the background even if the user switches to another application. The user has to stop the service explicitly in order to pause the music. Below is the complete step-by-step implementation of this android service using a few callback methods.\nNote: Following steps are performed on Android Studio version 4.0\nStep 1: Create a new project\nClick on File, then New => New Project.Choose Empty Views ActivitySelect language as Java/KotlinSelect the minimum SDK as per your need.Step 2: Modify strings.xml file\nAll the strings which are used in the activity are listed in this file.XML\n Services_In_Android \n Services In Android \n Start the Service \n Stop the Service \n Step 3: Working with the activity_main.xml file\nOpen the activity_main.xml file and add 2 Buttons in it which will start and stop the service. Below is the code for designing a proper activity layout.XML\n \n Step 4: Creating the custom service class\nA custom service class will be created in the same directory where the MainActivity class resides and this class will extend the Service class. The callback methods are used to initiate and destroy the services. To play music, the MediaPlayer object is used. Below is the code to carry out this task.Javaimport android.app.Service;\nimport android.content.Intent;\nimport android.media.MediaPlayer;\nimport android.os.IBinder;\nimport android.provider.Settings;\nimport androidx.annotation.Nullable;public class NewService extends Service { // declaring object of MediaPlayer\n private MediaPlayer player; @Override // execution of service will start\n // on calling this method\n public int onStartCommand(Intent intent, int flags, int startId) { // creating a media player which\n // will play the audio of Default\n // ringtone in android device\n player = MediaPlayer.create( this, Settings.System.DEFAULT_RINGTONE_URI ); // providing the boolean\n // value as true to play\n // the audio on loop\n player.setLooping( true ); // starting the process\n player.start(); // returns the status\n // of the program\n return START_STICKY;\n } @Override // execution of the service will\n // stop on calling this method\n public void onDestroy() {\n super.onDestroy(); // stopping the process\n player.stop();\n } @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n}Kotlinimport android.app.Service\nimport android.content.Intent\nimport android.media.MediaPlayer\nimport android.os.IBinder\nimport android.provider.Settingsclass NewService : Service() { // declaring object of MediaPlayer\n private lateinit var player:MediaPlayer // execution of service will start\n // on calling this method\n override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { // creating a media player which\n // will play the audio of Default\n // ringtone in android device\n player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI) // providing the boolean\n // value as true to play\n // the audio on loop\n player.setLooping(true) // starting the process\n player.start() // returns the status\n // of the program\n return START_STICKY\n } // execution of the service will\n // stop on calling this method\n override fun onDestroy() {\n super.onDestroy() // stopping the process\n player.stop()\n } override fun onBind(intent: Intent): IBinder? {\n return null\n }\n}Step 5: Working with the MainActivity file\nNow, the button objects will be declared and the process to be performed on clicking these buttons will be defined in the MainActivity class. Below is the code to implement this step.Javaimport androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener { // declaring objects of Button class\n private Button start, stop; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate( savedInstanceState );\n setContentView( R.layout.activity_main ); // assigning ID of startButton\n // to the object start\n start = (Button) findViewById( R.id.startButton ); // assigning ID of stopButton\n // to the object stop\n stop = (Button) findViewById( R.id.stopButton ); // declaring listeners for the\n // buttons to make them respond\n // correctly according to the process\n start.setOnClickListener( this );\n stop.setOnClickListener( this );\n } public void onClick(View view) { // process to be performed\n // if start button is clicked\n if(view == start){ // starting the service\n startService(new Intent( this, NewService.class ) );\n } // process to be performed\n // if stop button is clicked\n else if (view == stop){ // stopping the service\n stopService(new Intent( this, NewService.class ) ); }\n }\n}Kotlinimport android.content.Intent\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity(), View.OnClickListener { // declaring objects of Button class\n private var start: Button? = null\n private var stop: Button? = null override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) // assigning ID of startButton\n // to the object start\n start = findViewById(R.id.startButton) as Button // assigning ID of stopButton\n // to the object stop\n stop = findViewById(R.id.stopButton) as Button // declaring listeners for the\n // buttons to make them respond\n // correctly according to the process\n start!!.setOnClickListener(this)\n stop!!.setOnClickListener(this)\n } override fun onClick(view: View) { // process to be performed\n // if start button is clicked\n if (view === start) { // starting the service\n startService(Intent(this, NewService::class.java))\n } // process to be performed\n // if stop button is clicked\n else if (view === stop) { // stopping the service\n stopService(Intent(this, NewService::class.java))\n }\n }\n}Step 6: Modify the AndroidManifest.xml file\nTo implement the services successfully on any android device, it is necessary to mention the created service in the AndroidManifest.xml file. It is not possible for a service to perform its task if it is not mentioned in this file. The service name is mentioned inside the application tag.XML\n \n \n \n \n \n \n \n \n \n \n \n \n Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200912115416/Recording-of-android-service-tutorial.mp4\n"}, {"text": "\nProtractorView in Android\n\nIn this article, ProtractorView is added to android. ProtractorView is a semicircular Seekbar view for selecting an angle from 0\u00b0 to 180. Seek bar is a type of progress bar. Change the cursor from 0\u00b0 to 180 for selecting an angle. Below is the image of ProtractorView.Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Add the Required Dependencies\nNavigate to the Gradle Scripts > build.gradle(Module:app) and Add the Below Dependency in the Dependencies section.\nimplementation 'com.github.GoodieBag:ProtractorView:v1.2'\nAdd the Support Library in your settings.gradle File. This library Jitpack is a novel package repository. It is made for JVM so that any library which is present in Github and Bitbucket can be directly used in the application.\ndependencyResolutionManagement {\n repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n repositories {\n google()\n mavenCentral()\n \n // add the following\n maven { url \"https://jitpack.io\" }\n }\n}\nAfter adding this Dependency, Sync the Project and now we will move towards its implementation.\nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n Step 4: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. In this file, add interval, color, and setOnProtractorViewChangeListener to our ProtractorView. Whenever progress is changed setOnProtractorViewChangeListener is get invoked automatically. Here the changed angle value is shown in TextView.Java import androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\nimport com.goodiebag.protractorview.ProtractorView;public class MainActivity extends AppCompatActivity {TextView textView;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);ProtractorView protractorView = (ProtractorView) findViewById(R.id.protractorview);textView = findViewById(R.id.textView);\nprotractorView.setTickIntervals(15);protractorView.setArcColor(getColor(R.color.colorAccent));\nprotractorView.setProgressColor(getColor(R.color.myColor));protractorView.setOnProtractorViewChangeListener(new ProtractorView.OnProtractorViewChangeListener() {\n@Override\npublic void onProgressChanged(ProtractorView pv, int progress, boolean b) {\ntextView.setText(\"\" + progress);\n}@Override\npublic void onStartTrackingTouch(ProtractorView pv) {}@Override\npublic void onStopTrackingTouch(ProtractorView pv) {}\n});\n}\n}Kotlin import android.os.Build\nimport android.os.Bundle\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nimport com.goodiebag.protractorview.ProtractorViewclass MainActivity : AppCompatActivity() {private lateinit var textView: TextViewoverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)val protractorView = findViewById(R.id.protractorview)textView = findViewById(R.id.textView)\nprotractorView.setTickIntervals(15)if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\nprotractorView.setArcColor(getColor(R.color.colorAccent))\nprotractorView.setProgressColor(getColor(R.color.myColor))\n}protractorView.setOnProtractorViewChangeListener(object : OnProtractorViewChangeListener() {\nfun onProgressChanged(pv: ProtractorView?, progress: Int, b: Boolean) {\ntextView.text = \"\" + progress\n}fun onStartTrackingTouch(pv: ProtractorView?) {}fun onStopTrackingTouch(pv: ProtractorView?) {}\n})\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20200715022730/Record_2020-07-15-02-25-21_cc6551a6f21889984886581ad2f4e9ef1.mp4"}, {"text": "\nDifference Between AndroidX and Android Support Libraries\n\nSupport library packages in Android are a set of code libraries whose prime purpose is to provide backward-compatibility to the code and Android API framework. In the real world, there is a strong possibility that an application that is developed on the latest Android version is used on an older version of Android OS. Thus, including the support libraries in the project files is the best practice to follow while developing android applications. Further, these libraries are also needed for the features which are provided only through library API.\nAndroid Support Libraries(com.android.support)\nThese library packages are provided by Google to provide backward compatibility to android applications. The name of these packages ends with the minimum version of Android API supported by the libraries. For example, package name support-v4 and the support-v7 indicate that the minimum supported Android API version is 4 and 7 respectively. However, the continuous advancement in library function and modules leads to the minimum supported Android API level version changed to level 14(Android 4.0) along with the release of support library version 26.0.0 in July 2017.\nAndroidX Package Libraries(androidx.*)\nIntroduced along with the release of Android Jetpack in 2018, AndroidX is a brand new way of organizing the support libraries. The older support libraries were somewhat confusing for the developers as one cannot say that which all classes are included in a particular library just by looking at its name. To address this issue, Google launched AndroidX(stands for Android E X tension) libraries with the release of Android 9.0 (API level 28). Any library name which starts from androidx. is automatically becomes part of the Jetpack. It includes the existing android support library along with the latest Jetpack components. Moreover, developers need not bother about the version of libraries because Jetpack knows what code to use.\nDifference TableAndroid Support LibrariesAndroidX Package LibrariesSyntax of writing dependency: com.android.support:recyclerview-v7\nSyntax of writing dependency: androidx.recyclerview:recyclerviewWhile using support libraries in the project, it is mandatory to keep the same version for all the support libraries.\nDevelopers are free to use a different version of dependency for different android components.Dependencies that are required to add in order to use an android component in the application include various other things that are of no use.\nDevelopers are allowed to add only those dependencies which they are going to use in the application.The package of support library is bundled with the Android operating system. For eg: android.content.Intent\nUnbundled libraries are moved to androidx.* namespace and are packed with application\u2019s APK. For eg: androidx.fragment.app.FragmentThe package name contains the minimum supported API level.\nThe package has no dependency on the API level.All dependencies are required to update before using because all the support libraries need to have the exact same version specification.\nAndroidX libraries can be updated individually. Thus, developers can update only those libraries which are needed in the project.The support of com.android.support libraries have been stopped by Google.\nIt is the recommended library package by Google to use in the project.Note:\nWith the release of Android API level 28 i.e, Android 9.0, Google has stopped the support for com.android.support libraries and advised the developers to use AndroidX libraries which are a part of Jetpack for all new projects. To know what is the new mapping of support libraries in AndroidX, click here.\nGoogle also provide the feature to migrate an existing project in order to use the AndroidX libraries. Visit this link to read the official Google documentation."}, {"text": "\nAndroid | res/values folder\n\nThe res/values folder is used to store the values for the resources that are used in many Android projects including features of color, styles, dimensions, etc. In this article, we will learn about the res/values folder.\nBelow explained are a few basic files, contained in the res/values folder: \ncolors.xmldimens.xmlstrings.xmlstyles.xml1. colors.xmlThe colors.xml is an XML file that is used to store the colors for the resources. An Android project contains 3 essential colors namely: \ncolorPrimarycolorPrimaryDarkcolorAccentThese colors are used in some predefined resources of the Android studio as well. These colors need to be set opaque otherwise it could result in some exceptions to arise. \nBelow mentioned is the implementation of the colors.xml resource: colors.xml \n \n #1294c8 \n #1294c8 \n #FF4081 #555555 #FFFFFF \n #51d8c7 \n Note: It is also possible to define different user based colours for different types of resources.\n2. dimens.xmlThe dimens.xml is used for defining the dimensions for different widgets to be included in the Android project. It is a good coding practice to use dimens.xml to define a dimension rather than just writing the dimension in the resource, due to the fact that if ever any need arises to change the dimension, instead of making a change to all, only the dimens.xml can be changed once and the change is reflected in all. \nBelow mentioned is the implementation of dimens.xml resource:dimens.xml \n \n 16dp \n 16dp \n 8dp \n 176dp \n 16dp \n \nIt is also possible to apply user-defined dimensions. \nNote: Always remember the difference in using dp or sp. Generally use sp for font size and dp for others.\n3. strings.xmlOne of the most important as well as widely used values file is the strings.xml due to its applicability in the Android project. Basic function of the strings.xml is to define the strings in one file so that it is easy to use same string in different positions in the android project plus it makes the project looks less messy. We can also define an array in this file as well. \nBelow mentioned is the implementation of strings.xml resource: strings.xml \n Workshop app Open navigation drawer \n Close navigation drawer \n Settings \n Hello blank fragment \n Date: \n Timings: \n Android studio gives a warning in layout xml if a string is used in that file, thus it is a good practice to store all hardcoded strings in strings.xml file.\n4. styles.xmlAnother important file in the values folder is the styles.xml where all the themes of the Android project are defined. The base theme is given by default having the option to customize or make changes to the customized theme as well. Every theme has a parent attribute which defines the base of the theme. There are a lot of options to choose from depending on the need of the Android project. \nBelow mentioned is the implementation of styles.xml resource: styles.xml \n \n \n \n If any feature used in the files in values folder does not match with the minimum SDK version of the user, then android studio gives the option to define a separate file with the same name but for different API level. For eg., styles and styles(v21)[for API levels of 21 and above]."}, {"text": "\nUI Components of Android Jetpack\n\nAndroid Jetpack is a set of software components, libraries, tools, and guidance to help in developing robust Android applications. Launched by Google in 2018, Jetpack comprises existing android support libraries, android architecture components with an addition of the Android KTX library as a single modular entity. Nowadays, nearly 99% of the apps present on the Google Play Store uses Android Jetpack libraries. The UI area includes widgets, animations, palettes, etc to improve the user experience. It also provides up-to-date emoji fonts to be used in the apps. This article explains each and every library of the UI component in detail. Jetpack consist of a wide collection of libraries that are built in a way to work together and make robust mobile applications. Its software components have been divided into 4 categories:Foundation Components\nArchitecture Components\nBehavior Components\nUI ComponentsFurther, the following are the list of all UI components:Animation & Transition\nAuto\nEmoji\nFragment\nLayout\nPalette\nTV\nWearWays to include Android Jetpack libraries in the applicationAdd google repository in the build.gradle file of the application project.allprojects {\nrepositories {\n google()\n jcenter()\n }\n}All Jetpack components are available in the Google Maven repository, include them in the build.gradle fileallprojects {\nrepositories {\n jcenter()\n maven { url \u2018https://maven.google.com\u2019 }\n }\n}UI Components\n1. Animation & Transition\nJetpack offers APIs to set up different kinds of animations available for Android apps. This framework imparts the ability to move widgets as well as switching between screens with animation and transition in an application. To improve the user experience, animations are used to animate the changes occurring in an app and the transition framework gives the power to configure the appearance of that change. Developers can manage the way in which the transition modifies the application appearance while switching from one screen to another. Jetpack Compose is the toolkit used for building native Android UI. It offers a more modular approach for developing the apps by organizing the code in smaller and reusable components. These components are easy to maintain and the code written in it describes the appearance of a UI in a declarative fashion i.e., based upon the available state. Developers use this declarative nature of Jetpack Compose to showcase complex animations in a beautiful and expressive manner. \nA composable named Transition is used to create animations in Android. Its flexible nature allows developers to easily pass the information to the user through animating a component\u2019s property. Following are the elements involved in Transition composable that controls the overall animation of a component:TransitionDefinition: Includes definition of all animations as well as different states of animation required during the transition.\ninitState: Describe the initial stage of the transition. If it is undefined, it takes the value of the first toState available in the transition.\ntoState: Describe the next state of the transition.\nclock: Manage the animation with the change in time. It is an optional parameter.\nonStateChangeFinished: An optional listener that notifies the completion of a state change animation.\nchildren: It is composable that will be animated.Method signature of Transition:\n@Composable\nfun Transition(\n definition: TransitionDefinition,\n toState: T,\n clock: AnimationClockObservable = AnimationClockAmbient.current,\n initState: T = toState,\n onStateChangeFinished: ((T) -> Unit)? = null,\n children: @Composable() (state: TransitionState) -> Unit\n)Android Jetpack provides some predefined animation builders that developers can use directly in their app. The TransitionDefinition includes the code for all these animations.Tween: To animate the geometrical changes of an object like moving, rotating, stretching, etc.\nPhysics: To define spring animations for an object by providing a damping ratio and stiffness.\nKeyframe: To create an animation in which the value of the target object changes over the course of time.\nSnap: To animate the instant switch from one state to another.\nRepeatable: Used to repeat an animation as many times as the developer wants.2. Auto\nNowadays people are dependent upon smartphone apps up to such an extent that they need them even while driving. The reason for using the mobile phone can be an urgent call or to just enjoy music. Google realized this use case and developed Android Auto with a vision to minimize the driver\u2019s interaction with the phone as well as to assure safety plus security on the road. The task is to bring the most practical applications to the user\u2019s smartphone or on the compatible car display. Android Auto offers an extensive list of applications to use conveniently on the vehicle\u2019s display. The following category of applications can be built, test, and distributed on Android Auto: Navigation apps: The Google Maps navigation interface enables a user to set destinations, choose various routes, and view live traffic. It assists the driver through voice-guided driving directions at every turn and also estimates the arrival time of the destination. This application continues to run in the background even if the user switches to another screen. Moreover, users can also set other interest in this app like parking and location of gas stations, restaurants, etc.\nMessaging apps: Messaging or calling someone is likely the most dangerous thing while driving. To take care of this issue, Android Auto provides messaging apps that receive messages/notifications and read them aloud using the text-to-speech feature. Users can also send replies through voice input in the car. To activate the hands-free voice commands in Android Auto, one can press the \u201ctalk\u201d button on the steering wheel or can trigger the device by saying \u201cOk Google\u201d.\nMedia apps: This kind of apps allows users to browse and play any type of audio content in the car. It accepts voice commands to play radio, music, or audiobooks. Note: Android Auto is compatible only with phones running on Android 6.0 (API level 23) or higher.Jetpack libraries offer two options for developing android apps for cars namely Android Auto and Android Automotive OS. Android Auto apps along with an Android phone are capable of providing a driver-optimized app experience. On the other hand, Android Automotive OS is an Android-based infotainment system that is embedded into vehicles. With this, the car becomes a self-supporting Android device that can run applications directly on the car\u2019s screen. Developers prefer one app architecture while building applications to cover both use cases. \n3. Emoji\nIf an application is used to communicate between people, emojis are definitely going to be a part of that app. The Unicode standard is adding new emojis very frequently, thus it becomes important that the user should be able to see the latest Emoji irrespective of the android device version. Google has released a brand new library called EmojiCompat in order to handle emoji characters and to use downloadable font support. This library assures that an app is up to date with the latest emojis irrespective of the device OS version. EmojiCompat identifies an emoji using its CharSequence and replaces them with EmojiSpans(if required) to assure that the sender and receiver will observe the emoji in the exact same way. Users need to update this library dependency regularly to have the latest emojis. If an application is not using the EmojiCompat library, then the user will see an empty box with the cross sign(\u2612) in place of an emoji. The backward compatibility of this library is up to Android 4.4(API level 19). For the Android OS version lower than that, the emoji will be displayed exactly like a regular TextView.Adding the EmojiCompat support library into the Project:Add the below-mentioned implementation in the app-level build.gradle file. dependencies {\n \u2026..\n \u2026..\n implementation \u201candroidx.emoji:emoji:28.0.0\u201d\n }For using Emoji Widgets in AppCompat, add the AppCompat support library to the dependencies sectiondependencies {\n \u2026..\n \u2026..\n implementation \u201candroidx.emoji:emoji-appcompat:$version\u201d\n }Emoji Views / Widgets:WidgetClassEmojiTextView\nandroid.support.text.emoji.widget.EmojiTextViewEmojiEditText\nandroid.support.text.emoji.widget.EmojiEditTextEmojiButton\nandroid.support.text.emoji.widget.EmojiButtonEmojiAppCompatTextView\nandroid.support.text.emoji.widget.EmojiAppCompatTextViewEmojiAppCompatEditText\nandroid.support.text.emoji.widget.EmojiAppCompatEditTextEmojiAppCompatButton\nandroid.support.text.emoji.widget.EmojiAppCompatButton4. Fragment\nThe Fragment support class of Android has shifted into this segment of Jetpack. Fragments allow separating the UI into discrete pieces that brings modularity and reusability into the UI of an activity. A part of the user interface is defined by a fragment which is then embedded into an activity. There is no existence of fragments without an activity. With the release of Android Jetpack, Google provided some major improvements and advanced features in using the fragments. Navigation, BottomNavigationView, and ViewPager2 library of the Jetpack are designed to work with fragments in a much more effective way. Moreover, the proper integration of the fragment class with the lifecycle class of the jetpack architecture component is also guaranteed. Following is the list of newly added features and improvements by Google for Android developers:\na. Sharing and communicating among fragments:\nIn order to maintain the independent fragments, developers write code in such a way that does not allow fragments to communicate directly with other fragments or with their host activity. The Jetpack fragment library provides two options to establish the communication namely Fragment Result API and shared ViewModel. The Fragment Rest API is suitable for one-time results with data that could be accommodated in a bundle. Further, if there is a requirement to share persistent data along with any custom APIs, ViewModel is preferred. It is also capable of storing and managing UI data. Developers can choose between the two approaches according to the requirement of the app.\nb. Constructor can hold the Layout resource ID:\nThe AndroidX AppCompat 1.1.0 and Fragment 1.1.0 enable the constructor to take the layout ID as a parameter. With this, a considerable decrease in the number of method overrides is observed in fragments. Now, the inflater can be called manually to inflate the view of a fragment, without overriding the onCreateView() method. This makes the classes more readable.class MyFragmentActivity: FragmentActivity(R.layout.my_fragment_activity)\nclass MyFragment : Fragment(R.layout.my_fragment)c. FragmentManager and Navigation library:\nAll crucial task of a fragment like adding, removing, replacing as well as sending them back to the stack is carried out by the FragmentManager class. To handle all these navigation-related tasks, Jetpack recommends using the Navigation library. The framework of this library provides some best practices for developers so that they can work effectively with fragments, fragment manager, and the back stack. Every android application that contains fragments in its UI, have to use FragmentManager at some level. However, developers might not interact with the FragmentManager directly while using the Jetpack Navigation library.\nd. FragmentFactory:\nAndroid developers had always raised the issue with Fragments that there is no scope of using a constructor with arguments. For instance, developers cannot annotate the fragment constructor with Inject and specify the arguments while using Dagger2 for dependency injection. The AndroidX library introduced along with Jetpack offers FragmentFactory class that is capable of handling this and similar issues related to fragment creation. The structure of this API is straightforward and generalized which facilitates developers to create the fragment instance in their own customized way. In order to override the default way of instantiating the Fragment, one has to register the FragmentFactory in the FragmentManager of the application.class MyFragmentFactory : FragmentFactory() {\noverride fun instantiate(classLoader: ClassLoader, className: String): Fragment {\n // loadFragmentClass() method is called to acquire the Class object\n val fragmentClass = loadFragmentClass(classLoader, className)\n \n // use className or fragmentClass as an argument to define the \n // preferred manner of instantiating the Fragment object\n return super.instantiate(classLoader, className)\n}\n}e. Testing fragments:\nAndroidX Test has been launched by Google to make testing a necessary part of Jetpack. The existing libraries along with some new APIs and full Kotlin support of the AndroidX Test provides a way to write suitable and concise tests. FragmentScenario class of the AndroidX library construct the environment for performing tests on fragments. It consists of two major methods for launching fragments in a test, the first one is launchInContainer() that is used for testing the user interface of a fragment. Another method is the launch() that is used for testing without the fragment\u2019s user interface. In some cases, fragments have some dependencies. To generate test versions of these dependencies, one has to provide a custom FragmentFactory to the launchInContainer() or launch() methods. Developers can choose one of the methods and can use Espresso UI tests to check out the information regarding the UI elements of the fragment. For using FragmentScenario class, one needs to define the fragment testing artifact in the app-level build.gradle file.dependencies {\n def fragment_version = \u201c1.2.5\u201d\n debugImplementation \u201candroidx.fragment:fragment-testing:$fragment_version\u201d\n} f. FragmentContainerView:\nAndroidX Fragment 1.2.0 brings FragmentContainerView that extends FrameLayout and provides customized layout design for the fragments in android apps. It is used as a parent to the fragment so that it can coordinate with fragment behavior and introduce flexibility in the tasks like Fragment Transactions. It also supports the attributes and addresses the issues of window insets dispatching. Moreover, this container resolves some animation issues related to the z-ordering of fragments like exiting fragments no longer appear on the top of the view.\n5. Layout\nUser interface structure like the activity of an application is defined by Layout. It defines the View and ViewGroup objects. View and ViewGroup can be created in two ways: by declaring UI elements in XML or by writing code i.e., programmatically. This portion of Jetpack covers some of the most common layouts like LinearLayout, RelativeLayout, and the brand new ConstraintLayout. Moreover, the official Jetpack Layout documentation provides some guidance to create a list of items using RecyclerView and the card layout using CardView. A View is visible to the user. EditView, TextView, and Button are examples of View. On the other hand, a ViewGroup is a container object that defines layout structure for View(s) and thus it is invisible. Examples of ViewGroup are LinearLayout, RelativeLayout, and ConstraintLayout.\n6. Palette\nProviding the right color combination plays a major role in uplifting the user experience. Thus it is an important aspect during the app development process. Developers often build applications in which UI elements change their color according to the time(day and night). This type of practice gives the user a good kind of feeling and assure an immersive experience during app usage. To carry out these tasks, Android Jetpack provides a new Palette support library. It is capable of extracting a small set of colors from an image. The extracted color style the UI controls of the app and update the icons based on the background image\u2019s color. The Material Design of android apps is the reason behind the popularity of dynamic use of color. The extracted color or palette contains vibrant and muted tones of the image. It also includes foreground text colors to ensure maximum readability. \nTo include Palette API in a project, update the app-level build.gradle file in the following manner:dependencies {\n \u2026..\n \u2026..\n implementation \u2018androidx.palette:palette:1.0.0\u2019 \n}The palette gives the choice to developers to select the number of colors they want to be generated from a certain image source. The default value of numberOfColors in the resulting palette is set as 16. However, the count can go up to 24-32. The time taken in generating the complete palette is directly proportional to the color count. Once the palette is generated, a swatch(a kind of method) is used to access those colors. Each color profile has an associated swatch that returns the color in that palette. Following are the color profiles generated by the palette API:ProfileSwatchLight Vibrant\nPalette.getLightVibrantSwatch()Vibrant\nPalette.getVibrantSwatch()Dark Vibrant\nPalette.getDarkVibrantSwatch()Light Muted\nPalette.getLightMutedSwatch()Muted\nPalette.getMutedSwatch()Dark Muted\nPalette.getDarkMutedSwatch()7. TV\nJetpack offers several key components to assist developers in building apps for Android Smart TVs. The structure of the Android TV application is the same as the mobile/tablet apps, however, there are some obvious differences. The hardware and controllers of a TV are very much different than mobile devices. Further, the navigation system is to be handled through a d-pad on a TV remove(up, down, left, and right arrow buttons). To address these concerns, Jetpack offers Leanback library. This library also resolves the issue of searching as well as recommending content to the user on Android TV.\nThe dependency of the leanback library can be added in the app build.gradle file:dependencies {\n def leanback_version = \u201c1.0.0\u201d\n implementation \u201candroidx.leanback:leanback:$leanback_version\u201d\n}8. Wear OS\nAndroid version for wearable devices is called Wear OS. Android Jetpack includes the Wear UI library that enables developers to create apps that can play and control media from a watch. A standalone watch app or watch face can also be created using the UI component of the library. Jetpack assures that the user interface remains optimized and compatible across all apps. Wear OS also supports mobile device features like notifications and \u2018actions on Google\u2019. Developers can develop three kinds of systems under the Wear OS:Wear apps: Applications that will run on smartwatches or gears. It supports device features like sensors and the GPU.\nWatch faces: It is specially made for custom drawings, colors, animations, and contextual information.\nComplication data providers: Provides custom data such as text, images, etc. to watch faces.Wear UI Library can be used by adding the following dependency in the Wear module\u2019s build.gradle file:dependencies {\n \u2026..\n \u2026..\n compile \u2018androidx.wear:wear:1.0.0\u2019\n}"}, {"text": "\nWave Animation in Android\n\nWave Animation is one of the most commonly used features in Android app. You can see this animation in most of the shopping apps, music player apps, and many more. Using this Wave Animation makes the User Experience attractive. In this article, we are going to see how to implement Wave Animation in Android. A sample GIF is given below to get an idea about what we are going to do in this article.Applications of Wave AnimationUse for giving decorative animated effect in an Android app.\nWave Animation is used in most of the apps on the splash screen.\nYou can see this Wave animation in most of the Music Applications.Attributes of Wave AnimationAttributesDescriptionapp:mwhWaveHeight\nUse to give height to the curves of the Wave.app:mwhStartColor\nUse to give starting color of the wave animation.app:mwhCloseColor\nUse to give closing color of the wave animation.app:mwhGradientAngle\nUse for giving angles to the curves.app:mwhRunning\nUse for giving Animation.app:mwhVelocity\nUse for displaying Velocity.app:mwhProgress\nUse for displaying the progress.app:mwhWaves\nUse for displaying multiple waves.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.\nStep 2: Add dependency of Wave Animation library in build.gradle file\nThen Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.implementation \u2018com.scwang.wave:MultiWaveHeader:1.0.0\u2019now click on Sync now it will sync your all files in build.gradle().\nStep 3: Create a new Wave Animation in your activity_main.xml file\nNavigate to the app > res > layout to open the activity_main.xml file. Below is the code for the activity_main.xml file.XML \n \n \n Now click on the run option it will take some time to build Gradle. After that, you will get output on your device as given below.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210117112617/Screenrecorder-2021-01-17-11-02-26-476.mp4"}, {"text": "\nPreferences DataStore in Android\n\nPreference Data Store is used to store data permanently in android. Earlier we had to Shared Preferences for the same but since it is deprecated we are using Data Store now. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.https://media.geeksforgeeks.org/wp-content/uploads/20210122121933/prefs_data_store_gfg2.mp4\nStep by Step Implementation\nStep 1: Create a new project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language\nStep 2: Add dependency inside build.gradle(app)\nAdd the Data Store, Lifecycle, and Coroutines dependency inside the build.gradle(app) and click on the sync now button. // Preferences DataStore\n implementation \u201candroidx.datastore:datastore-preferences:1.0.0-alpha01\u201d\n // Lifecycle components\n implementation \u201candroidx.lifecycle:lifecycle-livedata-ktx:2.2.0\u201d\n implementation \u201candroidx.lifecycle:lifecycle-extensions:2.2.0\u201d\n implementation \u201candroidx.lifecycle:lifecycle-common-java8:2.2.0\u201d\n implementation \u201candroidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0\u201d\n // Kotlin coroutines components\n implementation \u201corg.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.10\u201d\n api \u201corg.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1\u201d\n api \u201corg.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1\u201dStep 3: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. This is for the basic layout used in the app.XML \n Step 4: Working with the UserManager.kt class\nCreate a new kotlin class and name it UserManager, this class holds the code for saving and retrieving data from the preference Data Store. Comments are added inside the code to understand the code in more detail.Kotlin import android.content.Context \nimport androidx.datastore.preferences.createDataStore \nimport androidx.datastore.preferences.edit \nimport androidx.datastore.preferences.preferencesKey \nimport kotlinx.coroutines.flow.Flow \nimport kotlinx.coroutines.flow.map class UserManager(context: Context) { // Create the dataStore and give it a name same as shared preferences \nprivate val dataStore = context.createDataStore(name = \"user_prefs\") // Create some keys we will use them to store and retrieve the data \ncompanion object { \nval USER_AGE_KEY = preferencesKey(\"USER_AGE\") \nval USER_NAME_KEY = preferencesKey(\"USER_NAME\") \n} // Store user data \n// refer to the data store and using edit \n// we can store values using the keys \nsuspend fun storeUser(age: Int, name: String) { \ndataStore.edit { \nit[USER_AGE_KEY] = age \nit[USER_NAME_KEY] = name // here it refers to the preferences we are editing } \n} // Create an age flow to retrieve age from the preferences \n// flow comes from the kotlin coroutine \nval userAgeFlow: Flow = dataStore.data.map { \nit[USER_AGE_KEY] ?: 0\n} // Create a name flow to retrieve name from the preferences \nval userNameFlow: Flow = dataStore.data.map { \nit[USER_NAME_KEY] ?: \"\"\n} \n}Step 5: Working with the MainActivity.kt file\nGo to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.os.Bundle \nimport android.widget.Button \nimport android.widget.EditText \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.lifecycle.asLiveData \nimport androidx.lifecycle.observe \nimport kotlinx.coroutines.GlobalScope \nimport kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { lateinit var etName: EditText \nlateinit var etAge: EditText \nlateinit var tvName: TextView \nlateinit var tvAge: TextView \nlateinit var saveButton: Button lateinit var userManager: UserManager \nvar age = 0\nvar name = \"\"override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) etName = findViewById(R.id.et_name) \netAge = findViewById(R.id.et_age) \ntvName = findViewById(R.id.tv_name) \ntvAge = findViewById(R.id.tv_age) \nsaveButton = findViewById(R.id.btn_save) // Get reference to our userManager class \nuserManager = UserManager(this) // this function saves the data to \n// preference data store on click of \n// save Button \nbuttonSave() // this function retrieves the saved data \n// as soon as they are stored and even \n// after app is closed and started again \nobserveData() \n} private fun buttonSave() { \n// Gets the user input and saves it \nsaveButton.setOnClickListener { \nname = etName.text.toString() \nage = etAge.text.toString().toInt() // Stores the values \n// Since the storeUser function of UserManager \n// class is a suspend function \n// So this has to be done in a coroutine scope \nGlobalScope.launch { \nuserManager.storeUser(age, name) \n} \n} \n} private fun observeData() { \n// Updates age \n// every time user age changes it will be observed by userAgeFlow \n// here it refers to the value returned from the userAgeFlow function \n// of UserManager class \nthis.userManager.userAgeFlow.asLiveData().observe(this) { \nage = it \ntvAge.text = it.toString() \n} // Updates name \n// every time user name changes it will be observed by userNameFlow \n// here it refers to the value returned from the usernameFlow function \n// of UserManager class \nuserManager.userNameFlow.asLiveData().observe(this) { \nname = it \ntvName.text = it.toString() \n} \n} \n}Output:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210122121933/prefs_data_store_gfg2.mp4\nGithub repo here."}, {"text": "\nAlert Dialog with MultipleItemSelection in Android\n\nIn the previous article Alert Dialog with SingleItemSelection in Android, we have seen how the alert dialog is built for single item selection. In this article, it\u2019s been discussed how to build an alert dialog with multiple item selection. Multiple Item selection dialogs are used when the user wants to select multiple items at a time. Have a look at the following image to differentiate between Single Item selection and Multiple Item selection alert dialogs.Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n Output UI:Step 3: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.The function that needs to implement the multiple item selection for alert dialog is discussed below.\nSyntax:\nsetMultiChoiceItems(listItems, checkedItems, new DialogInterface.OnMultiChoiceClickListener()\nParameters:listItems: are the items to be displayed on the alert dialog.\ncheckedItems: it is the boolean array that maintains the selected values as true, and unselected values as false.\nDialogInterface.OnMultiChoiceClickListener(): This is a callback when a change in the selection of items takes place.Invoke the following code to implement the things. Comments are added for better understanding.Java import androidx.appcompat.app.AlertDialog; \nimport androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport java.util.Arrays; \nimport java.util.List; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // UI widgets button and \nButton bOpenAlertDialog = findViewById(R.id.openAlertDialogButton); \nfinal TextView tvSelectedItemsPreview = findViewById(R.id.selectedItemPreview); // initialise the list items for the alert dialog \nfinal String[] listItems = new String[]{\"C\", \"C++\", \"JAVA\", \"PYTHON\"}; \nfinal boolean[] checkedItems = new boolean[listItems.length]; // copy the items from the main list to the selected item list for the preview \n// if the item is checked then only the item should be displayed for the user \nfinal List selectedItems = Arrays.asList(listItems); // handle the Open Alert Dialog button \nbOpenAlertDialog.setOnClickListener(v -> { \n// initially set the null for the text preview \ntvSelectedItemsPreview.setText(null); // initialise the alert dialog builder \nAlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // set the title for the alert dialog \nbuilder.setTitle(\"Choose Items\"); // set the icon for the alert dialog \nbuilder.setIcon(R.drawable.image_logo); // now this is the function which sets the alert dialog for multiple item selection ready \nbuilder.setMultiChoiceItems(listItems, checkedItems, (dialog, which, isChecked) -> { \ncheckedItems[which] = isChecked; \nString currentItem = selectedItems.get(which); \n}); // alert dialog shouldn't be cancellable \nbuilder.setCancelable(false); // handle the positive button of the dialog \nbuilder.setPositiveButton(\"Done\", (dialog, which) -> { \nfor (int i = 0; i < checkedItems.length; i++) { \nif (checkedItems[i]) { \ntvSelectedItemsPreview.setText(String.format(\"%s%s, \", tvSelectedItemsPreview.getText(), selectedItems.get(i))); \n} \n} \n}); // handle the negative button of the alert dialog \nbuilder.setNegativeButton(\"CANCEL\", (dialog, which) -> {}); // handle the neutral button of the dialog to clear the selected items boolean checkedItem \nbuilder.setNeutralButton(\"CLEAR ALL\", (dialog, which) -> { \nArrays.fill(checkedItems, false); \n}); // create the builder \nbuilder.create(); // create the alert dialog with the alert dialog builder instance \nAlertDialog alertDialog = builder.create(); \nalertDialog.show(); \n}); \n} \n}Kotlin import android.content.DialogInterface \nimport android.os.Bundle \nimport android.widget.Button \nimport android.widget.TextView \nimport androidx.appcompat.app.AlertDialog \nimport androidx.appcompat.app.AppCompatActivity \nimport java.util.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // UI widgets button and \nval bOpenAlertDialog = findViewById(R.id.openAlertDialogButton) \nval tvSelectedItemsPreview = findViewById(R.id.selectedItemPreview) // initialise the list items for the alert dialog \nval listItems = arrayOf(\"C\", \"C++\", \"JAVA\", \"PYTHON\") \nval checkedItems = BooleanArray(listItems.size) // copy the items from the main list to the selected item list for the preview \n// if the item is checked then only the item should be displayed for the user \nval selectedItems = mutableListOf(*listItems) // handle the Open Alert Dialog button \nbOpenAlertDialog.setOnClickListener { \n// initially set the null for the text preview \ntvSelectedItemsPreview.text = null// initialise the alert dialog builder \nval builder = AlertDialog.Builder(this) // set the title for the alert dialog \nbuilder.setTitle(\"Choose Items\") // set the icon for the alert dialog \nbuilder.setIcon(R.drawable.image_logo) // now this is the function which sets the alert dialog for multiple item selection ready \nbuilder.setMultiChoiceItems(listItems, checkedItems) { dialog, which, isChecked -> \ncheckedItems[which] = isChecked \nval currentItem = selectedItems[which] \n} // alert dialog shouldn't be cancellable \nbuilder.setCancelable(false) // handle the positive button of the dialog \nbuilder.setPositiveButton(\"Done\") { dialog, which -> \nfor (i in checkedItems.indices) { \nif (checkedItems[i]) { \ntvSelectedItemsPreview.text = String.format(\"%s%s, \", tvSelectedItemsPreview.text, selectedItems[i]) \n} \n} \n} // handle the negative button of the alert dialog \nbuilder.setNegativeButton(\"CANCEL\") { dialog, which -> } // handle the neutral button of the dialog to clear the selected items boolean checkedItem \nbuilder.setNeutralButton(\"CLEAR ALL\") { dialog: DialogInterface?, which: Int -> \nArrays.fill(checkedItems, false) \n} // create the builder \nbuilder.create() // create the alert dialog with the alert dialog builder instance \nval alertDialog = builder.create() \nalertDialog.show() \n} \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201204193252/GFG_nexus_5.mp4"}, {"text": "\nLaunch vs Async in Kotlin Coroutines\n\nPrerequisite: Kotlin Coroutines on Android\nThe Kotlin team defines coroutines as \u201clightweight threads\u201d. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin coroutines introduce a new style of concurrency that can be used on Android to simplify async code.The official documentation says that coroutines are lightweight threads. By lightweight, it means that creating coroutines doesn\u2019t allocate new threads. Instead, they use predefined thread pools and smart scheduling for the purpose of which task to execute next and which tasks later.There are mainly two functions in Kotlin to start the coroutines.launch{ }\nasync{ }Launch Function\nThe launch will not block the main thread, but on the other hand, the execution of the rest part of the code will not wait for the launch result since launch is not a suspend call. Following is a Kotlin Program Using Launch:Kotlin // Kotlin Program For better understanding of launch\nfun GFG() \n{\nvar resultOne = \"Android\"\nvar resultTwo = \"Kotlin\"\nLog.i(\"Launch\", \"Before\")\nlaunch(Dispatchers.IO) { resultOne = function1() }\nlaunch(Dispatchers.IO) { resultTwo = function2() }\nLog.i(\"Launch\", \"After\")\nval resultText = resultOne + resultTwo\nLog.i(\"Launch\", resultText)\n}suspend fun function1(): String \n{\ndelay(1000L)\nval message = \"function1\"\nLog.i(\"Launch\", message)\nreturn message\n}suspend fun function2(): String \n{\ndelay(100L)\nval message = \"function2\"\nLog.i(\"Launch\", message)\nreturn message\n}When you will run the code in Android IDE, the log result will be:Kotlin // pseudo kotlin code for demonstration of launch\nGlobalScope.launch(Dispatchers.Main) \n{\n// do on IO thread\nfetchUserAndSaveInDatabase() \n}suspend fun fetchUserAndSaveInDatabase() \n{\n// fetch user from network\n// save user in database\n// and do not return anything\n}As the fetchUserAndSaveInDatabase() does not return anything, we can use the launch to complete that task and then do something on Main Thread.When to Use Launch?Launch can be used at places where users do not want to use the returned result, which is later used in performing some other work. For example, It can be used at places involving tasks like update or changing a color, as in this case returned information would be of no use.Async Function\nAsync is also used to start the coroutines, but it blocks the main thread at the entry point of the await() function in the program. Following is a Kotlin Program Using Async:Kotlin // kotlin program for demonstration of async\nfun GFG \n{\nLog.i(\"Async\", \"Before\")\nval resultOne = Async(Dispatchers.IO) { function1() }\nval resultTwo = Async(Dispatchers.IO) { function2() }\nLog.i(\"Async\", \"After\")\nval resultText = resultOne.await() + resultTwo.await()\nLog.i(\"Async\", resultText)\n}suspend fun function1(): String \n{\ndelay(1000L)\nval message = \"function1\"\nLog.i(\"Async\", message)\nreturn message\n}suspend fun function2(): String \n{\ndelay(100L)\nval message = \"function2\"\nLog.i(\"Async\", message)\nreturn message\n}One important point to note is that Async makes both of the networks call for result1 and result2 in parallel, whereas with launch parallel function calls are not made. When you will run the code in Android IDE, the log result will be:When to Use Async?When making two or more network call in parallel, but you need to wait for the answers before computing the output, ie use async for results from multiple tasks that run in parallel. If you use async and do not wait for the result, it will work exactly the same as launch.Table of DifferencesBelow is the table of differences between Launch and Async:LaunchAsyncThe launch is basically fire and forget.\nAsync is basically performing a task and return a result.launch{} does not return anything.\nasync{ }, which has an await() function returns the result of the coroutine.launch{} cannot be used when you need the parallel execution of network calls.\nUse async only when you need the parallel execution network calls.launch{} will not block your main thread.\nAsync will block the main thread at the entry point of the await() function.Execution of other parts of the code will not wait for the launch result since launch is not a suspend call\nExecution of the other parts of the code will have to wait for the result of the await() function.It is not possible for the launch to work like async in any case or condition.\nIf you use async and do not wait for the result, it will work exactly the same as launch.Launch can be used at places if you don\u2019t need the result from the method called.\nUse async when you need the results from the multiple tasks that run in parallel.Example: It can be used at places involving tasks like update or changing color like fetch User And Save In Database.\nExample: Imagine the condition, when we have to fetch two users\u2019 data from the database by using two parallel network calls and then use them for computing some results based on their data."}, {"text": "\nBasics of Jetpack Compose in Android\n\nJetpack Compose is a modern UI toolkit that is designed to simplify UI development in Android. It consists of a reactive programming model with conciseness and ease of Kotlin programming language. It is fully declarative so that you can describe your UI by calling some series of functions that will transform your data into a UI hierarchy. When the data changes or is updated then the framework automatically recalls these functions and updates the view for you. In this article, we will see some of the basic topics which are helpful before starting with Jetpack Compose.What is Jetpack Compose?\nWhat are its benefits?\nWhat challenges we can solve by using Jetpack Compose?\nSome basic functions of Jetpack compose.What is Jetpack Compose?\nJetpack Compose is a modern UI toolkit recently launched by Google which is used for building native Android UI. It simplifies and accelerates the UI development with less code, Kotlin APIs, and powerful tools.\nWhat are the Benefits of Using Jetpack Compose?Declarative: It is fully declarative so that you can describe your UI components by calling some predefined functions.\nCompatible: It is easily compatible with the existing views present in Android.\nIncrease development speed: Previously developers have to work on the XML file and Kotlin file. But with the help of jetpack compose this becomes easy and developers only have to work on the Kotlin files that\u2019s why it will help developers in increasing development speed.\nConcise and Idiomatic Kotlin: Jetpack Compose built the UI with the benefit that Kotlin brings.\nEasy to maintain: As the codebase of any application is present in a single file. It becomes easy to manage and handle the codebase of the application.\nWritten in Kotlin: The application written using jetpack compose uses 100 % of Kotlin programming language.What Challenges Do We Can Solve using Jetpack Compose?When writing our code we create multiple methods for different purposes. After that we couple this method in our main function according to our requirement. In Android when building any type of view and setting data to that particular view. First of all, we initialize that view with a variable and then add data to that specific view. This process of coupling UI elements with the View Model is called Coupling. When our code is having so many couplings it becomes difficult to maintain this code. So coupling can give you sometimes some Null Reference errors.\nWhile developing apps in Java we generally prefer using View Modal concept in which we find each view from our XML layout file inside our Java class and add data to that specific view according to our requirement. In most apps, we use the UI elements to display dynamically so this may sometimes give you an error of NullReference. In this method, UI elements are declared in XML language whereas the functionality is written in java or Kotlin and we link UI elements with our Java or Kotlin class with the findViewbyId() method.\nIf we will prefer to use the same language for writing our UI components and for adding the functionality it will become easier to maintain our code. By using this method the number of couplings inside our code will also reduce.Some Basic Functions of Jetpack ComposeComposable Function: Composable Function is represented in code by using @Composable annotation to the function name. This function will let you define your app\u2019s UI programmatically by describing its shape and data dependencies rather than focusing on the UI construction process.\nPreview Function: The name of the function itself tells us that the function is used to generate the preview of the composable function. It is used to display a preview of our composable functions within our IDE rather than installing our APK in an emulator or a virtual device. The preview function is annotated by @Preview.\nColumn Function: The column function is used to stack UI elements in a vertical manner. This function will stack all the children directly one after another in a vertical manner with no spacing between them. It is annotated with Column().\nRow Function: The row function is used to stack UI elements in a horizontal manner. This function will stack all the children one after the other in a horizontal manner with no spacing between them. It is annotated with Row().\nBox: A widget that is used to positioned elements one over another. It will position its children relative to its edges. The stack is used to draw the children which will overlap in the order that they are specified. It is annotated with Box().\nSpacer: It is used to give spacing between two views. We can specify the height and width of the box. It is an empty box that is used to give spacing between the views. It is annotated with Spacer().\nVertical Scroll: If the UI components inside the app do not fit the height of the screen then we have to use the scrolling type of view. With the help of a vertical scroller, we can provide a vertically scrolling behavior to our view. The contents inside the vertical scroller will be clipped to the bounds of the vertical scroller. It is annotated with VerticalScroll().\nPadding: The padding function is used to provide extra white space according to the requirement around the specific view. It is simply annotated with Padding().\nLazy List: This composable is equivalent to a recycler view in android\u2019s view system. It is annotated with LazyColumn().."}, {"text": "\nAndroid | Creating a RatingBar\n\nRatingBar is used to allow the users to rate some products. In the below code getRating() function is used to calculate the rating of the products. The getRating() function returns double type value.\nBelow steps are involved to create a RatingBar in Android:Create a new android project.\nAdd RatingBar in your activity_main.xml.\nAdd Button to invoke action.\nUse TextView to display the ratings.To use the rating bar in the app, we will use the in-built RatingBar widget, hence the first step is to import it into the project.\nIn the MainActivity, make the RatingBar object denoted by the variable \u2018rt\u2019 and find its corresponding view in the XML file. This is done by the findViewById() method. After the java object has successfully bind to its view, create the \u2018stars\u2019 layout, which the user will interact with, to set the rating.\nTo get the drawable stars, the method rt.getProcessDrawable() is used. Then to modify the colours of the stars, the method setColorFilter() is used and the argument Color.YELLOW is passed. Finally, the Call method is written to extract the value of the rating that the user has selected, by the method rt.getMethod().Program to create MainActivity: // Below is the code for MainActivity.java \npackage com.example.hp.rating; // importing required libraries \nimport android.graphics.Color; \nimport android.graphics.PorterDuff; \nimport android.graphics.drawable.LayerDrawable; \nimport android.support.v7.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.RatingBar; \nimport android.widget.TextView; public class MainActivity extends AppCompatActivity { \nRatingBar rt; \n@Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); //binding MainActivity.java with activity_main.xml file \nrt = (RatingBar) findViewById(R.id.ratingBar); //finding the specific RatingBar with its unique ID \nLayerDrawable stars=(LayerDrawable)rt.getProgressDrawable(); //Use for changing the color of RatingBar \nstars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP); \n} public void Call(View v) \n{ \n// This function is called when button is clicked. \n// Display ratings, which is required to be converted into string first. \nTextView t = (TextView)findViewById(R.id.textView2); \nt.setText(\"You Rated :\"+String.valueOf(rt.getRating())); \n} \n} Note: For the layout, ConstraintLayout is good to use if you are a beginner because it can adjust the views as per the screens.\nThis XML file defines the view of the application.\nProgram to create layout for MainActivity: \n\nandroid:layout_width=\"match_parent\" \n\nandroid:layout_height=\"match_parent\" tools:context=\"com.example.hp.rating.MainActivity\" \nandroid:background=\"@color/colorPrimary\"> \n Here we don\u2019t need to change the manifest file, no permission is required for the ratingBar. By default, all the created new activities are mentioned in the manifest file.\nBelow is the code for AndroidManifest.xml \n \n \n \n \n \n \n Output:"}, {"text": "\nProgressBar in Kotlin\n\nAndroid ProgressBar is a user interface control that indicates the progress of an operation. For example, downloading a file, uploading a file on the internet we can see the progress bar to estimate the time remaining in operation. There are two modes of ProgressBar:Determinate ProgressBar\nIndeterminate ProgressBarDeterminate ProgressBar\nIn common, we use the Determinate progress mode in ProgressBar because it shows the quantity of progress that has occurred like the (%) percentage of the file downloaded, how much data was uploaded or downloaded on the internet, etc. If we have to use determinate we set the style of the progress bar as below:XML Indeterminate ProgressBar\nHere, we don\u2019t get the idea of the progress of work means how much it has been completed or How long it will take to complete.We can use indeterminate progressBar like below by setting the indeterminate attribute as true.XML Different Attributes of ProgressBar WidgetsXML AttributesDescriptionandroid:id\nUsed to uniquely identify the controlandroid:min\nUsed to set minimum valueandroid:max\nUsed to set the maximum valueandroid:progress\nUsed to set the default progress integer value between 0 and max.android:minHeight\nUsed to set the height of the progress bar.android:minWidth\nUsed to set the width of the progress bar.android:background\nUsed to set the background color for progress barandroid:indeterminate\nUsed to enable indeterminate progress mode.android:padding\nUsed to set the padding for left, right, top, or bottom of the progress bar.Add ProgressBar Widget in activity_main.xml fileXML \n\n \n \n Access the ProgressBar Widget in MainActivity.kt fileKotlin import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.ProgressBar\nimport android.widget.TextView\nimport android.os.Handlerclass MainActivity : AppCompatActivity() {private var progressBar: ProgressBar? = null\nprivate var i = 0\nprivate var txtView: TextView? = null\nprivate val handler = Handler()override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// finding progressbar by its id\nprogressBar = findViewById(R.id.progress_Bar) as ProgressBar// finding textview by its id\ntxtView = findViewById(R.id.text_view)// finding button by its id\nval btn = findViewById(R.id.show_button)// handling click on button \nbtn.setOnClickListener {\n// Before clicking the button the progress bar will invisible\n// so we have to change the visibility of the progress bar to visible\n// setting the progressbar visibility to visible\nprogressBar.visibility = View.VISIBLEi = progressBar.progressThread(Runnable {\n// this loop will run until the value of i becomes 99\nwhile (i < 100) {\ni += 1\n// Update the progress bar and display the current value\nhandler.post(Runnable {\nprogressBar.progress = i \n// setting current progress to the textview\ntxtView!!.text = i.toString() + \"/\" + progressBar.max\n})\ntry {\nThread.sleep(100)\n} catch (e: InterruptedException) {\ne.printStackTrace()\n}\n}// setting the visibility of the progressbar to invisible\n// or you can use View.GONE instead of invisible\n// View.GONE will remove the progressbar \nprogressBar.visibility = View.INVISIBLE}).start()\n}\n}\n}AndroidManifest.xml fileXML \n\n\n\n \n \n \n Output:https://media.geeksforgeeks.org/wp-content/uploads/20210707120803/1625639475757.mp4"}, {"text": "\nHow to Calculate Distance Between two Locations in Android?\n\nWe have seen many apps that use Google Maps. These maps are used to indicate places on Google Maps and also we can use this to calculate the distance between two locations. In this article, we will take a look at calculating the distance between two locations in Android.\nWhat we are going to build in this article?\nWe will be building a simple application in which we will be displaying a simple map and on our app launch, we will show a Toast message with a distance between two locations on our Map. Below is the video in which we will get to see what we are going to build in this article. We are going to calculate the distance between Sydney and Brisbane. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210118181455/Screenrecorder-2021-01-18-18-09-26-558.mp4\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Make sure to select Maps Activity while creating a new Project.\nStep 2: Generating an API key for using Google Maps\nTo generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY.\nStep 3: Adding a dependency to calculate the distance between two locations\nNavigate to the app > Gradle Scripts > build.gradle file and add below dependency in the dependencies section.implementation \u2018com.google.maps.android:android-maps-utils:0.4+\u2019After adding the below dependency now sync your project. After adding this dependency now move towards the MapsActivity.java file for showing a toast message.\nStep 4: Working with the MapsActivity.java file\nGo to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.widget.Toast; import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.GoogleMap; \nimport com.google.android.gms.maps.OnMapReadyCallback; \nimport com.google.android.gms.maps.SupportMapFragment; \nimport com.google.android.gms.maps.model.LatLng; \nimport com.google.maps.android.SphericalUtil; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; // below are the latitude and longitude \n// of 2 different locations. \nLatLng sydney = new LatLng(-34, 151); \nLatLng Brisbane = new LatLng(-27.470125, 153.021072); \nDouble distance; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_maps); \n// Obtain the SupportMapFragment and get notified \n// when the map is ready to be used. \nSupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); \nmapFragment.getMapAsync(this); \n} /** \n* Manipulates the map once available. \n* This callback is triggered when the map is ready to be used. \n* This is where we can add markers or lines, add listeners or move the camera. In this case, \n* we just add a marker near Sydney, Australia. \n* If Google Play services is not installed on the device, the user will be prompted to install \n* it inside the SupportMapFragment. This method will only be triggered once the user has \n* installed Google Play services and returned to the app. \n*/\n@Override\npublic void onMapReady(GoogleMap googleMap) { \nmMap = googleMap; \n// on below line we are calculating the distance between sydney and brisbane \ndistance = SphericalUtil.computeDistanceBetween(sydney, Brisbane); // in below line we are displaying a toast \n// message with distance between two locations. \n// in our distance we are dividing it by 1000 to \n// make in km and formatting it to only 2 decimal places. \nToast.makeText(this, \"Distance between Sydney and Brisbane is \\n \" + String.format(\"%.2f\", distance / 1000) + \"km\", Toast.LENGTH_SHORT).show(); \n} \n}After adding this code. Now run your app and see the output of the app.\nOutput:Note: In the Google Developer Console (https://console.developers.google.com), ensure that the \u201cGoogle Maps Android API v2\u201d is enabled. And also ensure that your API Key exists.https://media.geeksforgeeks.org/wp-content/uploads/20210118181455/Screenrecorder-2021-01-18-18-09-26-558.mp4"}, {"text": "\nWhat Are the Different Types of Bars Available in Android?\n\nAndroid is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android OS was developed by Android Inc. which Google bought in 2005. There are different types of bars available in android. Let\u2019s discuss each bar in this article.\nTypes of Bars Available in Android\nIn Android for the same bar, different names are available. For example, the Action bar is now named Tool Bar, and sometimes it is also named as an app bar. So this creates confusion. We are going to try to overcome this confusion in this article.Status Bar\nAction Bar/Toolbar/App Bar\nSystem Bar/Android Navigation Bar\nProgress Bar\nSeek Bar\nSnackbar\nRatingBar1. Status Bar\nIn an Android phone, the status bar contains the clock, battery icon, and other notification icons as shown in the below image. Most of the time, it is at the top of the screen. This is provided by the system; the app does not directly manipulate the contents of this bar.Note: According to Google design guidelines; the height of the status bar is 24dp.Below is a sample image to show where the status bar is present on an android device.2. Action Bar/Toolbar/App BarAction Bar: The action bar (sometimes referred to as the app bar), if it exists for an activity, will be at the top of the activity\u2019s content area, typically directly underneath the status bar. It is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain menu items that become visible when the user clicks the \u201cmenu\u201d button. In general, an ActionBar composed of the following four components:App Icon: App branding logo or icon will be shown here\nView Control: A dedicated space to display the Application title. Also provides the option to switch between views by adding spinner or tabbed navigation\nAction Buttons: Major actions of the app could be added here\nAction Overflow: All unimportant action will be displayed as a menuToolbar: The toolbar was added in Android Lollipop (API 21) and is the successor of the ActionBar. The toolbar is a ViewGroup that can be put anyplace in the XML layouts. Toolbar\u2019s looks and behavior could be more efficiently customized than the ActionBar. Toolbars are more flexible than ActionBar. One can simply change its color, size, and position. We can also add labels, logos, navigation icons, and other views to it.\nApp Bar: The app bar, (also recognized as the action bar), is one of the most prominent design elements in the app\u2019s activities because it gives a visual structure and interactive elements that are close to users. The most important functions of the app bar are as follows:A dedicated space for providing the app identification and showing the user\u2019s location in the app.\nEntree to major actions in an expected way, like search.\nAssist with navigation and view switching.Below is a sample image to show where the Action Bar/Toolbar/App Bar is present on an android device.Note: There are some differences between these three confusing terms. We are going to discuss this in another article.3. System Bar/Android Navigation Bar\nThe navigation or system bar contains the HOME, BACK, etc. buttons are. This is normally present on the opposite side of the screen of the status bar. Therefore it is usually present at the bottom of the screen. This is given by the system; the app doesn\u2019t directly manage the contents of this bar. It also provides a menu for apps written for Android 2.3 or earlier. Below is a sample image to show where the System Bar/Android Navigation Bar is present on an android device.4. Progress Bar\nAndroid ProgressBar is a UI control that shows the progress of an operation. For example, downloading a file, uploading a file on the internet one can see the progress bar to view the time remaining in operation. There are two modes of progressBar:Determinate ProgressBar: In general, we use the Determinate progress mode in the progress bar because it displays the amount of progress that has happened like the (%) percentage of the file downloaded, how much data uploaded or downloaded on the internet, etc.\nIndeterminate ProgressBar: Here, we don\u2019t get the idea of the progress of work means how much it has been completed or How long it will take to complete.Below is a sample image of how the progress bar looks like.5. Seek Bar\nAndroid seek bar is a revised version of progressBar that has a draggable thumb in which the users can drag the thumb back and forth to set the current progress value. We can use the seek bar in our android device like Brightness control, volume control, etc. It is one of the essential UI elements that provides the option to choose the integer values within the defined range like 1 to 100. By dragging the thumb in SeekBar, we can slide back and forth to choose a value between the minimum and maximum integer value which we defined using the android:min and the android:max attributes. respectively. Below is a sample image of how the Seek Bar looks like.6. Snackbar\nSnackbar provides lightweight feedback about an operation. The message appears at the bottom of the screen on mobile and lower left on larger devices. Having a CoordinatorLayout in the view hierarchy provides Snackbar to facilitate specific features, such as swipe-to-dismiss and automatically moving of widgets. Snackbar is comparable to Toast but the only significant difference is that an action can be added with Snackbar. Below is a sample GIF of how the Snackbar looks like.7. RatingBar\nAndroid RatingBar is a user interface widget that is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allows users to give the rating by clicking on the stars. In RatingBar, we can establish the step size using android:stepSize and it will always return a rating value as a floating-point number such as 1.0, 2.0, 2.5, etc. By using, android:numStars attribute one can define the number of stars in RatingBar. RatingBar is used to get ratings from users or customers about the product, movie or hotel experience, etc. Below is a sample image of how the RatingBar looks like."}, {"text": "\nStaggered GridView in Android with Example\n\nStaggeredGridLayout is a LayoutManager in the android studio similar to GridView, but in StaggeredGridLayout each grid has its own height and width.\nDifference Between GridView and Staggered GridView\nStaggeredGridlayoutThe children are in a staggered grid format.\nIt supports horizontal and vertical layout\nExample: Pinterest, a wallpaper app, a status app, etcGridViewThe children\u2019s in a rectangular grid format\nIt also supports horizontal and vertical layout\nExample: Flipkart, Amazon, wallpaper app, etcExample\nA sample GIF is given below to get an idea about what we are going to do in this article. We are going toimplement this project using both Java and Kotlin Programming Language for Android.Step by Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Adding Dependency to the build.gradle File\nGo to Module build.gradle file and add this dependency and click on Sync Now button.\nimplementation 'androidx.recyclerview:recyclerview:1.1.0'\nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail. Add a RecyclerView as shown below.XML \n \n \n Now we create a new layout resource file (recyclerview_row.xml)\nInside it, we add a simple ImageView and set it android:scaleType=\u201dfitXY\u201d complete code of recyclerview_row.xml is shown belowXML \n \n \n Step 4: Working with the Java/Kotlin Files\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. First, we create a RecyclerViewAdapter class and extend it to RecyclerView.Adapter and implements its methods as shown below. Below is the code for theRecyclerViewAdapter file. Comments are added inside the code to understand the code in more detail.Java import android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.ImageView; \nimport androidx.recyclerview.widget.RecyclerView; \nimport java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter { // ArrayList \nArrayList Image; \nContext context; // constructor \npublic RecyclerViewAdapter(Context context, ArrayList Image) { \nsuper(); \nthis.context = context; \nthis.Image = Image; \n} @Override\npublic ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { \nView v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recyclerview_row, viewGroup, false); \nreturn new ViewHolder(v); \n} @Override\npublic void onBindViewHolder(ViewHolder viewHolder, int i) { \n// setting image resource \nviewHolder.imgview.setImageResource(Image.get(i)); \n} @Override\npublic int getItemCount() { \nreturn Image.size(); \n} public static class ViewHolder extends RecyclerView.ViewHolder { \npublic ImageView imgview; \npublic ViewHolder(View itemView) { \nsuper(itemView); \n// getting ImageView reference \nimgview = (ImageView) itemView.findViewById(R.id.imgView); \n} \n} \n}Kotlin import android.content.Context \nimport android.view.LayoutInflater \nimport android.view.View \nimport android.view.ViewGroup \nimport android.widget.ImageView \nimport androidx.recyclerview.widget.RecyclerView class RecyclerViewAdapter(var context: Context, private var Image: ArrayList) : RecyclerView.Adapter() { \noverride fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder { \nval v: View = LayoutInflater.from(viewGroup.context).inflate(R.layout.recyclerview_row, viewGroup, false) \nreturn ViewHolder(v) \n} override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) { \n// setting image resource \nviewHolder.imgview.setImageResource(Image[i]) \n} override fun getItemCount(): Int { \nreturn Image.size \n} class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { \nvar imgview: ImageView \ninit { \n// getting ImageView reference \nimgview = itemView.findViewById(R.id.imgView) as ImageView \n} \n} \n}Now Open the MainActivity File there within the Class\nFirst of all, create the object of the RecyclerViewAdapter, RecyclerView class, and an ArrayList to store ids of images\n// creating recyclerviewadapter object\nRecyclerViewAdapter recyclerViewAdapter;// creating arrayList\nArrayList ImageList;// creating recycler view object\nRecyclerView recyclerView;\nNow inside the onCreate() method, link those objects with their respective IDs that are given in the activity_main.xml file.\n // adding values to arrayList\n ImageList = new ArrayList<>(Arrays.asList(\n R.drawable.k1, R.drawable.k2, R.drawable.k3,\n R.drawable.k4, R.drawable.k5, R.drawable.k6,\n R.drawable.k7, R.drawable.k8, R.drawable.k9)\n );\n recyclerView = findViewById(R.id.recycleViewStagged);\nNow inside onCreate() method, we create a RecyclerView.LayoutManager (Learn more about StaggeredGridLayoutManager) and set it to RecyclerView\n// setting recyclerView layoutManager\nRecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);\nrecyclerView.setLayoutManager(layoutManager);\nNow we initialize and setAdapter()\nrecyclerViewAdapter = new RecyclerViewAdapter(this, ImageList);\n// setting recycle view adapter\nrecyclerView.setAdapter(recyclerViewAdapter);\nBelow is the complete code for the MainActivity file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.RecyclerView; \nimport androidx.recyclerview.widget.StaggeredGridLayoutManager; \nimport java.util.ArrayList; \nimport java.util.Arrays; public class MainActivity extends AppCompatActivity { // creating recyclerviewadapter object \nRecyclerViewAdapter recyclerViewAdapter; // creating arrayList \nArrayList ImageList; // creating recycler view object \nRecyclerView recyclerView; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // adding values to arrayList \nImageList = new ArrayList<>(Arrays.asList( \nR.drawable.k1, R.drawable.k2, R.drawable.k3, \nR.drawable.k4, R.drawable.k5, R.drawable.k6, \nR.drawable.k7, R.drawable.k8, R.drawable.k9) \n); recyclerView = findViewById(R.id.recycleViewStagged); // setting recyclerView layoutManager \nRecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); \nrecyclerView.setLayoutManager(layoutManager); \nrecyclerViewAdapter = new RecyclerViewAdapter(this, ImageList); // setting recycle view adapter \nrecyclerView.setAdapter(recyclerViewAdapter); \n} \n}Kotlin import android.os.Bundle \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.recyclerview.widget.RecyclerView \nimport androidx.recyclerview.widget.StaggeredGridLayoutManager \nimport java.util.* class MainActivity : AppCompatActivity() { // creating recyclerviewadapter object \nprivate lateinit var recyclerViewAdapter: RecyclerViewAdapter \n// creating arrayList \nprivate lateinit var ImageList: ArrayList \n// creating recycler view object \nprivate lateinit var recyclerView: RecyclerView override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // adding values to arrayList \nImageList = ArrayList(mutableListOf( \nR.drawable.k1, R.drawable.k2, R.drawable.k3, \nR.drawable.k4, R.drawable.k5, R.drawable.k6, \nR.drawable.k7, R.drawable.k8, R.drawable.k9 \n) \n) \nrecyclerView = findViewById(R.id.recycleViewStagged) // setting recyclerView layoutManager \nval layoutManager: RecyclerView.LayoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) \nrecyclerView.layoutManager = layoutManager \nrecyclerViewAdapter = RecyclerViewAdapter(this, ImageList) // setting recycle view adapter \nrecyclerView.adapter = recyclerViewAdapter \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20201115011437/Staggered-Grid-View-Example.mp4"}, {"text": "\nBroadcast Receiver in Android With Example\n\nBroadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events. Broadcast Receivers allow us to register for the system and application events, and when that event happens, then the register receivers get notified. There are mainly two types of Broadcast Receivers:Static Broadcast Receivers: These types of Receivers are declared in the manifest file and works even if the app is closed.\nDynamic Broadcast Receivers: These types of receivers work only if the app is active or minimized.Since from API Level 26, most of the broadcast can only be caught by the dynamic receiver, so we have implemented dynamic receivers in our sample project given below. There are some static fields defined in the Intent class which can be used to broadcast different events. We have taken a change of airplane mode as a broadcast event, but there are many events for which broadcast register can be used. Following are some of the important system-wide generated intents:- IntentDescription Of Eventandroid.intent.action.BATTERY_LOW :\nIndicates low battery condition on the device.android.intent.action.BOOT_COMPLETED\nThis is broadcast once after the system has finished bootingandroid.intent.action.CALL\nTo perform a call to someone specified by the dataandroid.intent.action.DATE_CHANGED\nIndicates that the date has changedandroid.intent.action.REBOOT\nIndicates that the device has been a rebootandroid.net.conn.CONNECTIVITY_CHANGE\nThe mobile network or wifi connection is changed(or reset)android.intent.ACTION_AIRPLANE_MODE_CHANGED\nThis indicates that airplane mode has been switched on or off.The two main things that we have to do in order to use the broadcast receiver in our application are:\nCreating the Broadcast Receiver:class AirplaneModeChangeReceiver:BroadcastReceiver() {\n override fun onReceive(context: Context?, intent: Intent?) {\n // logic of the code needs to be written here\n }\n}Registering a BroadcastReceiver:IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {\n // receiver is the broadcast receiver that we have registered\n // and it is the intent filter that we have created\n registerReceiver(receiver,it)\n }Example\nBelow is the sample project showing how to create the broadcast Receiver and how to register them for a particular event and how to use them in the application.\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.\nStep 2: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for theactivity_main.xml file.XML \n\n Step 3: Working with the MainActivity file\nGo to the MainActivity file and refer to the following code. Below is the code for theMainActivity file. Comments are added inside the code to understand the code in more detail.Kotlin import android.content.Intent\nimport android.content.IntentFilter\nimport android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {// register the receiver in the main activity in order\n// to receive updates of broadcasts events if they occur\nlateinit var receiver: AirplaneModeChangeReceiver\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)receiver = AirplaneModeChangeReceiver()// Intent Filter is useful to determine which apps wants to receive\n// which intents,since here we want to respond to change of\n// airplane mode\nIntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {\n// registering the receiver\n// it parameter which is passed in registerReceiver() function\n// is the intent filter that we have just created\nregisterReceiver(receiver, it)\n}\n}// since AirplaneModeChangeReceiver class holds a instance of Context\n// and that context is actually the activity context in which\n// the receiver has been created\noverride fun onStop() {\nsuper.onStop()\nunregisterReceiver(receiver)\n}\n}Java import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;\nimport android.content.IntentFilter;\nimport android.os.Bundle;public class MainActivity extends AppCompatActivity {AirplaneModeChangeReceiver airplaneModeChangeReceiver = new AirplaneModeChangeReceiver();@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);\n}@Override\nprotected void onStart() {\nsuper.onStart();\nIntentFilter filter = new IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);\nregisterReceiver(airplaneModeChangeReceiver, filter);\n}@Override\nprotected void onStop() {\nsuper.onStop();\nunregisterReceiver(airplaneModeChangeReceiver);\n}\n}Step 4: Create a new class\nGo to app > java > your package name(in which the MainActicity is present) > right-click > New > Kotlin File/Class and name the files as AirplaneModeChangeReceiver. Below is the code for theAirplaneModeChangeReceiver file. Comments are added inside the code to understand the code in more detail.Kotlin import android.content.BroadcastReceiver\nimport android.content.Context\nimport android.content.Intent\nimport android.widget.Toast// AirplaneModeChangeReceiver class extending BroadcastReceiver class\nclass AirplaneModeChangeReceiver : BroadcastReceiver() {// this function will be executed when the user changes his\n// airplane mode\noverride fun onReceive(context: Context?, intent: Intent?) {// intent contains the information about the broadcast\n// in our case broadcast is change of airplane mode// if getBooleanExtra contains null value,it will directly return back\nval isAirplaneModeEnabled = intent?.getBooleanExtra(\"state\", false) ?: return// checking whether airplane mode is enabled or not\nif (isAirplaneModeEnabled) {\n// showing the toast message if airplane mode is enabled\nToast.makeText(context, \"Airplane Mode Enabled\", Toast.LENGTH_LONG).show()\n} else {\n// showing the toast message if airplane mode is disabled\nToast.makeText(context, \"Airplane Mode Disabled\", Toast.LENGTH_LONG).show()\n}\n}\n}Java import android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.provider.Settings;\nimport android.widget.Toast;public class AirplaneModeChangeReceiver extends BroadcastReceiver {@Override\npublic void onReceive(Context context, Intent intent) {if (isAirplaneModeOn(context.getApplicationContext())) {\nToast.makeText(context, \"AirPlane mode is on\", Toast.LENGTH_SHORT).show();\n} else {\nToast.makeText(context, \"AirPlane mode is off\", Toast.LENGTH_SHORT).show();\n}\n}private static boolean isAirplaneModeOn(Context context) {\nreturn Settings.System.getInt(context.getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 0) != 0;\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20201031202726/Broadcast_Receiver_Output.mp4"}, {"text": "\nTheming Floating Action Buttons in Android with Example\n\nPrerequisite:Floating Action Button (FAB) in Android with Example\nExtended Floating Action Button in Android with ExampleAndroid application developers want to seek the attention of the users by customizing and theming the android application widgets and keep more traffic of customers only by the design of the application. In this article, it has been discussed theming one of the most important UI elements that is Floating Action Buttons (extended as well as normal). Below are some sample images of Theming Floating Action Buttons.Steps for Creating Theming Floating Action Buttons\nStep 1: Create an Empty Activity Android Studio ProjectCreate an Empty Activity Android studio project. You may refer to this How to Create/Start a New Project in Android Studio.Step 2: Add a dependency to the app level Gradle file.Here we are using the Floating action button which is designed and developed by Google Material Design Team.\nAdd the dependency in the build.gradle(app) file as:implementation \u2018com.google.android.material:material:1.3.0-alpha02\u2019Make sure that add the dependency to the app level Gradle file. After adding the dependency you need to click on the \u201cSync Now\u201d button which appears at the top right corner of the Android Studio IDE.\nWhen you click on the Sync Now button make sure that you are connected to the network so that it can download the required files.\nRefer the below image if you can\u2019t get the steps mentioned above or if you can\u2019t locate the app level Gradle file:Step 3: Change the base application theme in the styles.xml fileThe theme needs to be changed as the ExtendedFloating action button is the child class of the Google Material Design Buttons. So it needs the MaterialComponent theme to be applied to the Base theme of the application. Otherwise, the app will crash immediately as soon as we launch the application.\nYou may refer to this article: Material Design Buttons in Android with Example, as the ExtendedMaterial design button, is child class of the Material design buttons. The article says, the advantages of having Material design buttons, and why the theme needs to be changed.\nGo to app -> src -> main -> res -> values -> styles.xml and change the base application theme. The MaterialComponents contains various action bar theme styles, one may invoke any of the MaterialComponents action bar theme styles, except AppCompat styles. Below is the code for the styles.xml file.XML \n\n \n If you are unable to get the things in the step mentioned above you may refer to this image.Step 4: Import some of the vector icons in the drawable folderIn this case, simple add vector, add alarm, vector, add person vector icons are imported for demonstration purpose.\nTo import any vector in the project one needs to right-click on the drawable folder -> New -> Vector Asset.\nA new pop window will be opened and choose any vector you want by clicking on the Clip Art button.\nYou can refer to the following image to how to open the vector asset selector.You may refer the following image to how to locate the Clip Art button and choose the vectors.Step 5: Working with the activity_main.xml fileNow in the activity_main.xml file, add a normal Floating Action Button and an Extended Floating Action Button. Make sure to use the ConstraintLayout.\nInvoke both of the Floating Action Button, so that it can be seen how these both buttons changes after manipulating the styles.xml file.\nInvoke the following code to add both Floating Action Buttons:XML \n \n\n \n\n After invoking the code, the following UI is produced:To change the background color of both the FABs invoke the following attribute while defining these two of the FABs in the activity_main.xml file (add backgroundTint manually because all FAB will be applied with the default SmallComponent theme).android:backgroundTint=\u201d@color/colorAccent\u201dNow let\u2019s discuss how to change the theme of both of the Floating action Buttons in a single code:To change the theme of both FABs we need to override the default theme that is SmallComponent theme in the styles.xml file:XML \n Output: Run on Emulator (after making changes to styles.xml):One can observe that in the above code the \u201ccornerFamily\u201d attribute is invoked as \u201ccut\u201d value. So let\u2019s overriding the corner family in from the SmallComponent theme.\nThe \u201ccornerFamily\u201d attribute contains the two values that are \u201ccut\u201d and \u201crounded\u201d. For more information on these continue reading the article on how to change the corner size with the help of \u201ccornerSize\u201d attribute.\nSo this method of changing the theme affects all of the FAB types whether it may be an Extended or Normal FAB.\nEven it changes the shape and theme of the Google Material Design Buttons if there are implemented in the application. Please refer to this: Material Design Buttons in Android with Example.Now let\u2019s discuss how to separately change the theme of both type of FABs:Now in the same styles.xml file, we need to do small changes.\nIn the previous case, we have invoked the item \u201cshapeAppearanceSmallComponent\u201d inside the AppTheme style.\nNow we need to add the items \u201cextendedFloatingActionButtonStyle\u201d for Extended FAB and \u201cfloatingActionButtonStyle\u201d for normal FAB, to differentiate the theming of both.\nRefer to the following code on how it has been done:XML \n \n\n\n\n\n\n \n \n\n\n \n\n\n\n\n\n \n After making changes to the styles.xml file the following UI is produced:Now different themes are established separately for the normal FAB and extended FAB.Note: The colors of both FABs are made different in this case, for demonstration purpose only, as this is not recommended the colors of the all FABs must be same for entire application according to material design recommendations.Experiment with the customNormalFAB and customExtendedFABNow onward experiment with the children \u201ccustomNormalFAB\u201d and \u201ccustomExtendedFAB\u201d (and remaining other things are unchanged) to make changes in the shapes of both the FABs.\nAlso experiment with \u201ccornerSizeTopRight\u201d, \u201ccornerSizeTopLeft\u201d, \u201ccornerSizeBottomRight\u201d and \u201ccornerSizeBottomLeft\u201d.\nNow make changes to both children as follows:Example 1:XML \n \nOutput UI will be:Example 2:XML \n \nOutput UI will be:Example 3:XML \n \nOutput UI will be:Example 4:XML \n \nOutput UI will be:Example 5:XML \n \nOutput UI will be:"}, {"text": "\nTabHost in Android with Example\n\nTabHost is a container that holds a set of tabs. Each tab consists of either the activity or the fragments. TabHost consists of two children of which one is FrameLayout (which is used to show the contents of the activity) and another one is TabWidget.(It is used to choose the tab which the user wants to open). Mostly Tabhost is used in the project with the help of the LinearLayout.\nImportant Methods of TabHost\naddTab(TabSpec tabSpec): This method is used to add the new tab onto a tab widget. Whenever a new tab is being specified using TabSpec class, one needs to add that tab in our TabHost.\n// initiate TabHost\nTabHost tabhost = findViewById(R.id.tabhost);\n// setting up the tabhost\ntabhost.setup();\n \n// setting the name of the new tab \nTabHost.TabSpec spec = tabhost.newTabSpec(\"Tab One\");\n \nspec.setContent(R.id.tab1);\nspec.setIndicator(\"Tab One\");\n// adding the tab to tabhost \ntabhost.addTab(spec); \nclearAllTabs(): This method is used to clear all tabs within the tab host. After adding the tab as shown above, if some want to clear the tab from TabHost, then write the below code.\ntabHost.clearAllTabs(); // this method is used to clear all the tabs from tabhost\nsetOnTabChangedListener(OnTabChangeListener): This method is used to register a callback that needs to be invoked when the selected state of any of the items in this list changes. This method is used when one needs to invoke the callback and register it when the state changes of any selected items in the list.\nsetCurrentTab(int index): By default, tab hosts set the first tab position as the default position which will appear when the app is being launched, but we can explicitly change the default position of the tab using these methods. (Position starts from 0)\ntabHost.setCurrentTab(1); // it will set second tab as default selected tab\nExample\nLet\u2019s try to understand TabHost in detail by making a small project. A sample GIF is given below to get an idea about what we are going to do in this project.We are going toimplement this project using both Java and Kotlin Programming languages for Android.Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n Step 3: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.widget.TabHost; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { \n@Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // initiating the tabhost \nTabHost tabhost = findViewById(R.id.tabhost); // setting up the tab host \ntabhost.setup(); // Code for adding Tab 1 to the tabhost \nTabHost.TabSpec spec = tabhost.newTabSpec(\"Tab One\"); \nspec.setContent(R.id.tab1); // setting the name of the tab 1 as \"Tab One\" \nspec.setIndicator(\"Tab One\"); // adding the tab to tabhost \ntabhost.addTab(spec); // Code for adding Tab 2 to the tabhost \nspec = tabhost.newTabSpec(\"Tab Two\"); \nspec.setContent(R.id.tab2); // setting the name of the tab 1 as \"Tab Two\" \nspec.setIndicator(\"Tab Two\"); \ntabhost.addTab(spec); // Code for adding Tab 3 to the tabhost \nspec = tabhost.newTabSpec(\"Tab Three\"); \nspec.setContent(R.id.tab3); \nspec.setIndicator(\"Tab Three\"); \ntabhost.addTab(spec); \n} \n}Kotlin import android.os.Bundle \nimport android.widget.TabHost \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // initiating the tabhost \nval tabhost = findViewById(R.id.tabhost) // setting up the tab host \ntabhost.setup() // Code for adding Tab 1 to the tabhost \nvar spec = tabhost.newTabSpec(\"Tab One\") \nspec.setContent(R.id.tab1) // setting the name of the tab 1 as \"Tab One\" \nspec.setIndicator(\"Tab One\") // adding the tab to tabhost \ntabhost.addTab(spec) // Code for adding Tab 2 to the tabhost \nspec = tabhost.newTabSpec(\"Tab Two\") \nspec.setContent(R.id.tab2) // setting the name of the tab 1 as \"Tab Two\" \nspec.setIndicator(\"Tab Two\") \ntabhost.addTab(spec) // Code for adding Tab 3 to the tabhost \nspec = tabhost.newTabSpec(\"Tab Three\") \nspec.setContent(R.id.tab3) \nspec.setIndicator(\"Tab Three\") \ntabhost.addTab(spec) \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20201019175424/Tab_Host_Android.mp4"}, {"text": "\nContext Menu in Android with Example\n\nIn Android, there are three types of menus available to define a set of options and actions in the Android apps. The lists of menus in Android applications are the following:Android options menu\nAndroid context menu\nAndroid popup menuHere in this article let\u2019s discuss the detail of the Context Menu. In Android, the context menu is like a floating menu and arises when the user has long-pressed or clicked on an item and is beneficial for implementing functions that define the specific content or reference frame effect. The Android context menu is alike to the right-click menu in Windows or Linux. In the Android system, the context menu provides actions that change a specific element or context frame in the user interface and one can provide a context menu for any view. The context menu will not support any object shortcuts and object icons. A sample GIF is given below to get an idea about what we are going to do in this article.Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the XML Files\nOpen res -> Layout -> activity_main.xml and write the following code. In this file add only a TextView to display a simple text.XML \n\n \n Step 3: Working with the MainActivity file\nOpen the app -> Java -> Package -> Mainactivity.java file. In this step, add the code to show the ContextMenu. Whenever the app will start make a long click on a text and display the number of options to select of them for specific purposes. Comments are added inside the code to understand the code in more detail.Java import android.graphics.Color; \nimport android.os.Bundle; \nimport android.view.ContextMenu; \nimport android.view.MenuItem; \nimport android.view.View; \nimport android.widget.RelativeLayout; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { \nTextView textView; \nRelativeLayout relativeLayout; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Link those objects with their respective id's that we have given in .XML file \ntextView = (TextView) findViewById(R.id.textView); \nrelativeLayout = (RelativeLayout) findViewById(R.id.relLayout); // here you have to register a view for context menu you can register any view \n// like listview, image view, textview, button etc \nregisterForContextMenu(textView); } @Override\npublic void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { \nsuper.onCreateContextMenu(menu, v, menuInfo); \n// you can set menu header with title icon etc \nmenu.setHeaderTitle(\"Choose a color\"); \n// add menu items \nmenu.add(0, v.getId(), 0, \"Yellow\"); \nmenu.add(0, v.getId(), 0, \"Gray\"); \nmenu.add(0, v.getId(), 0, \"Cyan\"); \n} // menu item select listener \n@Override\npublic boolean onContextItemSelected(MenuItem item) { \nif (item.getTitle() == \"Yellow\") { \nrelativeLayout.setBackgroundColor(Color.YELLOW); \n} else if (item.getTitle() == \"Gray\") { \nrelativeLayout.setBackgroundColor(Color.GRAY); \n} else if (item.getTitle() == \"Cyan\") { \nrelativeLayout.setBackgroundColor(Color.CYAN); \n} \nreturn true; \n} \n}Kotlin import android.graphics.Color \nimport android.os.Bundle \nimport android.view.ContextMenu \nimport android.view.ContextMenu.ContextMenuInfo \nimport android.view.MenuItem \nimport android.view.View \nimport android.widget.RelativeLayout \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \nlateinit var textView: TextView \nlateinit var relativeLayout: RelativeLayout override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Link those objects with their respective id's that we have given in .XML file \ntextView = findViewById(R.id.textView) \nrelativeLayout = findViewById(R.id.relLayout) // here you have to register a view for context menu you can register any view \n// like listview, image view, textview, button etc \nregisterForContextMenu(textView) \n} override fun onCreateContextMenu(menu: ContextMenu, v: View, menuInfo: ContextMenuInfo) { \nsuper.onCreateContextMenu(menu, v, menuInfo) \n// you can set menu header with title icon etc \nmenu.setHeaderTitle(\"Choose a color\") \n// add menu items \nmenu.add(0, v.id, 0, \"Yellow\") \nmenu.add(0, v.id, 0, \"Gray\") \nmenu.add(0, v.id, 0, \"Cyan\") \n} // menu item select listener \noverride fun onContextItemSelected(item: MenuItem): Boolean { \nif (item.title === \"Yellow\") { \nrelativeLayout.setBackgroundColor(Color.YELLOW) \n} else if (item.title === \"Gray\") { \nrelativeLayout.setBackgroundColor(Color.GRAY) \n} else if (item.title === \"Cyan\") { \nrelativeLayout.setBackgroundColor(Color.CYAN) \n} \nreturn true\n} \n}Output: Run on Emulator\nNow connect the device with a USB cable or in an Emulator and launch the application. The user will see a text. Now long pressing on the text will generate menu options and select one of them to perform specific functionality.https://media.geeksforgeeks.org/wp-content/uploads/20200922011103/context.mp4"}, {"text": "\nImplicit and Explicit Intents in Android with Examples\n\nPre-requisites:Android App Development Fundamentals for Beginners\nGuide to Install and Set up Android Studio\nAndroid | Starting with the first app/android project\nAndroid | Running your first Android appThis article aims to tell about the Implicit and Explicit intents and how to use them in an android app.\nWhat is intent in Android?\nThe intent is a messaging object which passes between components like services, content providers, activities, etc. Normally startActivity() method is used for invoking any activity. Some of the general functions of intent are:Start service\nLaunch Activity\nDisplay web page\nDisplay contact list\nMessage broadcastingMethods and their DescriptionMethods\nDescriptionContext.startActivity()\nThis is to launch a new activity or get an existing activity to be action.Context.startService()\nThis is to start a new service or deliver instructions for an existing service.Context.sendBroadcast()\nThis is to deliver the message to broadcast receivers.Intent Classification:\nThere are two types of intents in androidImplicit Intent\nExplicit IntentImplicit Intent\nUsing implicit Intent, components can\u2019t be specified. An action to be performed is declared by implicit intent. Then android operating system will filter out components that will respond to the action. For Example,In the above example, no component is specified, instead, an action is performed i.e. a webpage is going to be opened. As you type the name of your desired webpage and click on the \u2018CLICK\u2019 button. Your webpage is opened.\nStep by Step Implementation\nCreating an Android App to Open a Webpage Using Implicit Intent\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android. Create an XML file and Java File. Please refer to the pre-requisites to learn more about this step.\nStep 2: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.\nSyntax:\nandroid:id=\"@+id/id_name\"XML \n Step 3: Working with the MainActivity File\nNow, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.\nSyntax:\nComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);Java import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;public class MainActivity extends AppCompatActivity {@Override\nprotected void onCreate(Bundle savedInstanceState) {EditText editText;\nButton button;super.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);button = findViewById(R.id.btn);\neditText = (EditText) findViewById(R.id.editText);button.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View view) {\nString url=editText.getText().toString();\nIntent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));\nstartActivity(intent);\n}\n});\n}\n}Kotlin import android.content.Intent\nimport android.net.Uri\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.EditText\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {lateinit var editText: EditTextoverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)editText = findViewById(R.id.editText)\n}fun search() {\nval url = editText.text.toString()\nval urlIntent = Intent(Intent.ACTION_VIEW, Uri.parse(url))\nstartActivity(urlIntent)\n}\n}Explicit Intent\nUsing explicit intent any other component can be specified. In other words, the targeted component is specified by explicit intent. So only the specified target component will be invoked. For Example:\nExplicit Intent Example\nIn the above example, There are two activities (FirstActivity, and SecondActivity). When you click on the \u2018GO TO OTHER ACTIVITY\u2019 button in the first activity, then you move to the second activity. When you click on the \u2018GO TO HOME ACTIVITY\u2019 button in the second activity, then you move to the first activity. This is getting done through Explicit Intent.\nStep by Step Implementation\nHow to create an Android App to move to the next activity using Explicit Intent(with Example)\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android. Please refer to the pre-requisites to learn more about this step.\nStep 2: Working with the activity_main.xml File\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.\nSyntax:\nandroid:id=\"@+id/id_name\"XML \n \n Step 3: Working with the MainActivity File\nNow, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.\nSyntax:\nComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);\nIntent i = new Intent(getApplicationContext(), );\nstartActivity(i);Java import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;public class MainActivity extends AppCompatActivity {@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);\n}public void newsScreen(View view) {\nIntent i = new Intent(getApplicationContext(), MainActivity2.class);\nstartActivity(i);\n}\n}Kotlin import android.content.Intent\nimport android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)\n}fun newsScreen() {\nval i = Intent(applicationContext, MainActivity2::class.java)\nstartActivity(i)\n}\n}Step 4: Working with the activity_main2.xml File\nNow we have to create a second activity as a destination activity. The steps to create the second activity are File > new > Activity > Empty Activity.Next, go to the activity_main2.xml file, which represents the UI of the project. Below is the code for theactivity_main2.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n Step 5: Working with the MainActivity2 File\nNow, we will create the Backend of the App. For this, Open the MainActivity file and instantiate the component (Button, TextView) created in the XML file using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.\nSyntax:\nComponentType object = (ComponentType) findViewById(R.id.IdOfTheComponent);\nIntent i = new Intent(getApplicationContext(), );\nstartActivity(i);Java import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.view.View;public class MainActivity2 extends AppCompatActivity {@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main2);\n}public void homeScreen(View view) {\nIntent i = new Intent(getApplicationContext(), MainActivity.class);\nstartActivity(i);\n}\n}Kotlin import android.content.Intent\nimport android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity2 : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main2)\n}fun homeScreen() {\nval i = Intent(applicationContext, MainActivity::class.java)\nstartActivity(i)\n}\n}"}, {"text": "\nDifference Between MVC, MVP and MVVM Architecture Pattern in Android\n\nDeveloping an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in the future. MVC (Model \u2014 View \u2014 Controller), MVP (Model \u2014 View \u2014 Presenter), and MVVM (Model \u2014 View \u2014 ViewModel) is the most popular and industry-recognized android architecture pattern among developers.\nThe Model\u2014View\u2014Controller(MVC) Pattern\nThe MVC pattern suggests splitting the code into 3 components. While creating the class/file of the application, the developer must categorize it into one of the following three layers:Model: This component stores the application data. It has no knowledge about the interface. The model is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: It is the UI(User Interface) layer that holds components that are visible on the screen. Moreover, it provides the visualization of the data stored in the Model and offers interaction to the user.\nController: This component establishes the relationship between the View and the Model. It contains the core application logic and gets informed of the user\u2019s response and updates the Model as per the need.The Model\u2014View\u2014Presenter(MVP) Pattern\nMVP pattern overcomes the challenges of MVC and provides an easy way to structure the project codes. The reason why MVP is widely accepted is that it provides modularity, testability, and a more clean and maintainable codebase. It is composed of the following three components:Model: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: UI(User Interface) layer. It provides the visualization of the data and keep a track of the user\u2019s action in order to notify the Presenter.\nPresenter: Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user\u2019s input notification from the View.The Model \u2014 View \u2014 ViewModel (MVVM) Pattern\nMVVM pattern has some similarities with the MVP(Model \u2014 View \u2014 Presenter) design pattern as the Presenter role is played by the ViewModel. However, the drawbacks of the MVP pattern has been solved by MVVM. It suggests separating the data presentation logic(Views or UI) from the core business logic part of the application. The separate code layers of MVVM are:Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.\nView: The purpose of this layer is to inform the ViewModel about the user\u2019s action. This layer observes the ViewModel and does not contain any kind of application logic.\nViewModel: It exposes those data streams which are relevant to the View. Moreover, it servers as a link between the Model and the View.Difference Between MVC, MVP, and MVVM Design PatternMVC(MODEL VIEW CONTROLLER)MVP(MODEL VIEW PRESENTER)MVVM(MODEL VIEW VIEWMODEL)One of the oldest software architecture\nDeveloped as the second iteration of software architecture which is advance from MVC.\nIndustry-recognized architecture pattern for applications.UI(View) and data-access mechanism(Model) are tightly coupled.\nIt resolves the problem of having a dependent View by using Presenter as a communication channel between Model and View.\nThis architecture pattern is more event-driven as it uses data binding and thus makes easy separation of core business logic from the View.Controller and View exist with the one-to-many relationship. One Controller can select a different View based upon required operation.\nThe one-to-one relationship exists between Presenter and View as one Presenter class manages one View at a time.\nMultiple View can be mapped with a single ViewModel and thus, the one-to-many relationship exists between View and ViewModel.The View has no knowledge about the Controller.\nThe View has references to the Presenter.\nThe View has references to the ViewModelDifficult to make changes and modify the app features as the code layers are tightly coupled.\nCode layers are loosely coupled and thus it is easy to carry out modifications/changes in the application code.\nEasy to make changes in the application. However, if data binding logic is too complex, it will be a little harder to debug the application.User Inputs are handled by the Controller.\nThe View is the entry point to the Application\nThe View takes the input from the user and acts as the entry point of the application.Ideal for small scale projects only.\nIdeal for simple and complex applications.\nNot ideal for small scale projects.Limited support to Unit testing.\nEasy to carry out Unit testing but a tight bond of View and Presenter can make it slightly difficult.\nUnit testability is highest in this architecture.This architecture has a high dependency on Android APIs.\nIt has a low dependency on the Android APIs.\nHas low or no dependency on the Android APIs.It does not follow the modular and single responsibility principle.\nFollows modular and single responsibility principle.\nFollows modular and single responsibility principle.The key difference between MVP and MVC is that the Presenter in MVP has a more active role in the communication between the Model and the View, and is responsible for controlling the flow of data between the two. MVVM stands for Model-View-ViewModel. In the MVVM pattern, the \u201cModel\u201d represents the data and logic of the application, the \u201cView\u201d represents the UI of the application, and the \u201cViewModel\u201d is a layer that sits between the Model and the View and is responsible for exposing the data and logic of the Model to the View in a way that is easier to work with. The ViewModel also handles user input and updates the Model as needed.\nOverall, the main difference between these patterns is the role of the mediator component. MVC and MVP both involve a Controller or Presenter that acts as a mediator between the Model and the View, while MVVM involves a ViewModel that serves as the mediator between the Model and the View. MVC is the simplest of these patterns, while MVP and MVVM are more flexible and allow for a cleaner separation of concerns between the different layers of the application.\n"}, {"text": "\nDynamic TextSwitcher in Kotlin\n\nAndroid TextSwitcher is a user interface widget that contains number of textView and displays one at a time. Textswitcher is subclass of View Switcher which is used to animates one text and displays next one.\nHere, we create TextSwitcher programmatically in Kotlin file.\nFirst we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Modify activity_main.xml file\nIn this file, we use the TextSwitcher, Buttons and also set their attributes.XML \n Update strings.xml file\nHere, we update the name of the application using the string tag.XML \nDynamicTextSwitcherInKotlin \nNext \nPrev \n "}, {"text": "\nHow to Convert Kotlin Code to Java Code in Android Studio?\n\nJava programming language is the oldest and most preferred language for Android app development. However, during Google I/O 2017, Kotlin has been declared as an official language for Android development by the Google Android Team. Kotlin has gained popularity among developers very quickly because of its similarities as well as interoperable with the Java language. One can mix code of Java and Kotlin while designing an Android project. The syntax of Java and Kotlin differs in many aspects but their compilation process is almost the same. Code of both the languages gets compiled into bytecode that is executable on Java Virtual Machine(JVM). Thus if one can derive the bytecode of compiled Kotlin file, it can be decompiled in order to produce the equivalent Java code. Android Studio does exactly the same to carry out the code conversion from Kotlin to Java. Developers may have many reasons to convert the Kotlin code into Java such as:To integrate features that are easy to implement in Java language.\nTo resolve some performance issue that is difficult to locate in Kotlin.\nTo remove the Kotlin code from the project files.Code Conversion\nStep 1: Open Kotlin Class/File\nOpen the Kotlin Class/File which is to be converted into Java. Consider the code of the MainActivity file mentioned below for the conversion.Kotlin import android.os.Bundle \nimport android.view.View \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \n// declaring variable for TextView component \nprivate var textView: TextView? = null// declaring variable to store \n// the number of button click \nprivate var count = 0\noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // assigning ID of textView2 to the variable \ntextView = findViewById(R.id.textView2) // initializing the value of count with 0 \ncount = 0\n} // function to perform operations \n// when button is clicked \nfun buttonOnClick(view: View?) { \n// increasing count by one on \n// each tap on the button \ncount++ // changing the value of the \n// textView with the current \n// value of count variable \ntextView!!.text = Integer.toString(count) \n} \n}Step 2: Navigate to Tools Menu\nFrom the topmost toolbar of the Android Studio, select Tools and then navigate to Kotlin > Show Kotlin Bytecode. It will open a window at the right-hand side that will contain the line by line bytecode for the Kotlin file.Step 3: Decompile bytecode\nIn the bytecode window, checkbox the option \u201cJVM 8 target\u201d and click on Decompile. The Android Studio will generate the Java equivalent code for the Kotlin file. The produced java code will contain some additional information like metadata. Below is the generated Java code for the above mentioned Kotlin file.Java import android.os.Bundle; \nimport android.view.View; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; \nimport kotlin.Metadata; \nimport kotlin.jvm.internal.Intrinsics; \nimport org.jetbrains.annotations.Nullable; @Metadata( \nmv = {1, 4, 1}, \nbv = {1, 0, 3}, \nk = 1, \nd1 = {\"\\u0000,\\n\\u0002\\u0018\\u0002\\n\\u0002\\u0018\\u0002\\n\\u0002\\b\\u0002\\n\\u0002\\u0010\\b\\n\\u0000\\n\\u0002\\u0018\\u0002\\n\\u0000\\n\\u0002\\u0010\\u0002\\n\\u0000\\n\\u0002\\u0018\\u0002\\n\\u0002\\b\\u0002\\n\\u0002\\u0018\\u0002\\n\\u0000\\u0018\\u00002\\u00020\\u0001B\\u0005\u00a2\\u0006\\u0002\\u0010\\u0002J\\u0010\\u0010\\u0007\\u001a\\u00020\\b2\\b\\u0010\\t\\u001a\\u0004\\u0018\\u00010\\nJ\\u0012\\u0010\\u000b\\u001a\\u00020\\b2\\b\\u0010\\f\\u001a\\u0004\\u0018\\u00010\\rH\\u0014R\\u000e\\u0010\\u0003\\u001a\\u00020\\u0004X\\u0082\\u000e\u00a2\\u0006\\u0002\\n\\u0000R\\u0010\\u0010\\u0005\\u001a\\u0004\\u0018\\u00010\\u0006X\\u0082\\u000e\u00a2\\u0006\\u0002\\n\\u0000\u00a8\\u0006\\u000e\"}, \nd2 = {\"Lcom/example/javatokotlin/MainActivity;\", \"Landroidx/appcompat/app/AppCompatActivity;\", \"()V\", \"count\", \"\", \"textView\", \"Landroid/widget/TextView;\", \"buttonOnClick\", \"\", \"view\", \"Landroid/view/View;\", \"onCreate\", \"savedInstanceState\", \"Landroid/os/Bundle;\", \"app\"} \n) \npublic final class MainActivity extends AppCompatActivity { \nprivate TextView textView; \nprivate int count; protected void onCreate(@Nullable Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nthis.setContentView(1300009); \nthis.textView = (TextView)this.findViewById(1000069); \nthis.count = 0; \n} public final void buttonOnClick(@Nullable View view) { \nint var10001 = this.count++; \nTextView var10000 = this.textView; \nIntrinsics.checkNotNull(var10000); \nvar10000.setText((CharSequence)Integer.toString(this.count)); \n} \n}Note: The Kotlin to Java code conversion will not create a new file in the project directory from where one can access the Java code. Thus to use the Android Studio generated Java code, one needs to copy it from the displayed decompiled java file.Advantages of Java Over KotlinOperator overloading is not possible.\nClasses written in Java are not made final by default.\nMore readable syntax.\nUse of static methods and variables."}, {"text": "\nHow to Push Notification in Android?\n\nNotification is a message which appears outside of our Application\u2019s normal UI. A notification can appear in different formats and locations such as an icon in the status bar, a more detailed entry in the notification drawer, etc. Through the notification, we can notify users about any important updates, events of our application. By clicking the notification user can open any activity of our application or can do some action like opening any webpage etc.\nHow Does Notification Look?\nLet see the basic design of a notification template that appears in the navigation drawer.Part of a NotificationMethod for defining contentsType of argument needs to pass into the methodSmall Icon\nsetSmallIcon()\nneed to pass a drawable file as an ID that is an Int type.App Name\nBy default, App Name is provided by the System and we can\u2019t override it.Time Stamp\nBy default, timeStamp is provided by the System but we can override it by setWhen() method.\nA Long type of data should be passed.Title\nsetContentTitle()\nA String type of data should be passed.Text\nsetContentText()\nA String type of data should be passed.Large Icon\nsetLargeIcon()\nA Bitmap! type image file data should be passed.Understand Some Important Concepts of Push a Notification\nWe shall discuss all the concepts mentioned below step by step,Creating a basic notification\nCreating notification channel\nAdding large icon\nMaking notification expandable\nMaking notification clickable\nAdding an action button to our notification1. Creating a basic notification\nTo create a basic notification at first we need to build a notification. Now to build notification, we must use NotificationCompat.Builder() class where we need to pass a context of activity and a channel id as an argument while making an instance of the class. Please note here we are not using Notification.Builder(). NotificationCompat gives compatibility to upper versions (Android 8.0 and above) with lower versions (below Android 8.0).Kotlin val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) \n.setContentTitle(et1.text.toString()) \n.setContentText(et2.text.toString()) \n.setSmallIcon(R.drawable.spp_notification_foreground) \n.setPriority(NotificationCompat.PRIORITY_DEFAULT) \n.build()Please note, here we need to set the priority of the notification accordingly by the setPriority() method.Now to deliver the notification we need an object of NotificationManagerCompat class and then we notify it.Kotlin val nManager = NotificationManagerCompat.from(this) \n// Here we need to set an unique id for each \n// notification and the notification Builder \nnManager.notify(1, nBuilder)Please note that, in this method, we can deliver notification only in the android versions below 8.0 but in the android versions 8.0 and upper, no notification will appear by only this block of code.2. Creating a notification channel\nNow to deliver notifications on android version 8.0 and above versions, we need to create a notification channel. This Notification Channel concept comes from android 8.0. Here every application may have multiple channels for different types of notifications and each channel has some type of notification. Before you can deliver the notification on Android 8.0 and above versions, you must register your app\u2019s notification channel with the system by passing an instance of NotificationChannel to createNotificationChannel().Kotlin if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { \nval channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply { \ndescription = CHANNEL_DESCRIPTION \n} \nval nManager: NotificationManager = \ngetSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager \nnManager.createNotificationChannel(channel) \n}Please note that here we must provide a unique CHANNEL_ID for each channel and also we must give a CHANNEL_NAME and CHANNEL_DESCRIPTION. Also, we must give channel importance.3. Adding a large icon\nTo set a large icon we use the setLargeIcon() method which is applied to the instance of the NotificationCompat.Builder() class. In this method, we need to pass a Bitmap form of an image. Now to convert an image file (e.g. jpg, jpeg, png, etc.) of the drawable folder into a Bitmap, we use the following code in KotlinKotlin // converting a jpeg file to Bitmap file and making an instance of Bitmap! \nval imgBitmap=BitmapFactory.decodeResource(resources,R.drawable.gfg_green) // Building notification \nval nBuilder= NotificationCompat.Builder(this,CHANNEL_ID) \n.setContentTitle(et1.text.toString()) \n.setContentText(et2.text.toString()) \n.setSmallIcon(R.drawable.spp_notification_foreground) \n.setPriority(NotificationCompat.PRIORITY_DEFAULT) \n// passing the Bitmap object as an argument \n.setLargeIcon(imgBitmap) \n.build()4. Making notification expandable\nIn the short template of the notification, large information can\u2019t be shown. Therefore we need to make the notification expandable like this:to make such an expandable notification we use the setStyle() method on the notification builder (nBuilder) object. In this expanded area we can display an image, any text, different messages, etc. In our Application, we have added an image by passing the instance of the NotificationCompat.BigPictureStyle class to setStyle() method.Kotlin val imgBitmap = BitmapFactory.decodeResource(resources,R.drawable.gfg_green) \nval nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) \n.setContentTitle(et1.text.toString()) \n.setContentText(et2.text.toString()) \n.setSmallIcon(R.drawable.spp_notification_foreground) \n.setPriority(NotificationCompat.PRIORITY_DEFAULT) \n.setLargeIcon(imgBitmap) \n// Expandable notification \n.setStyle(NotificationCompat.BigPictureStyle() \n.bigPicture(imgBitmap) \n// as we pass null in bigLargeIcon() so the large icon \n// will goes away when the notification will be expanded. \n.bigLargeIcon(null)) \n.build()5. Making notification clickable\nWe need to make our notification clickable to perform some action by clicking the notification such as open an activity or system setting or any webpage etc. Now to perform such actions intent is needed (e.g. explicit or implicit intent). In our Application, we are making an Implicit intent to open the GFG official home page.Kotlin // Creating the Implicit Intent to \n// open the home page of GFG \nval intent1= Intent() \nintent1.action=Intent.ACTION_VIEW \nintent1.data=Uri.parse(\"https://www.geeksforgeeks.org/\")Now it is not necessary that whenever the notification will appear then the user will click it instantly, user can click it whenever he /she wants and therefore we also need to make an instance of PendingIntent which basically makes the intent action pending for future purpose.Kotlin val pendingIntent1=PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT) // Here the four parameters are context of activity, \n// requestCode,Intent and flag of the pendingIntent respectively \n// The request code is used to trigger a \n// particular action in application activity \nval nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) \n.setContentTitle(et1.text.toString()) \n.setContentText(et2.text.toString()) \n.setSmallIcon(R.drawable.notifications) \n.setPriority(NotificationCompat.PRIORITY_DEFAULT) \n.setLargeIcon(imgBitmap) \n.setStyle(NotificationCompat.BigPictureStyle() \n.bigPicture(imgBitmap) \n.bigLargeIcon(null)) \n// here we are passing the pending intent \n.setContentIntent(pendingIntent1) \n// as we set auto cancel true, the notification \n// will disappear after afret clicking it \n.setAutoCancel(true) \n.build()6. Adding an action button to our notification\nSometimes there exists some action button at our notification template that is used to perform some action.Here we also need an Intent and a PendingIntent. Then we need to pass the instance of the PendingIntent to addAction() method at the time of building the notification.Kotlin // Creating the Implicit Intent \n// to open the GFG contribution page \nval intent2 = Intent() \nintent2.action = Intent.ACTION_VIEW \nintent2.data = Uri.parse(\"https://www.geeksforgeeks.org/contribute/\") val nBuilder = NotificationCompat.Builder(this,CHANNEL_ID) \n.setContentTitle(et1.text.toString()) \n.setContentText(et2.text.toString()) \n.setSmallIcon(R.drawable.notifications) \n.setPriority(NotificationCompat.PRIORITY_DEFAULT) \n.setLargeIcon(imgBitmap) \n.setStyle(NotificationCompat.BigPictureStyle() \n.bigPicture(imgBitmap) \n.bigLargeIcon(null)) \n.setContentIntent(pendingIntent1) \n.setAutoCancel(true) \n// Here we need to pass 3 arguments which are \n// icon id, title, pendingIntent respectively \n// Here we pass 0 as icon id which means no icon \n.addAction(0,\"LET CONTRIBUTE\",pendingIntent2) \n.build()Example\nLet discuss all the concepts by making an Application named GFG_PushNotification. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theKotlinlanguage.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Choose the API level according to your choice( Here we have chosen API Level 26).After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link:\nCLICK HERE\n***Please note that it is optional***Step 2: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n \n \n \n Step 3: Insert a vector asset into the drawable folder in the res directory\nRight-click on the drawable folder \u2192 New \u2192 Vector Asset \u2192 select appropriate Clip Art \u2192 give appropriate Name and adjust Size accordingly\u2192 Next then click on the finish button as shown in the below image.Step 4: Working with the MainActivity.kt file\nGo to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.app.NotificationChannel \nimport android.app.NotificationManager \nimport android.app.PendingIntent \nimport android.content.Context \nimport android.content.Intent \nimport android.graphics.BitmapFactory \nimport android.net.Uri \nimport android.os.Build \nimport android.os.Bundle \nimport android.widget.Button \nimport android.widget.EditText \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.core.app.NotificationCompat \nimport androidx.core.app.NotificationManagerCompat class MainActivity : AppCompatActivity() { \nval CHANNEL_ID = \"GFG\"\nval CHANNEL_NAME = \"GFG ContentWriting\"\nval CHANNEL_DESCRIPTION = \"GFG NOTIFICATION\"// the String form of link for \n// opening the GFG home-page \nval link1 = \"https://www.geeksforgeeks.org/\"// the String form of link for opening \n// the GFG contribution-page \nval link2 = \"https://www.geeksforgeeks.org/contribute/\"\nlateinit var et1: EditText \nlateinit var et2: EditText \nlateinit var btn1: Button \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Binding Views by their IDs \net1 = findViewById(R.id.et1) \net2 = findViewById(R.id.et2) \nbtn1 = findViewById(R.id.btn1) \nbtn1.setOnClickListener { // Converting the .png Image file to a Bitmap! \nval imgBitmap = BitmapFactory.decodeResource(resources, R.drawable.gfg_green) // Making intent1 to open the GFG home page \nval intent1 = gfgOpenerIntent(link1) // Making intent2 to open The GFG contribution page \nval intent2 = gfgOpenerIntent(link2) // Making pendingIntent1 to open the GFG home \n// page after clicking the Notification \nval pendingIntent1 = PendingIntent.getActivity(this, 5, intent1, PendingIntent.FLAG_UPDATE_CURRENT) // Making pendingIntent2 to open the GFG contribution \n// page after clicking the actionButton of the notification \nval pendingIntent2 = PendingIntent.getActivity(this, 6, intent2, PendingIntent.FLAG_UPDATE_CURRENT) // By invoking the notificationChannel() function we \n// are registering our channel to the System \nnotificationChannel() // Building the notification \nval nBuilder = NotificationCompat.Builder(this, CHANNEL_ID) // adding notification Title \n.setContentTitle(et1.text.toString()) // adding notification Text \n.setContentText(et2.text.toString()) // adding notification SmallIcon \n.setSmallIcon(R.drawable.ic_android_black_24dp) // adding notification Priority \n.setPriority(NotificationCompat.PRIORITY_DEFAULT) // making the notification clickable \n.setContentIntent(pendingIntent1) \n.setAutoCancel(true) // adding action button \n.addAction(0, \"LET CONTRIBUTE\", pendingIntent2) // adding largeIcon \n.setLargeIcon(imgBitmap) // making notification Expandable \n.setStyle(NotificationCompat.BigPictureStyle() \n.bigPicture(imgBitmap) \n.bigLargeIcon(null)) \n.build() \n// finally notifying the notification \nval nManager = NotificationManagerCompat.from(this) \nnManager.notify(1, nBuilder) \n} \n} // Creating the notification channel \nprivate fun notificationChannel() { \n// check if the version is equal or greater \n// than android oreo version \nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { \n// creating notification channel and setting \n// the description of the channel \nval channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT).apply { \ndescription = CHANNEL_DESCRIPTION \n} \n// registering the channel to the System \nval notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager \nnotificationManager.createNotificationChannel(channel) \n} \n} // The function gfgOpenerIntent() returns \n// an Implicit Intent to open a webpage \nprivate fun gfgOpenerIntent(link: String): Intent { \nval intent = Intent() \nintent.action = Intent.ACTION_VIEW \nintent.data = Uri.parse(link) \nreturn intent \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20201216225710/output_final.mp4"}, {"text": "\nHow to Create Dynamic Horizontal RecyclerView in Android using Firebase Firestore?\n\nHorizontalRecyclerView is seen in many apps. It is generally used to display the categories in most apps and websites. This type of RecyclerView is seen in many E-commerce apps to indicate categories in the app. And this RecyclerView is also dynamic so that the admin can add or remove any item from that RecyclerView at any time. So in this article, we will take a look at creating a dynamic Horizontal Recycler View in Android using Firebase. We will be using Firebase Firestore to display the items of RecyclerView.\nWhat we are going to build in this article?We will be building a simple application in which we will be displaying a horizontal RecyclerView in which we will be showing different technologies used in Computer Science. So we will represent this amazing computer technology in our Horizontal RecyclerView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.\nStep by Step ImplementationStep 1: Create a new Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. \nStep 2: Connect your app to Firebase\nAfter creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.\nimplementation \u2018com.google.firebase:firebase-firestore:22.0.1\u2019\nAfter adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. \nStep 3: Working with the AndroidManifest.xml file\nFor adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. XML\n \n Step 4: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML\n \n \n Step 5: Now we will create a new Java class for storing our data \nFor reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app\u2019s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it. Javapublic class DataModal { // variables for storing our image and name.\n private String name;\n private String imgUrl; public DataModal() {\n // empty constructor required for firebase.\n } // constructor for our object class.\n public DataModal(String name, String imgUrl) {\n this.name = name;\n this.imgUrl = imgUrl;\n } // getter and setter methods\n public String getName() {\n return name;\n } public void setName(String name) {\n this.name = name;\n } public String getImgUrl() {\n return imgUrl;\n } public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n}Step 6: Now we will create a layout file for our item of RecyclerView\nNavigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_rv_item and add the below code to it. XML\n \n \n Step 7: Now we will move towards creating an Adapter class\nFor creating a new Adapter class navigate to the app > java > your app\u2019s package name > Right-click on it and Click on New > Java class and name your java class as DataRVAdapter and add below code to it. Comments are added inside the code to understand the code in more detail.Javaimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;import com.squareup.picasso.Picasso;import java.util.ArrayList;public class DataRVAdapter extends RecyclerView.Adapter {\n private ArrayList dataModalArrayList;\n private Context context; // constructor class for our Adapter\n public DataRVAdapter(ArrayList dataModalArrayList, Context context) {\n this.dataModalArrayList = dataModalArrayList;\n this.context = context;\n } @NonNull\n @Override\n public DataRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n // passing our layout file for displaying our card item\n return new DataRVAdapter.ViewHolder(LayoutInflater.from(context).inflate(R.layout.image_rv_item, parent, false));\n } @Override\n public void onBindViewHolder(@NonNull DataRVAdapter.ViewHolder holder, int position) {\n // setting data to our views in Recycler view items.\n DataModal modal = dataModalArrayList.get(position);\n holder.courseNameTV.setText(modal.getName());\n \n // we are using Picasso to load images\n // from URL inside our image view.\n Picasso.get().load(modal.getImgUrl()).into(holder.courseIV);\n holder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // setting on click listener\n // for our items of recycler items.\n Toast.makeText(context, \"Clicked item is \" + modal.getName(), Toast.LENGTH_SHORT).show();\n }\n });\n } @Override\n public int getItemCount() {\n // returning the size of array list.\n return dataModalArrayList.size();\n } public class ViewHolder extends RecyclerView.ViewHolder {\n // creating variables for our \n // views of recycler items.\n private TextView courseNameTV;\n private ImageView courseIV; public ViewHolder(@NonNull View itemView) {\n super(itemView);\n // initializing the views of recycler views.\n courseNameTV = itemView.findViewById(R.id.idTVtext);\n courseIV = itemView.findViewById(R.id.idIVimage);\n }\n }\n}Step 8: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Javaimport android.os.Bundle;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;import com.google.android.gms.tasks.OnFailureListener;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.firebase.firestore.DocumentSnapshot;\nimport com.google.firebase.firestore.FirebaseFirestore;\nimport com.google.firebase.firestore.QuerySnapshot;import java.util.ArrayList;\nimport java.util.List;public class MainActivity extends AppCompatActivity { private RecyclerView courseRV;\n private ArrayList dataModalArrayList;\n private DataRVAdapter dataRVAdapter;\n private FirebaseFirestore db; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); // initializing our variables.\n courseRV = findViewById(R.id.idRVItems);\n \n // initializing our variable for firebase \n // firestore and getting its instance.\n db = FirebaseFirestore.getInstance();\n \n // creating our new array list\n dataModalArrayList = new ArrayList<>();\n courseRV.setHasFixedSize(true);\n \n // adding horizontal layout manager for our recycler view.\n courseRV.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));\n \n // adding our array list to our recycler view adapter class.\n dataRVAdapter = new DataRVAdapter(dataModalArrayList, this);\n \n // setting adapter to our recycler view.\n courseRV.setAdapter(dataRVAdapter); loadrecyclerViewData();\n } private void loadrecyclerViewData() { db.collection(\"Data\").get()\n .addOnSuccessListener(new OnSuccessListener() {\n @Override\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) {\n // after getting the data we are calling on success method\n // and inside this method we are checking if the received \n // query snapshot is empty or not.\n if (!queryDocumentSnapshots.isEmpty()) {\n // if the snapshot is not empty we are hiding our\n // progress bar and adding our data in a list.\n List list = queryDocumentSnapshots.getDocuments();\n for (DocumentSnapshot d : list) {\n // after getting this list we are passing that \n // list to our object class.\n DataModal dataModal = d.toObject(DataModal.class);\n \n // and we will pass this object class\n // inside our arraylist which we have\n // created for recycler view.\n dataModalArrayList.add(dataModal);\n }\n // after adding the data to recycler view.\n // we are calling recycler view notifyDataSetChanged\n // method to notify that data has been changed in recycler view.\n dataRVAdapter.notifyDataSetChanged();\n } else {\n // if the snapshot is empty we are \n // displaying a toast message.\n Toast.makeText(MainActivity.this, \"No data found in Database\", Toast.LENGTH_SHORT).show();\n }\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n // if we do not get any data or any error we are displaying \n // a toast message that we do not get any data\n Toast.makeText(MainActivity.this, \"Fail to get the data.\", Toast.LENGTH_SHORT).show();\n }\n });\n }\n}Step 9: Now add the data to your Firebase Console\nSearch for Firebase in your browser and go to that website and you will get to see the below screen.\nAfter clicking on Go to Console option. Click on your project which is shown below.\nAfter clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen.After clicking on the Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console.\nYou have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for \u201cname\u201d and one filed for \u201cimgUrl\u201d and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added.\nSimilarly, add more images by clicking on the \u201cAdd document\u201d button.\nAfter adding these images run your app and you will get to see the output on the below screen.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210111135124/Screenrecorder-2021-01-11-13-48-56-864.mp4\n"}, {"text": "\nAndroid Architecture Patterns\n\nWhen developers work on a real mobile application whose nature is dynamic and will expand its features according to the user\u2019s need, then it is not possible to write core logic in activities or fragments. To structure the project\u2019s code and to give it a modular design(separated code parts), architecture patterns are applied to separate the concerns. The most popular android architectures used by developers are the following:MVC (Model \u2014 View \u2014 Controller)\nMVP (Model \u2014 View \u2014 Presenter)\nMVVM (Model \u2014 View \u2014 ViewModel)The main idea of all these patterns is to organize the project in a proper way so that all the codes get covered in the Unit Testing. Moreover, it is very helpful in the maintenance of the software, to add and remove features and developers can keep a track of various crucial logic parts.\nThe Model\u2014View\u2014Controller(MVC) Pattern\nMVC pattern is the oldest android app architecture which simply suggests separating the code into 3 different layers:Model: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: UI(User Interface) layer. It provides the visualization of the data stored in the Model.\nController: Layer which contains core logic. It gets informed of the user\u2019s behavior and updates the Model as per the need.In MVC schema, View and Controller both depend upon the Model. Application data is updated by the controller and View gets the data. In this pattern, the Model could be tested independently of the UI as it is separated. There are multiple approaches possible to apply the MVC pattern. Either the activities and fragments can act like the controller where they are responsible for data processing and updating the views. Another way is to use the activities and fragments as Views and the controller, as well as Models, should be a separate class that does not extend any Android class. If the Views respect the single responsibility principle then their role is just to update the Controller for every user event and just display data from the Model, without implementing any business logic. In this case, UI tests should be enough to cover the functionalities of the View.\nAdvantages:MVC pattern increases the code testability and makes it easier to implement new features as it highly supports the separation of concerns.\nUnit testing of the Model and Controller is possible as they do not extend or use any Android class.\nFunctionalities of the View can be checked through UI tests if the View respect the single responsibility principle(update controller and display data from the model without implementing domain logic)Disadvantages:Code layers depend on each other even if MVC is applied correctly.\nNo parameter to handle UI logic i.e., how to display the data.The Model\u2014View\u2014Presenter(MVP) Pattern\nMVP pattern is the second iteration of Android app architecture. This pattern is widely accepted and is still recommended for upcoming developers. The purpose of each component is easy to learn:Model: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: UI(User Interface) layer. It provides the visualization of the data and keep a track of the user\u2019s action in order to notify the Presenter.\nPresenter: Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user\u2019s input notification from the View.In the MVP schema, View and Presenter are closely related and have a reference to each other. To make the code readable and easier to understand, a Contract interface class is used to define the Presenter and View relationship. The View is abstracted and has an interface in order to enable the Presenter for Unit Testing.\nAdvantages:No conceptual relationship in android components\nEasy code maintenance and testing as the application\u2019s model, view, and presenter layer are separated.Disadvantages:If the developer does not follow the single responsibility principle to break the code then the Presenter layer tends to expand to a huge all-knowing class.The Model\u2014View\u2014ViewModel (MVVM) Pattern\nThe third iteration of android architecture is the MVVV pattern. While releasing the Android Architecture Components, the Android team recommended this architecture pattern. Below are the separate code layers:Model: This layer is responsible for the abstraction of the data sources. Model and ViewModel work together to get and save the data.\nView: The purpose of this layer is to inform the ViewModel about the user\u2019s action.\nViewModel: It exposes those data streams which are relevant to the View.The MVVM and MVP patterns are quite similar because both are efficient in abstracting the state and behavior of the View layer. In MVVM, Views can bind itself to the data streams which are exposed by ViewModel.In MVVM schema the View informs the ViewModel about various actions. The View has a reference to the ViewModel while ViewModel has no information about the View. The many-to-one relationship that exists between View and ViewModel and MVVM supports two-way data binding between both.\nComparing MVC, MVP, and MVVM Architecture PatternPatternDependency on Android APIXML ComplexityUnit TestabilityFollow Modular and single\nresponsibility principleMVC\nHigh\nLow\nDifficult\nNoMVP\nLow\nLow\nGood\nYesMVVM\nLow or No dependency\nMedium to High\nBest\nYesAdvantages of ArchitectureDevelopers can design applications that can accept changes in the future.\nGives a modular design to the application which assures good quality testing and maintenance of code.Disadvantages of ArchitectureWriting the whole project code in an architecture pattern is a time taking process.\nStrict discipline is required from the developer team side as one misplaced change can ruin the integrity of the architecture."}, {"text": "\nAndroid UI Layouts\n\nAndroid Layout is used to define the user interface that holds the UI controls or widgets that will appear on the screen of an android application or activity screen. Generally, every application is a combination of View and ViewGroup. As we know, an android application contains a large number of activities and we can say each activity is one page of the application. So, each activity contains multiple user interface components and those components are the instances of the View and ViewGroup. All the elements in a layout are built using a hierarchy of View and ViewGroup objects.\nView\nA View is defined as the user interface which is used to create interactive UI components such as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and drawing. They are Generally Called Widgets.\nView\nA ViewGroup act as a base class for layouts and layouts parameters that hold other Views or ViewGroups and to define the layout properties. They are Generally Called layouts.\nViewGroup\nThe Android framework will allow us to use UI elements or widgets in two ways:Use UI elements in the XML file\nCreate elements in the Kotlin file dynamicallyTypes of Android LayoutAndroid Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements one by one either in a particular direction either horizontally or vertically based on the orientation property.\nAndroid Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the top of the parent).\nAndroid Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the position of layout constraints for every child View relative to other views present. A ConstraintLayout is similar to a RelativeLayout, but having more power.\nAndroid Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of View elements it contains on the top of each other to display only a single View inside the FrameLayout.\nAndroid Table Layout: TableLayout is a ViewGroup subclass, used to display the child View elements in rows and columns.\nAndroid Web View: WebView is a browser that is used to display the web pages in our activity layout.\nAndroid ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single column.\nAndroid Grid View: GridView is a ViewGroup that is used to display a scrollable list of items in a grid view of rows and columns.Use UI Elements in the XML file\nHere, we can create a layout similar to web pages. The XML layout file contains at least one root element in which additional layout elements or widgets can be added to build a View hierarchy. Following is the example:XML \n\n \n Load XML Layout File and its elements from an Activity\nWhen we have created the layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element from the XML using findViewById.\noverride fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) // finding the button\n val showButton = findViewById(R.id.showInput) // finding the edit text\n val editText = findViewById(R.id.editText)\nHere, we can observe the above code and finds out that we are calling our layout using the setContentView method in the form of R.layout.activity_main. Generally, during the launch of our activity, the onCreate() callback method will be called by the android framework to get the required layout for an activity.\nCreate elements in the Kotlin file Dynamically\nWe can create or instantiate UI elements or widgets during runtime by using the custom View and ViewGroup objects programmatically in the Kotlin file. Below is the example of creating a layout using LinearLayout to hold an EditText and a Button in an activity programmatically.Kotlin import android.os.Bundle\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.LinearLayout\nimport android.widget.Toast\nimport android.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// create the button\nval showButton = Button(this)\nshowButton.setText(\"Submit\")// create the editText\nval editText = EditText(this)val linearLayout = findViewById(R.id.l_layout)\nlinearLayout.addView(editText)\nlinearLayout.addView(showButton)// Setting On Click Listener\nshowButton.setOnClickListener\n{\n// Getting the user input\nval text = editText.text// Showing the user input\nToast.makeText(this, text, Toast.LENGTH_SHORT).show()\n}\n}\n}Different Attribute of the LayoutsXML attributesDescriptionandroid:id\nUsed to specify the id of the view.android:layout_width\nUsed to declare the width of View and ViewGroup elements in the layout.android:layout_height\nUsed to declare the height of View and ViewGroup elements in the layout.android:layout_marginLeft\nUsed to declare the extra space used on the left side of View and ViewGroup elements.android:layout_marginRight\nUsed to declare the extra space used on the right side of View and ViewGroup elements.android:layout_marginTop\nUsed to declare the extra space used in the top side of View and ViewGroup elements.android:layout_marginBottom\nUsed to declare the extra space used in the bottom side of View and ViewGroup elements.android:layout_gravity\nUsed to define how child Views are positioned in the layout."}, {"text": "\nInterpolator in Android with Example\n\nAn interpolator is a function (in the mathematical sense) that outputs values \u201cinterpolated\u201d between a range of values that are given to it as input. Interpolation is simply a method to generate new data points between two fixed data points. The exact values of these generated data points are determined by the kind of interpolation is performed. For example, in linear interpolation, all the generated values are evenly distributed between the fixed points. While an understanding of interpolation is helpful, it isn\u2019t necessary to get started animating your views in your apps. In fact, the animation perspective of interpolation might prove helpful in understanding it! So, let\u2019s get started. In this example, we\u2019ll create a simple app with a list of buttons. Each of these buttons is for a specific type of interpolated animation which kicks off when you press it. The animation is a simple horizontal translation that moves the button to the right.\nThe Interpolator Interface\nIn the Android development framework, Interpolator is defined as an interface. This allows methods to accept an interpolator that can bring its own configuration and not tie developers to a specific implementation. As of this writing, there are 11 indirect subclasses of the Interpolator interface. They are:Linear Interpolator: The generated values between the two fixed points are evenly distributed. For example, consider a = 1 and b = 5 to be the fixed points. Linear interpolation between a and b would look like: 1 -> 2 -> 3 -> 4 -> 5, where the numbers between 1 and 5 have been generated.\nAccelerate Interpolator: This interpolator generates values that initially have a small difference between them and then ramps up the difference gradually until it reaches the endpoint. For example, the generated values between 1 -> 5 with accelerated interpolation could be 1 -> 1.2 -> 1.5 -> 1.9 -> 2.4 -> 3.0 -> 3.6 -> 4.3 -> 5. Notice how the difference between consecutive values grows consistently.\nDecelerate Interpolator: In the sense that the accelerate interpolator generates values in an accelerating fashion, a decelerate interpolator generates values that are \u201cslowing down\u201d as you move forward in the list of generated values. So, the values generated initially have a greater difference between them and the difference gradually reduces until the endpoint is reached. Therefore, the generated values between 1 -> 5 could look like 1 -> 1.8 -> 2.5 -> 3.1 -> 3.6 -> 4.0 -> 4.3 -> 4.5 -> 4.6 -> 4.7 -> 4.8 -> 4.9 -> 5. Again, pay attention to the difference between consecutive values growing smaller.\nAccelerate Decelerate Interpolator: This interpolator starts out with a slow rate of change and accelerates towards the middle. As it approaches the end, it starts decelerating, i.e. reducing the rate of change.\nAnticipate Interpolator: This interpolation starts by first moving backward, then \u201cflings\u201d forward, and then proceeds gradually to the end. This gives it an effect similar to cartoons where the characters pull back before shooting off running. For example, generated values between 1 -> 3 could look like: 1 -> 0.5 -> 2 -> 2.5 -> 3. Notice how the first generated value is \u201cbehind\u201d the starting value and how it jumps forward to a value ahead of the starting value. It then proceeds uniformly to the endpoint.\nBounce Interpolator: To understand this interpolator, consider a meter scale that\u2019s standing vertically on a solid surface. The starting value is at the top and the end value is at the bottom, touching the surface. Consider now, a ball that is dropped next to the meter scale. The ball on hitting the surface bounces up and down a few times until finally coming to rest on the surface. With the bounce interpolator, the generated values are similar to the list of values the ball passes by alongside the meter scale. For example, the generated values between 1 -> 5 could be 1 -> 2 -> 3 -> 4 -> 5 -> 4.2 -> 5 -> 4.5 -> 5. Notice how the generated values bounce.\nOvershoot Interpolator: This interpolator generates values uniformly from the start to end. However, after hitting the end, it overshoots or goes beyond the last value by a small amount and then comes back to the endpoint. For example, the generated values between 1 -> 5 could look like: 1 -> 2 -> 3 -> 4 -> 5 -> 5.5 -> 5.\nAnticipate Overshoot Interpolator: This interpolator is a combination of the anticipate and overshoot interpolators. That is, it first goes backward from the starting value, flings forward and uniformly moves to the endpoint, overshoots it, and then returns to the endpoint.Creating the App\nTo better understand the above-mentioned classes and see them in action, it\u2019s highly recommended you follow along with an actual project and run the app as you build it.Enable and Setup View Binding (Optional)View binding is a neat little feature that was introduced not too long ago that makes it easier to work with views in your app. Essentially it does away with findViewById calls and gives you handles to views that are easier to use. They also make your code cleaner. It\u2019s a very simple process and you can see how to turn it on and set it up in the official docs. This step is optional, however, and if you prefer to wire up your views manually, you can proceed with that as well. The end result just needs to be that you have handles to the buttons you aim to configure.\nCreate the LayoutIn your activity_main.xml file, create the list of buttons as shown in the code section below. The layout basically consists of repeated code for the different buttons, so if you understand what\u2019s going on with one button, you can apply the same to the other buttons as well.Step 1: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n \n Step 2: Working with the MainActivity.java file\nSetup ObjectAnimator Object: For this example, we\u2019ll use a single ObjectAnimator to animate the different buttons. We\u2019ll also use a fixed duration of 2 seconds for the animations to play out, this gives us ample time to observe the animation behaviors. You can have this set up with 2 lines of code as below.Java // 2-second animation duration \nfinal private static int ANIMATION_DURATION = 2000; \nprivate ObjectAnimator animator;Setup Animations on Button Click: Now that we have the pre-requisites setup, we can finally get to configuring the buttons to trigger their respective animations. For each button, you can configure the specific property to animate, its duration, and the interpolation, among other things. The basic three-step configuration is performed as shown in the code snippet below:Java // Linear \nbinding.linear.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.linear,\"translationX\", 200f); \nanimator.setInterpolator(new LinearInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n});Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.animation.ObjectAnimator; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.view.animation.AccelerateDecelerateInterpolator; \nimport android.view.animation.AccelerateInterpolator; \nimport android.view.animation.AnticipateInterpolator; \nimport android.view.animation.AnticipateOvershootInterpolator; \nimport android.view.animation.BounceInterpolator; \nimport android.view.animation.CycleInterpolator; \nimport android.view.animation.DecelerateInterpolator; \nimport android.view.animation.LinearInterpolator; \nimport android.view.animation.OvershootInterpolator; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.example.doobar.databinding.ActivityMainBinding; public class MainActivity extends AppCompatActivity { // 2-second animation duration \nfinal private static int ANIMATION_DURATION = 2000; private ActivityMainBinding binding; \nprivate ObjectAnimator animator; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nbinding = ActivityMainBinding.inflate(getLayoutInflater()); \nView view = binding.getRoot(); \nsetContentView(view); // setup animation buttons // Linear \nbinding.linear.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.linear, \"translationX\", 200f); \nanimator.setInterpolator(new LinearInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Accelerate \nbinding.accelerate.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.accelerate, \"translationX\", 200f); \nanimator.setInterpolator(new AccelerateInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Decelerate \nbinding.decelerate.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.decelerate, \"translationX\", 200f); \nanimator.setInterpolator(new DecelerateInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Bounce \nbinding.bounce.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.bounce, \"translationX\", 200f); \nanimator.setInterpolator(new BounceInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Overshoot \nbinding.overshoot.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.overshoot, \"translationX\", 200f); \nanimator.setInterpolator(new OvershootInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Anticipate \nbinding.anticipate.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.anticipate, \"translationX\", 200f); \nanimator.setInterpolator(new AnticipateInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Cycle \nbinding.cycle.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.cycle, \"translationX\", 200f); \nanimator.setInterpolator(new CycleInterpolator(2)); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Accelerate Decelerate \nbinding.accelerateDecelerate.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.accelerateDecelerate, \"translationX\", 200f); \nanimator.setInterpolator(new AccelerateDecelerateInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); // Anticipate Overshoot \nbinding.anticipateOvershoot.setOnClickListener(clickedView -> { \nanimator = ObjectAnimator.ofFloat(binding.anticipateOvershoot, \"translationX\", 200f); \nanimator.setInterpolator(new AnticipateOvershootInterpolator()); \nanimator.setDuration(ANIMATION_DURATION); \nanimator.start(); \n}); \n} \n}Output: Run the App\nHaving built the buttons and having set them up to trigger animations when pressed, you\u2019re all set to fire up the app and see your animations come to life. And you\u2019re done! That\u2019s how you use interpolators in your animations to spice them up and not make them look monotonic.https://media.geeksforgeeks.org/wp-content/uploads/20201129145930/recording.mp4\nYou can view the entire application here: https://github.com/krishnakeshan/android-interpolators."}, {"text": "\nDebugging with Stetho in Android\n\nStetho is an open-source debug library developed by Facebook. It allows you to use chrome debugging tools to troubleshoot network traffic., thus it provides a rich, interactive debugging experience for android developers. Stetho easily and smoothly debug network calls. It is a Sophisticated Debug Bridge for Android Applications. When enabled, developers have a path to the Chrome Developer Tools feature natively part of the Chrome desktop browser. Developers can also prefer to allow the optional dumpApp tool which allows a powerful command-line interface to application internals. Without limiting its functionality to just network inspection, JavaScript console, database inspection, etc. We are going toimplement this project using both Java and Kotlin Programming Language for Android.\nFeatures of StethoStetho is an open-source debugging platform.\nIt provides a rich and highly interactive experience.\nWith the help of Stetho native applications debugging is very simple.\nIt offers you to use Google Chrome debugging tool for various activities.\nIt provides hierarchy inspection during debugging.\nAlso, Stetho allows network, database management, and more interacting features.\nStetho uses an HTTP web socket to send data.The Problem\nThe problem with debugging network traffic while developing android applications, debugger facing problems with traditional debugging tools get messed up and inspection got very complex while switching the devices.\nThe Solution Provided by Stetho\nThe debugging is more reliable and easy with the Stetho library because it uses the chrome debugging tool which supports web-socket and uses it for network debugging. Stetho automated the call inspection, so it becomes more important for android developers.\nHow to Work with Chrome Dev Tool?\nStetho uses an HTTP web Socket server that sends all debugging information to the browser. It is accessible through:\nchrome://inspectStep by Step Implementation\nStep 1: Adding Dependency to the build.gradle File\nGo to Module build.gradle file and add this dependency and click on Sync Now button.\nimplementation 'com.facebook.stetho:stetho-okhttp3:1.5.1'\nStep 2: Register the Class in AndroidManifest.xml, and Initialize it in the ApplicationJava import android.app.Application; \nimport android.content.Context; \nimport com.facebook.stetho.InspectorModulesProvider; \nimport com.facebook.stetho.Stetho; \nimport com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain; \nimport com.facebook.stetho.okhttp3.StethoInterceptor; \nimport com.facebook.stetho.rhino.JsRuntimeReplFactoryBuilder; \nimport com.jakewharton.caso.OkHttp3Downloader; \nimport com.squareup.caso.Caso; \nimport okhttp3.OkHttpClient; public class Stetho extends Application { public OkHttpClient httpClient; @Override\npublic void onCreate() { \nsuper.onCreate(); \nfinal Context context = this; if (BuildConfig.DEBUG) { // Create an InitializerBuilder \nStetho.InitializerBuilder initializerBuilder = Stetho.newInitializerBuilder(this); // Enable Chrome DevTools \ninitializerBuilder.enableWebKitInspector(new InspectorModulesProvider() { \n@Override\npublic Iterable get() { \n// Enable command line interface \nreturn new Stetho.DefaultInspectorModulesBuilder(context).runtimeRepl( \nnew JsRuntimeReplFactoryBuilder(context).addVariable(\"foo\", \"bar\").build() \n).finish(); \n} \n}); // Use the InitializerBuilder to generate an Initializer \nStetho.Initializer initializer = initializerBuilder.build(); // Initialize Stetho with the Initializer \nStetho.initialize(initializer); // Add Stetho interceptor \nhttpClient = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build(); \n} else { \nhttpClient = new OkHttpClient(); \n} \nCaso caso = new Caso.Builder(this).downloader(new OkHttp3Downloader(httpClient)).build(); \nCaso.setSingletonInstance(caso); \n} \n}Kotlin import android.app.Application \nimport android.content.Context \nimport com.facebook.stetho.InspectorModulesProvider \nimport com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain \nimport com.facebook.stetho.okhttp3.StethoInterceptor \nimport com.facebook.stetho.rhino.JsRuntimeReplFactoryBuilder \nimport com.jakewharton.caso.OkHttp3Downloader \nimport com.squareup.caso.Caso \nimport okhttp3.OkHttpClient class Stetho : Application() { private lateinit var httpClient: OkHttpClient override fun onCreate() { \nsuper.onCreate() \nval context: Context = thisif (BuildConfig.DEBUG) { \n// Create an InitializerBuilder \nval initializerBuilder: Stetho.InitializerBuilder = newInitializerBuilder(this) \n// Enable Chrome DevTools \ninitializerBuilder.enableWebKitInspector(object : InspectorModulesProvider() { \nfun get(): Iterable { \n// Enable command line interface \nreturn DefaultInspectorModulesBuilder(context).runtimeRepl( \nJsRuntimeReplFactoryBuilder(context).addVariable(\"foo\", \"bar\").build() \n).finish() \n} \n}) // Use the InitializerBuilder to generate an Initializer \nval initializer: Stetho.Initializer = initializerBuilder.build() // Initialize Stetho with the Initializer \ninitialize(initializer) // Add Stetho interceptor \nhttpClient = Builder().addNetworkInterceptor(StethoInterceptor()).build() \n} else { \nhttpClient = OkHttpClient() \n} \nval caso: Caso = Builder(this).downloader(OkHttp3Downloader(httpClient)).build() \nCaso.setSingletonInstance(caso) \n} \n}OR\nInitialize your Library with a Single Line of Code:Java import android.app.Application; public class ApplicationStetho extends Application { \npublic void onCreate() { \nsuper.onCreate(); if(BuildConfig.DEBUG ){ \nStetho.initializeWithDefault(this); \n} \n} \n}Kotlin import android.app.Application class ApplicationStetho : Application() { \noverride fun onCreate() { \nsuper.onCreate() if (BuildConfig.DEBUG) { \nStetho.initializeWithDefault(this) \n} \n} \n}Updating the Manifest File in the Android Project:XML \n \n Step 3: Enable Network Inspection.\nThe following method is the easiest and simpler way to enable network inspection when you constructing the okHttpClient instance:\nokHttpClient.Builder().addNetworkInterceptor(StethoInterceptor()).build()\nHow to Check?\nRun the emulator on the device. Then open chrome://inspect on Chrome and your emulator device should appear, after that click inspects to launch a new window, and click the network tab to watch network traffics."}, {"text": "\nHow to Access any Component Outside RecyclerView from RecyclerView in Android?\n\nThe title may be a little confusing but what we want to say is, suppose in an Android App, there\u2019s a RecyclerView, and outside that there\u2019s a TextView. In the RecyclerView there\u2019s a list of clickable components, said Button. Now what I want is, for different button clicks, the text in the TextView will be different. So this is basically controlling a component outside RecyclerView, from a RecyclerView.As per the picture, there\u2019s a RecyclerView with four Buttons (1 hidden at the left) and a TextView. For different Button clicks different texts are showing up in the TextView. In this article, the same concept will be implemented with a little real-world touch. So the final app will show a list and a sub-list of the Tutorials offered by GEEKS FOR GEEKS. Here\u2019s a demo GIF of the final app:Prerequisites:How to install Android Studio\nSetting up a new project in Android Studio\nWhat is RecyclerViewStep 1: Working with the activity_main.xml fileGo to the res -> layout -> activity_main.xml file.\nHere is the code of that XML file:XML \n \n \n \n Here, two RecyclerView is used, one horizontal (recyclerViewOne) and one vertical (recyclerViewTwo). The first one shows the main list and the second one shows the sub-list of the main list item.\nA TextView is also used to show the main list-item text.Step 2: Add single_card_layout.xml for the main list itemsGo to the res -> layout\nRight Click on the layout folder\nGo to New -> Layout Resource File\nType the file name (single_card_layout.xml for me)\nChange the root element to RelativeLayout\nClick OKHere is the code of this XML file:XML \n \n \n This is basically the layout of the items shown in the recyclerViewOne or the main list or the horizontal RecyclerView.Step 3: Add single_card_layout_vertical.xml for the sub-list itemsGo to the res -> layout\nRight Click on the layout folder\nGo to New -> Layout Resource File\nType the file name (single_card_layout_vertical.xml as per this example)\nChange the root element to RelativeLayout\nClick OK\nHere is the code of this XML file:XML \n \n This is the layout of the items shown in the recyclerViewTwo or the sub list or the vertical RecyclerView.Step 4: Working on the horizontal RecyclerView or the main listGo to java ->com.wheic.recyclergetsout (Your\u2019s may differ)\nMake a directory under com.wheic.recyclergetsout (I named it RV1). Making a directory from Android Studio is weird, there\u2019s a lot of bugs in the process (at least for me). So you can follow these steps:Right-click on com.wheic.recyclergetsout (Your\u2019s may differ)\ncom.wheic.recyclergetsout -> New -> Sample Data DirectoryGo to Build -> Rebuild ProjectA sampledata folder will be seen under the app folder.Right-click on it. Go to Refactor -> Rename.Give the name of the folder. (Here we named it RV1).\nClick Refactor.Drag the folder on to com.wheic.recyclergetsout\nClick Refactor in the pop-up window.Go to Build -> Rebuild Project.\nOR, If don\u2019t wanna do all these, just directly go to the Explorer and make a directory there. For this right-click on com.wheic.recyclergetsout -> Show in Explorer. Then create a folder there manually.Start working on the corresponding model class:Right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneModel.\nSo basically I am using two variables, one String type, and one integer. The String variable will be used to store the title of the list item and the integer variable to differentiate each item. Then a constructor with both the variables and only the Getter functions are made for these two variables.\nHere\u2019s the java code of the model class:Java public class RVOneModel { \n// this variable will store main-list item title \nprivate String name; // this will differentiate between the main-list items \nprivate int num; // parameterized constructor \npublic RVOneModel(String name, int num) { \nthis.name = name; \nthis.num = num; \n} // getter functions for these two variables \npublic String getName() { \nreturn name; \n} public int getNum() { \nreturn num; \n} \n}Start working on the Adapter class for the horizontal RecyclerView:So, right-click on the just created folder (RV1) -> New -> Java Class. Give the name of the class. I named it RVOneAdapter.\nSo with the adapter, we also need a ViewHolder class.\nThe use of these classes and every other method are already clearly described in this GFG link.\nHere\u2019s the java code of this Adapter class with the ViewHolder class:Java import android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; \nimport androidx.annotation.NonNull; \nimport androidx.cardview.widget.CardView; \nimport androidx.recyclerview.widget.RecyclerView; \nimport com.wheic.recyclergetsout.R; \nimport java.util.List; public class RVOneAdapter extends RecyclerView.Adapter { // Main-list item titles will be stored here \nprivate List tutorialList; // Parameterized constructor of this \n// class to initialize tutorialList \npublic RVOneAdapter(List tutorialList) { \nthis.tutorialList = tutorialList; } // Attach the item layout with the proper xml file \n@NonNull\n@Override\npublic ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout, parent, false); \nreturn new ViewHolder(view); \n} // It deals with the setting of different data and methods \n@Override\npublic void onBindViewHolder(@NonNull ViewHolder holder, int position) { \nfinal RVOneModel modelItems = tutorialList.get(position); \nholder.setData(tutorialList.get(position).getName()); \n} // It returns the length of the RecyclerView \n@Override\npublic int getItemCount() { \nreturn tutorialList.size(); \n} // The ViewHolder is a java class that stores \n// the reference to the item layout views \npublic class ViewHolder extends RecyclerView.ViewHolder{ public CardView singleItemCardView; \npublic TextView singleItemTextView; //Link up the Main-List items layout \n// components with their respective id \npublic ViewHolder(@NonNull View itemView) { \nsuper(itemView); \nsingleItemCardView = itemView.findViewById(R.id.singleItemCardView); \nsingleItemTextView = itemView.findViewById(R.id.singleItemTextView); \n} // setText in Main-List title text \npublic void setData(String name){ \nthis.singleItemTextView.setText(name); \n} \n} \n}Start working on the MainActivity.java to add the first RecyclerView:The tutorialList is stored with Main-List item title string variables one by one and then the adapter is set to the horizontal RecyclerView.\nHere is the code in MainActivity.java to add the first RecyclerView:Java import androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; \nimport android.os.Bundle; \nimport android.widget.LinearLayout; \nimport android.widget.TextView; \nimport com.wheic.recyclergetsout.RV1.RVOneAdapter; \nimport com.wheic.recyclergetsout.RV1.RVOneModel; \nimport java.util.ArrayList; \nimport java.util.List; public class MainActivity extends AppCompatActivity { // reference for the Main-List RecyclerView \nprivate RecyclerView RVOne; \n// Main-list item titles will be stored here \nprivate List tutorialList; \n// reference for the RVOneAdapter class \nprivate RVOneAdapter rvOneAdapter; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Linked up with its respective id \n// used in the activity_main.xml \nRVOne = findViewById(R.id.recyclerViewOne); \nRVTwo = findViewById(R.id.recyclerViewTwo); // Setting the Main-List RecyclerView horizontally \nRVOne.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false)); tutorialList = new ArrayList<>(); // Static data are stored one by one in the tutorialList arrayList \ntutorialList.add(new RVOneModel(\"Algorithms\", 1)); \ntutorialList.add(new RVOneModel(\"Data Structures\", 2)); \ntutorialList.add(new RVOneModel(\"Languages\", 3)); \ntutorialList.add(new RVOneModel(\"Interview Corner\", 4)); \ntutorialList.add(new RVOneModel(\"GATE\", 5)); \ntutorialList.add(new RVOneModel(\"ISRO CS\", 6)); \ntutorialList.add(new RVOneModel(\"UGC NET CS\", 7)); \ntutorialList.add(new RVOneModel(\"CS Subjects\", 8)); \ntutorialList.add(new RVOneModel(\"Web Technologies\", 9)); rvOneAdapter = new RVOneAdapter(tutorialList); \nRVOne.setAdapter(rvOneAdapter); \n} \n}Step 5: Set up the clickListener for each item in the horizontal RecyclerView:The next 4 steps are done in RVOneAdapater.java\nFirst, an interface is created in RVOneAdapater.java for each item click with an onItemClick abstract method.Java // Interface to perform events on Main-List item click \npublic interface OnItemsClickListener{ \nvoid onItemClick(RVOneModel rvOneModel); \n}A reference variable of the interface is created.Java // Need this for the Main-list item onClick events \nprivate OnItemsClickListener listener;A method setWhenClickListener is created that will be called from the MainActivity.Java // Main-list item clickListener is initialized \n// This will be used in MainActivity \npublic void setWhenClickListener(OnItemsClickListener listener){ \nthis.listener = listener; \n}Now, inside onBindViewHolder, a setOnClickListener is created that will actually call the onItemClick method when a single item in the horizontal RecyclerView is clicked.Java holder.singleItemCardView.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \nif(listener != null){ \nlistener.onItemClick(modelItems); \n} \n} \n});In MainActivity.java, a reference variable is made for the TextView and it is attached with the XML file using the corresponding id.Java algorithmTitleText = findViewById(R.id.algorithmTitleText);Now, adapter setOnClickListener is called and the textView text change event will occur when a single list-item is clicked.Java rvOneAdapter.setWhenClickListener(new RVOneAdapter.OnItemsClickListener() { \n@Override\npublic void onItemClick(RVOneModel rvOneModel) { \nalgorithmTitleText.setText(rvOneModel.getName()); \nsetRVTwoList(rvOneModel.getNum()); \n} \n});Step 6: Work on the vertical RecyclerView or the sub-listGo to java -> com.wheic.recyclergetsout (Your\u2019s may differ)\nJust like the previous one, a directory is made. I named it RV2.Start working on the model class for the sub-list:Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. for me it\u2019s RVTwoModel.\nAs per this app, in this model class, only one String variable is necessary. The String variable will store the title text of the sub-list item. Then just like the previous one a constructor and a getter function are created.\nHere\u2019s the java code of the model class.Java public class RVTwoModel { \n// this variable will store sub-list item title \nprivate String name; // parameterized constructor \npublic RVTwoModel(String name) { \nthis.name = name; \n} // getter function for the name variable \npublic String getName() { \nreturn name; \n} \n}Start working on the Adapter class for the vertical RecyclerView:Right-click on the just created folder (RV2) -> New -> Java Class. Give the name of the class. I named it RVTwoAdapter.\nJust like any other RecyclerView, this adapter class is also not that different.\nHere\u2019s the java code of this Adapter class and the ViewHolder class:Java import android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; \nimport androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; \nimport com.wheic.recyclergetsout.R; \nimport java.util.List; public class RVTwoAdapter extends RecyclerView.Adapter { // Sub-list item titles will be stored here \nprivate List tutorialSubList; // Parameterized constructor of this class \n// to initialize tutorialSubList \npublic RVTwoAdapter(List tutorialSubList) { \nthis.tutorialSubList = tutorialSubList; \n} // Attach the item layout with the proper xml file \n@NonNull\n@Override\npublic RVTwoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout_vertical, parent, false); \nreturn new ViewHolder(view); \n} // It deals with the setting of different data and methods \n@Override\npublic void onBindViewHolder(@NonNull RVTwoAdapter.ViewHolder holder, int position) { \nholder.setData(tutorialSubList.get(position).getName()); \n} // It returns the length of the RecyclerView \n@Override\npublic int getItemCount() { \nreturn tutorialSubList.size(); \n} // The ViewHolder is a java class that stores \n// the reference to the item layout views \npublic class ViewHolder extends RecyclerView.ViewHolder{ public TextView rvTwoText; // Link up the Sub-List items layout \n// components with their respective id \npublic ViewHolder(@NonNull View itemView) { \nsuper(itemView); \nrvTwoText = itemView.findViewById(R.id.singleItemTextViewRVTwo); \n} // setText in Sub-List title text \npublic void setData(String name){ \nthis.rvTwoText.setText(name); \n} \n} \n}Let\u2019s finish the code in MainActivity.java:A second ArrayList tutorialSubList for the sub-list is needed. So a reference variable of a second ArrayList is created.Java // Sub-list item titles will be stored here \nprivate List tutorialSubList;A function is created just for the vertical recyclerView, which takes an integer parameter.\nThe static data is added in the ArrayList for each main-list item.Here is the code for the function:Java private void setRVTwoList(int num){ // Setting the Sub-List RecyclerView vertically \nRVTwo.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); // Previous tutorialSubList will be deleted \n// and new memory will be allocated \ntutorialSubList = new ArrayList<>(); // Static data are stored one by one in the \n// tutorialSubList arrayList for each Main-List items \nif (num == 1) { tutorialSubList.add(new RVTwoModel(\"Searching Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Sorting Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Graph Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Pattern Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Geometric Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Mathematical\")); \ntutorialSubList.add(new RVTwoModel(\"Randomized Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Greedy Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Dynamic Programming\")); \ntutorialSubList.add(new RVTwoModel(\"Divide and Conquer\")); \ntutorialSubList.add(new RVTwoModel(\"Backtracking\")); \ntutorialSubList.add(new RVTwoModel(\"Branch and Bound\")); \ntutorialSubList.add(new RVTwoModel(\"All Algorithms\")); } else if (num == 2){ tutorialSubList.add(new RVTwoModel(\"Arrays\")); \ntutorialSubList.add(new RVTwoModel(\"Linked List\")); \ntutorialSubList.add(new RVTwoModel(\"Stack\")); \ntutorialSubList.add(new RVTwoModel(\"Queue\")); \ntutorialSubList.add(new RVTwoModel(\"Binary Tree\")); \ntutorialSubList.add(new RVTwoModel(\"Binary Search Tree\")); \ntutorialSubList.add(new RVTwoModel(\"Heap\")); \ntutorialSubList.add(new RVTwoModel(\"Hashing\")); \ntutorialSubList.add(new RVTwoModel(\"Graph\")); \ntutorialSubList.add(new RVTwoModel(\"Advanced Data Structure\")); \ntutorialSubList.add(new RVTwoModel(\"Matrix\")); \ntutorialSubList.add(new RVTwoModel(\"Strings\")); \ntutorialSubList.add(new RVTwoModel(\"All Data Structures\")); } else if (num == 3){ tutorialSubList.add(new RVTwoModel(\"C\")); \ntutorialSubList.add(new RVTwoModel(\"C++\")); \ntutorialSubList.add(new RVTwoModel(\"Java\")); \ntutorialSubList.add(new RVTwoModel(\"Python\")); \ntutorialSubList.add(new RVTwoModel(\"C#\")); \ntutorialSubList.add(new RVTwoModel(\"Javascript\")); \ntutorialSubList.add(new RVTwoModel(\"JQuery\")); \ntutorialSubList.add(new RVTwoModel(\"SQL\")); \ntutorialSubList.add(new RVTwoModel(\"PHP\")); \ntutorialSubList.add(new RVTwoModel(\"Scala\")); \ntutorialSubList.add(new RVTwoModel(\"Perl\")); \ntutorialSubList.add(new RVTwoModel(\"GO Language\")); \ntutorialSubList.add(new RVTwoModel(\"HTML\")); \ntutorialSubList.add(new RVTwoModel(\"CSS\")); \ntutorialSubList.add(new RVTwoModel(\"Kotlin\")); } else if (num == 4){ tutorialSubList.add(new RVTwoModel(\"Company Preparation\")); \ntutorialSubList.add(new RVTwoModel(\"Top Topics\")); \ntutorialSubList.add(new RVTwoModel(\"Practice Company Questions\")); \ntutorialSubList.add(new RVTwoModel(\"Interview Experiences\")); \ntutorialSubList.add(new RVTwoModel(\"Experienced Interviews\")); \ntutorialSubList.add(new RVTwoModel(\"Internship Interviews\")); \ntutorialSubList.add(new RVTwoModel(\"Competitive Programming\")); \ntutorialSubList.add(new RVTwoModel(\"Design Patterns\")); \ntutorialSubList.add(new RVTwoModel(\"Multiple Choice Quizzes\")); } else if (num == 5){ tutorialSubList.add(new RVTwoModel(\"GATE CS Notes 2021\")); \ntutorialSubList.add(new RVTwoModel(\"Last Minute Notes\")); \ntutorialSubList.add(new RVTwoModel(\"GATE CS Solved Papers\")); \ntutorialSubList.add(new RVTwoModel(\"GATE CS Original Papers and Official Keys\")); \ntutorialSubList.add(new RVTwoModel(\"GATE 2021 Dates\")); \ntutorialSubList.add(new RVTwoModel(\"GATE CS 2021 Syllabus\")); \ntutorialSubList.add(new RVTwoModel(\"Important Topics for GATE CS\")); \ntutorialSubList.add(new RVTwoModel(\"Sudo GATE 2021\")); } else if (num == 6){ tutorialSubList.add(new RVTwoModel(\"ISRO CS Solved Papers\")); \ntutorialSubList.add(new RVTwoModel(\"ISRO CS Original Papers and Official Keys\")); \ntutorialSubList.add(new RVTwoModel(\"ISRO CS Syllabus for Scientist/Engineer Exam\")); } else if (num == 7){ \ntutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper II\")); \ntutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper III\")); \ntutorialSubList.add(new RVTwoModel(\"UGC NET CS Solved Papers\")); } else if (num == 8){ tutorialSubList.add(new RVTwoModel(\"Mathematics\")); \ntutorialSubList.add(new RVTwoModel(\"Operating System\")); \ntutorialSubList.add(new RVTwoModel(\"DBMS\")); \ntutorialSubList.add(new RVTwoModel(\"Computer Networks\")); \ntutorialSubList.add(new RVTwoModel(\"Computer Organization and Architecture\")); \ntutorialSubList.add(new RVTwoModel(\"Theory of Computation\")); \ntutorialSubList.add(new RVTwoModel(\"Compiler Design\")); \ntutorialSubList.add(new RVTwoModel(\"Digital Logic\")); \ntutorialSubList.add(new RVTwoModel(\"Software Engineering\")); } else if (num == 9){ tutorialSubList.add(new RVTwoModel(\"HTML\")); \ntutorialSubList.add(new RVTwoModel(\"CSS\")); \ntutorialSubList.add(new RVTwoModel(\"Javascript\")); \ntutorialSubList.add(new RVTwoModel(\"jQuery\")); \ntutorialSubList.add(new RVTwoModel(\"PHP\")); } rvTwoAdapter = new RVTwoAdapter(tutorialSubList); \nRVTwo.setAdapter(rvTwoAdapter); \n}Inside onCreate(), the setRVTwo() function is called in the main-list item clickListener. Also, it is called outside because we need to see the sub-list just when the activity gets created.Java // The app will show Algorithms Sub-List \n// every time the activity starts \nalgorithmTitleText.setText(\"Algorithms\"); \nsetRVTwoList(1);Here are every final JAVA codes of this project:\nMainActivity.javaJava import androidx.appcompat.app.AppCompatActivity; \nimport androidx.recyclerview.widget.LinearLayoutManager; \nimport androidx.recyclerview.widget.RecyclerView; \nimport android.os.Bundle; \nimport android.widget.LinearLayout; \nimport android.widget.TextView; \nimport com.wheic.recyclergetsout.RV1.RVOneAdapter; \nimport com.wheic.recyclergetsout.RV1.RVOneModel; \nimport com.wheic.recyclergetsout.RV2.RVTwoAdapter; \nimport com.wheic.recyclergetsout.RV2.RVTwoModel; \nimport java.util.ArrayList; \nimport java.util.List; public class MainActivity extends AppCompatActivity { // reference for the Main-List RecyclerView \nprivate RecyclerView RVOne; \n// reference for the Sub-List RecyclerView \nprivate RecyclerView RVTwo; \n// Main-list item titles will be stored here \nprivate List tutorialList; \n// Sub-list item titles will be stored here \nprivate List tutorialSubList; \n// reference for the RVOneAdapter class \nprivate RVOneAdapter rvOneAdapter; \n// reference for the RVTwoAdapter class \nprivate RVTwoAdapter rvTwoAdapter; \n// TextView to show the title of the clicked Main-List item \nprivate TextView algorithmTitleText; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Linked up with its respective id used in the activity_main.xml \nRVOne = findViewById(R.id.recyclerViewOne); \nRVTwo = findViewById(R.id.recyclerViewTwo); \nalgorithmTitleText = findViewById(R.id.algorithmTitleText); // Setting the Main-List RecyclerView horizontally \nRVOne.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false)); tutorialList = new ArrayList<>(); // Static data are stored one by one in the tutorialList arrayList \ntutorialList.add(new RVOneModel(\"Algorithms\", 1)); \ntutorialList.add(new RVOneModel(\"Data Structures\", 2)); \ntutorialList.add(new RVOneModel(\"Languages\", 3)); \ntutorialList.add(new RVOneModel(\"Interview Corner\", 4)); \ntutorialList.add(new RVOneModel(\"GATE\", 5)); \ntutorialList.add(new RVOneModel(\"ISRO CS\", 6)); \ntutorialList.add(new RVOneModel(\"UGC NET CS\", 7)); \ntutorialList.add(new RVOneModel(\"CS Subjects\", 8)); \ntutorialList.add(new RVOneModel(\"Web Technologies\", 9)); // The app will show Algorithms Sub-List every time the activity starts \nalgorithmTitleText.setText(\"Algorithms\"); \nsetRVTwoList(1); rvOneAdapter = new RVOneAdapter(tutorialList); \nRVOne.setAdapter(rvOneAdapter); // Setting up the events that will occur on each Main-List item click \nrvOneAdapter.setWhenClickListener(new RVOneAdapter.OnItemsClickListener() { \n@Override\npublic void onItemClick(RVOneModel rvOneModel) { \nalgorithmTitleText.setText(rvOneModel.getName()); \nsetRVTwoList(rvOneModel.getNum()); \n} \n}); } private void setRVTwoList(int num){ // Setting the Sub-List RecyclerView vertically \nRVTwo.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false)); // Previous tutorialSubList will be deleted and new memory will be allocated \ntutorialSubList = new ArrayList<>(); // Static data are stored one by one in the tutorialSubList arrayList for each Main-List items \nif (num == 1) { tutorialSubList.add(new RVTwoModel(\"Searching Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Sorting Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Graph Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Pattern Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Geometric Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Mathematical\")); \ntutorialSubList.add(new RVTwoModel(\"Randomized Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Greedy Algorithms\")); \ntutorialSubList.add(new RVTwoModel(\"Dynamic Programming\")); \ntutorialSubList.add(new RVTwoModel(\"Divide and Conquer\")); \ntutorialSubList.add(new RVTwoModel(\"Backtracking\")); \ntutorialSubList.add(new RVTwoModel(\"Branch and Bound\")); \ntutorialSubList.add(new RVTwoModel(\"All Algorithms\")); } else if (num == 2){ tutorialSubList.add(new RVTwoModel(\"Arrays\")); \ntutorialSubList.add(new RVTwoModel(\"Linked List\")); \ntutorialSubList.add(new RVTwoModel(\"Stack\")); \ntutorialSubList.add(new RVTwoModel(\"Queue\")); \ntutorialSubList.add(new RVTwoModel(\"Binary Tree\")); \ntutorialSubList.add(new RVTwoModel(\"Binary Search Tree\")); \ntutorialSubList.add(new RVTwoModel(\"Heap\")); \ntutorialSubList.add(new RVTwoModel(\"Hashing\")); \ntutorialSubList.add(new RVTwoModel(\"Graph\")); \ntutorialSubList.add(new RVTwoModel(\"Advanced Data Structure\")); \ntutorialSubList.add(new RVTwoModel(\"Matrix\")); \ntutorialSubList.add(new RVTwoModel(\"Strings\")); \ntutorialSubList.add(new RVTwoModel(\"All Data Structures\")); } else if (num == 3){ tutorialSubList.add(new RVTwoModel(\"C\")); \ntutorialSubList.add(new RVTwoModel(\"C++\")); \ntutorialSubList.add(new RVTwoModel(\"Java\")); \ntutorialSubList.add(new RVTwoModel(\"Python\")); \ntutorialSubList.add(new RVTwoModel(\"C#\")); \ntutorialSubList.add(new RVTwoModel(\"Javascript\")); \ntutorialSubList.add(new RVTwoModel(\"JQuery\")); \ntutorialSubList.add(new RVTwoModel(\"SQL\")); \ntutorialSubList.add(new RVTwoModel(\"PHP\")); \ntutorialSubList.add(new RVTwoModel(\"Scala\")); \ntutorialSubList.add(new RVTwoModel(\"Perl\")); \ntutorialSubList.add(new RVTwoModel(\"GO Language\")); \ntutorialSubList.add(new RVTwoModel(\"HTML\")); \ntutorialSubList.add(new RVTwoModel(\"CSS\")); \ntutorialSubList.add(new RVTwoModel(\"Kotlin\")); } else if (num == 4){ tutorialSubList.add(new RVTwoModel(\"Company Preparation\")); \ntutorialSubList.add(new RVTwoModel(\"Top Topics\")); \ntutorialSubList.add(new RVTwoModel(\"Practice Company Questions\")); \ntutorialSubList.add(new RVTwoModel(\"Interview Experiences\")); \ntutorialSubList.add(new RVTwoModel(\"Experienced Interviews\")); \ntutorialSubList.add(new RVTwoModel(\"Internship Interviews\")); \ntutorialSubList.add(new RVTwoModel(\"Competitive Programming\")); \ntutorialSubList.add(new RVTwoModel(\"Design Patterns\")); \ntutorialSubList.add(new RVTwoModel(\"Multiple Choice Quizzes\")); } else if (num == 5){ tutorialSubList.add(new RVTwoModel(\"GATE CS Notes 2021\")); \ntutorialSubList.add(new RVTwoModel(\"Last Minute Notes\")); \ntutorialSubList.add(new RVTwoModel(\"GATE CS Solved Papers\")); \ntutorialSubList.add(new RVTwoModel(\"GATE CS Original Papers and Official Keys\")); \ntutorialSubList.add(new RVTwoModel(\"GATE 2021 Dates\")); \ntutorialSubList.add(new RVTwoModel(\"GATE CS 2021 Syllabus\")); \ntutorialSubList.add(new RVTwoModel(\"Important Topics for GATE CS\")); \ntutorialSubList.add(new RVTwoModel(\"Sudo GATE 2021\")); } else if (num == 6){ tutorialSubList.add(new RVTwoModel(\"ISRO CS Solved Papers\")); \ntutorialSubList.add(new RVTwoModel(\"ISRO CS Original Papers and Official Keys\")); \ntutorialSubList.add(new RVTwoModel(\"ISRO CS Syllabus for Scientist/Engineer Exam\")); } else if (num == 7){ \ntutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper II\")); \ntutorialSubList.add(new RVTwoModel(\"UGC NET CS Notes Paper III\")); \ntutorialSubList.add(new RVTwoModel(\"UGC NET CS Solved Papers\")); } else if (num == 8){ tutorialSubList.add(new RVTwoModel(\"Mathematics\")); \ntutorialSubList.add(new RVTwoModel(\"Operating System\")); \ntutorialSubList.add(new RVTwoModel(\"DBMS\")); \ntutorialSubList.add(new RVTwoModel(\"Computer Networks\")); \ntutorialSubList.add(new RVTwoModel(\"Computer Organization and Architecture\")); \ntutorialSubList.add(new RVTwoModel(\"Theory of Computation\")); \ntutorialSubList.add(new RVTwoModel(\"Compiler Design\")); \ntutorialSubList.add(new RVTwoModel(\"Digital Logic\")); \ntutorialSubList.add(new RVTwoModel(\"Software Engineering\")); } else if (num == 9){ tutorialSubList.add(new RVTwoModel(\"HTML\")); \ntutorialSubList.add(new RVTwoModel(\"CSS\")); \ntutorialSubList.add(new RVTwoModel(\"Javascript\")); \ntutorialSubList.add(new RVTwoModel(\"jQuery\")); \ntutorialSubList.add(new RVTwoModel(\"PHP\")); } rvTwoAdapter = new RVTwoAdapter(tutorialSubList); \nRVTwo.setAdapter(rvTwoAdapter); \n} \n}RVOneAdapter.javaJava import android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; \nimport androidx.annotation.NonNull; \nimport androidx.cardview.widget.CardView; \nimport androidx.recyclerview.widget.RecyclerView; \nimport com.wheic.recyclergetsout.R; \nimport java.util.List; public class RVOneAdapter extends RecyclerView.Adapter { // Main-list item titles will be stored here \nprivate List tutorialList; // Need this clickListener for the Main-list item onClick events \nprivate OnItemsClickListener listener; // Parameterized constructor of this class to initialize tutorialList \npublic RVOneAdapter(List tutorialList) { \nthis.tutorialList = tutorialList; } // Main-list item clickListener is initialized \n// This will be used in MainActivity \npublic void setWhenClickListener(OnItemsClickListener listener){ \nthis.listener = listener; \n} // Attach the item layout with the proper xml file \n@NonNull\n@Override\npublic ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout, parent, false); \nreturn new ViewHolder(view); \n} // It deals with the setting of different data and methods \n@Override\npublic void onBindViewHolder(@NonNull ViewHolder holder, int position) { \nfinal RVOneModel modelItems = tutorialList.get(position); \nholder.setData(tutorialList.get(position).getName()); \nholder.singleItemCardView.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \nif(listener != null){ \nlistener.onItemClick(modelItems); \n} \n} \n}); \n} // It returns the length of the RecyclerView \n@Override\npublic int getItemCount() { \nreturn tutorialList.size(); \n} // The ViewHolder is a java class that stores \n// the reference to the item layout views \npublic class ViewHolder extends RecyclerView.ViewHolder{ public CardView singleItemCardView; \npublic TextView singleItemTextView; // Link up the Main-List items layout components with their respective id \npublic ViewHolder(@NonNull View itemView) { \nsuper(itemView); \nsingleItemCardView = itemView.findViewById(R.id.singleItemCardView); \nsingleItemTextView = itemView.findViewById(R.id.singleItemTextView); \n} // setText in Main-List title text \npublic void setData(String name){ \nthis.singleItemTextView.setText(name); \n} \n} // Interface to perform events on Main-List item click \npublic interface OnItemsClickListener{ \nvoid onItemClick(RVOneModel rvOneModel); \n} \n}RVOneModel.javaJava public class RVOneModel { \n// this variable will store main-list item title \nprivate String name; \n// this will help differentiate between the main-list items \nprivate int num; // parameterized constructor \npublic RVOneModel(String name, int num) { \nthis.name = name; \nthis.num = num; \n} // getter functions for these two variables \npublic String getName() { \nreturn name; \n} public int getNum() { \nreturn num; \n} \n}RVTwoAdapter.javaJava import android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.TextView; \nimport androidx.annotation.NonNull; \nimport androidx.recyclerview.widget.RecyclerView; \nimport com.wheic.recyclergetsout.R; \nimport java.util.List; public class RVTwoAdapter extends RecyclerView.Adapter { // Sub-list item titles will be stored here \nprivate List tutorialSubList; // Parameterized constructor of this \n// class to initialize tutorialSubList \npublic RVTwoAdapter(List tutorialSubList) { \nthis.tutorialSubList = tutorialSubList; \n} // Attach the item layout with the proper xml file \n@NonNull\n@Override\npublic RVTwoAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { \nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.single_card_layout_vertical, parent, false); \nreturn new ViewHolder(view); \n} // It deals with the setting of different data and methods \n@Override\npublic void onBindViewHolder(@NonNull RVTwoAdapter.ViewHolder holder, int position) { \nholder.setData(tutorialSubList.get(position).getName()); \n} // It returns the length of the RecyclerView \n@Override\npublic int getItemCount() { \nreturn tutorialSubList.size(); \n} // The ViewHolder is a java class that stores \n// the reference to the item layout views \npublic class ViewHolder extends RecyclerView.ViewHolder{ public TextView rvTwoText; // Link up the Sub-List items layout components with their respective id \npublic ViewHolder(@NonNull View itemView) { \nsuper(itemView); \nrvTwoText = itemView.findViewById(R.id.singleItemTextViewRVTwo); \n} // setText in Sub-List title text \npublic void setData(String name){ \nthis.rvTwoText.setText(name); \n} \n} \n}RVTwoModel.javaJava public class RVTwoModel { \n// this variable will store sub-list item title \nprivate String name; // parameterized constructor \npublic RVTwoModel(String name) { \nthis.name = name; \n} // getter function for the name variable \npublic String getName() { \nreturn name; \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20201205225318/Output.mp4\nYou can check this project from this GitHub link."}, {"text": "\nInteresting Facts About Android\n\nAndroid is a Mobile Operating System that was released on 23, September 2008. Android is free, open-source operating system and is based on modified version of Linux kernel. Open Handset Alliance (OHA) developed the Android and Google commercially sponsored it. It is mainly designed for touchscreen devices such as smartphones and tablets. Android is supported on different platforms like 32- and 64-bit ARM, x86, and x86-64. Android is available in more than 100 languages with Graphical (multi-touch) as the default user interface.Journey of ANDROID from first version to latest version:Android 1.0 (2008) \u2013 No Version Name\nAndroid 1.1 2009) \u2013 Petit Four\nAndroid 1.5 (2009) \u2013 Cupcake\nAndroid 1.6 (2009) \u2013 Donut\nAndroid 2.0 \u2013 2.1 (2009) \u2013 \u00c9clair\nAndroid 2.2 \u2013 2.2.3 (2010) \u2013 Froyo\nAndroid 2.3 \u2013 2.3.7 (2010) \u2013 Gingerbread\nAndroid 3.0 \u2013 3.2.6 (2011) \u2013 Honeycomb\nAndroid 4.0 \u2013 4.0.4 (2011) \u2013 Ice Cream Sandwich\nAndroid 4.1 \u2013 4.3.1 (2012) \u2013 Jelly Bean\nAndroid 4.4 \u2013 4.4.4 (2013) \u2013 KitKat\nAndroid 5.0 \u2013 5.1.1 (2014) \u2013 Lollipop\nAndroid 6.0 \u2013 6.0.1 (2015) \u2013 Marshmallow\nAndroid 7.0 \u2013 7.1.2 (2016) \u2013 Nougat\nAndroid 8.0 \u2013 8.1 (2017) \u2013 Oreo\nAndroid 9.0 (2018) \u2013 Pie\nAndroid 10 (2019) \u2013 Android 10Here are some facts about Android :Android\u2019s creator is Andy Rubin.\nAndroid Inc. developed Android operating system and Google bought it in 2005, with a huge amount of $50 million.\nPrior to Google, an offer was given to Samsung to buy Android Inc. but they find Android uninteresting and reject the offer.\nInitially, Android was developed as an operating system for digital cameras but later on, it focuses on Smart Phones.\nAndroid is written in many languages like Java, C, C++, XML, Assembly language, Python, Shell script, Go, Make, D.\nHTC Dream or T-Mobile G1 was the first smartphone that runs on Android operating system.\nHTC Dream or T-Mobile G1 was launched in 2008 with no headphone jack and required an adapter.\nAndroid captures 88% of total smart phone market whereas IOS captures 11% market share.\nCurrently, more than 2 billion smart devices use Google Android OS as their operating system.\nThe word Android refers to a male robot, whereas a female robot is known as \u201cGynoid\u201c.\nAndroid is an open source software, which means its source code is freely available. Anyone can modify the source code and add new & unique features.\nAll Android versions are named in alphabetical order, along with the name of sweet deserts associated with that alphabet like Cupcake, Donut etc.\nThe Logging System of Android has a method named as \u201cwtf()\u201d which stands for \u201cWhat a Terrible Failure\u201d.\nIn 2010, Anssi Vanjoki, CEO of Nokia, made a hilarious comment on Android. He said the use of Android is like a Finnish boy peeing his pants to stay warm.\nAndroid\u2019s Google Store has more than 48 billion apps installed in it, and most of them are free of cost.\nNASA once used Nexus S handsets (device based on Android Gingerbread), in their floating space Robots.\nThe sale of Android devices is more than the combined sale of Microsoft Windows, iOS, and Mac OS devices.\nMicrosoft earns around $2 billion yearly in patent royalties, from the sale of Android devices.\nEven Google Maps uses the speed of Android Mobiles to calculate the traffic on roads.\nGoogle had to make a deal with Nestle in order to use the name \u201cKit-Kat\u201d for Android version 4.4."}, {"text": "\nHow to Share a Captured Image to Another Application in Android?\n\nPre-requisite: How to open a Camera through Intent and capture an image\nIn this article, we will try to send the captured image (from this article) to other apps using Android Studio.\nApproach: The image captured gets stored on the external storage. Hence we need to request permission to access the files from the user. So take permission to access external storage permission in the manifest file.\nHere pictureDir(File) is pointing to the directory of external storage named DIRECTORY_PICTURESFile pictureDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),\u201dCameraDemo\u201d);In the onCreate() method, check whether the directory pictureDir is present or not. If not then create the directory with the code below\nif(!pictureDir.exists()) {\n pictureDir.mkdirs();\n}\nCreate another method called callCameraApp() to get the clicked image from external storage.Capture the image using Intent\nCreate a file to store the image in the pictureDir directory.\nGet the URI object of this image file\nPut the image on the Intent storage to be accessed from other modules of the app.\nPass the image through intent to startActivityForResult()Share this image to other apps using intent.\nIntent emailIntent = new Intent(android.content.Intent.ACTION_SEND);\nFor the sake of this article, we will be selecting Gmail and will be sending this image as an attachment in a mail.\nstartActivity(Intent.createChooser(emailIntent, \"Send mail...\"));\nBelow is the Complete Implementation of the above Approach:\nStep By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Adding the Required Permissions in the Manifest File\nNavigate to the app > AndroidManifest.xml file and add the below permissions to it.\n \nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n \n \n \n Step 4: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.Manifest; \nimport android.content.Intent; \nimport android.content.pm.PackageManager; \nimport android.net.Uri; \nimport android.os.Bundle; \nimport android.os.Environment; \nimport android.provider.MediaStore; \nimport android.view.View; \nimport android.widget.ImageView; \nimport android.widget.Toast; \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \nimport androidx.core.app.ActivityCompat; \nimport androidx.core.content.ContextCompat; \nimport java.io.File; public class MainActivity extends AppCompatActivity { private static final int CAMERA_PIC_REQUEST = 1337; \nprivate static final int REQUEST_EXTERNAL_STORAGE_RESULT = 1; \nprivate static final String FILE_NAME = \"image01.jpg\"; \nprivate ImageView img1; File pictureDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), \"CameraDemo\"); \nprivate Uri fileUri; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); img1 = findViewById(R.id.imageView1); \nif (!pictureDir.exists()) { \npictureDir.mkdirs(); \n} \n} // Open the camera app to capture the image \npublic void callCameraApp() { \nIntent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); \nFile image = new File(pictureDir, FILE_NAME); \nfileUri = Uri.fromFile(image); \nintent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); \nstartActivityForResult(intent, CAMERA_PIC_REQUEST); \n} public void takePicture(View view) { \nif (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { \ncallCameraApp(); \n} else { \nif (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { \nToast.makeText(this, \"External storage permission\" + \" required to save images\", Toast.LENGTH_SHORT).show(); \n} \nActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE_RESULT); \n} \n} protected void onActivityResult(int requestCode, int resultCode, Intent data) { \nsuper.onActivityResult(requestCode, resultCode, data); if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) { \nImageView imageView = findViewById(R.id.imageView1); \nFile image = new File(pictureDir, FILE_NAME); \nfileUri = Uri.fromFile(image); \nimageView.setImageURI(fileUri); \nemailPicture(); \n} else if (resultCode == RESULT_CANCELED) { \nToast.makeText(this, \"You did not click the photo\", Toast.LENGTH_SHORT).show(); \n} \n} @Override\npublic void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { \nif (requestCode == REQUEST_EXTERNAL_STORAGE_RESULT) { \nif (grantResults[0] == PackageManager.PERMISSION_GRANTED) { \ncallCameraApp(); \n} else { \nToast.makeText(this, \"External write permission\" + \" has not been granted, \" + \" cannot saved images\", Toast.LENGTH_SHORT).show(); \n} \n} else { \nsuper.onRequestPermissionsResult(requestCode, permissions, grantResults); \n} \n} // Function to send the image through mail \npublic void emailPicture() { \nToast.makeText(this, \"Now, sending the mail\", Toast.LENGTH_LONG).show(); \nIntent emailIntent = new Intent(android.content.Intent.ACTION_SEND); \nemailIntent.setType(\"application/image\"); \nemailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ \n// default receiver id \n\"enquiry@geeksforgeeks.org\"}); \n// Subject of the mail \nemailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, \"New photo\"); \n// Body of the mail \nemailIntent.putExtra(android.content.Intent.EXTRA_TEXT, \"Here's a captured image\"); \n// Set the location of the image file to be added as an attachment \nemailIntent.putExtra(Intent.EXTRA_STREAM, fileUri); \n// Start the email activity to with the prefilled information \nstartActivity(Intent.createChooser(emailIntent, \"Send mail...\")); \n} \n}Kotlin import android.Manifest \nimport android.content.Intent \nimport android.content.pm.PackageManager \nimport android.net.Uri \nimport android.os.Build \nimport android.os.Bundle \nimport android.os.Environment \nimport android.provider.MediaStore \nimport android.widget.ImageView \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.core.app.ActivityCompat \nimport androidx.core.content.ContextCompat \nimport java.io.File class MainActivity : AppCompatActivity() { companion object { \nprivate const val CAMERA_PIC_REQUEST = 1337\nprivate const val REQUEST_EXTERNAL_STORAGE_RESULT = 1\nprivate const val FILE_NAME = \"image01.jpg\"\n} private lateinit var img1: ImageView \nprivate lateinit var fileUri: Uri \nvar pictureDir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { \nFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), \"CameraDemo\") \n} else { \nTODO(\"VERSION.SDK_INT < FROYO\") \n} override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \nimg1 = findViewById(R.id.imageView1) \nif (!pictureDir.exists()) { \npictureDir.mkdirs() \n} \n} // Open the camera app to capture the image \nprivate fun callCameraApp() { \nval image = File(pictureDir, FILE_NAME) \nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) { \nval intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) \nfileUri = Uri.fromFile(image) \nintent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri) \nstartActivityForResult(intent, CAMERA_PIC_REQUEST) \n} else { \nTODO(\"VERSION.SDK_INT < CUPCAKE\") \n} \n} fun takePicture() { \nif (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { \ncallCameraApp() \n} else { \nif (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { \nToast.makeText(this, \"External storage permission\" + \" required to save images\", Toast.LENGTH_SHORT).show() \n} \nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) { \nActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_EXTERNAL_STORAGE_RESULT) \n} \n} \n} override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { \nsuper.onActivityResult(requestCode, resultCode, data) \nif (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) { \nval imageView = findViewById(R.id.imageView1) \nval image = File(pictureDir, FILE_NAME) \nfileUri = Uri.fromFile(image) \nimageView.setImageURI(fileUri) \nemailPicture() \n} else if (resultCode == RESULT_CANCELED) { \nToast.makeText(this, \"You did not click the photo\", Toast.LENGTH_SHORT).show() \n} \n} override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { \nif (requestCode == REQUEST_EXTERNAL_STORAGE_RESULT) { \nif (grantResults[0] == PackageManager.PERMISSION_GRANTED) { \ncallCameraApp() \n} else { \nToast.makeText(this, \"External write permission\" + \" has not been granted, \" + \" cannot saved images\", Toast.LENGTH_SHORT).show() \n} \n} else { \nsuper.onRequestPermissionsResult(requestCode, permissions, grantResults) \n} \n} // Function to send the image through mail \nprivate fun emailPicture() { \nToast.makeText(this, \"Now, sending the mail\", Toast.LENGTH_LONG).show() \nval emailIntent = Intent(Intent.ACTION_SEND) \nemailIntent.type = \"application/image\"\n// default receiver id \nemailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(\"enquiry@geeksforgeeks.org\")) \n// Subject of the mail \nemailIntent.putExtra(Intent.EXTRA_SUBJECT, \"New photo\") \n// Body of the mail \nemailIntent.putExtra(Intent.EXTRA_TEXT, \"Here's a captured image\") \n// Set the location of the image file to be added as an attachment \nemailIntent.putExtra(Intent.EXTRA_STREAM, fileUri) \n// Start the email activity to with the prefilled information \nstartActivity(Intent.createChooser(emailIntent, \"Send mail...\")) \n} \n}"}, {"text": "\nOverview of Google Admob\n\nIn order to earn money from the Android app or game, there are several ways such as in-App Purchases, Sponsorship, Advertisements, and many more. But there is another conventional approach to earn money from the Android app is by integrating an advertisement which is known as Google AdMob. Google AdMob is created with developers in mind, AdMob helps to make more app revenue, deliver better user experience, and surface actionable insights all with automated tools that do the hard work for you.\nWhy Google AdMob?Minimum Payout is $100\nWide Range of Ad Formats\nMaximum Fill Rates\nHigh eCPM(Effective Cost Per Mille)\nQuality Ads\nPersonalized AdsAdvantages of Google AdMobSmarter tech, more revenue: As one of the largest global ad networks, AdMob can fill the ad requests from anywhere in the world. Maximize the value of each track across all the networks with the most excellent monetization technology.\nActionable analytics: Make more intelligent decisions to grow mobile app earnings and enhance customer experience. AdMob\u2019s robust reporting and measurement features deliver deeper insights into how the users are interacting with the mobile app and ads. Earn even richer insights by instantly integrating Google Analytics for Firebase with AdMob.\nHigh-performing ad formats: Engage and retain users with innovative ad formats. Customize the UX and gain more revenue by integrating native, rewarded, banner, video, and interstitial ads seamlessly into the app.\nAutomated tools: Streamline day-to-day tasks with automated tools. Easy to set up and integrate, the tools offer everything from state-of-the-art brand safety controls to advanced monetization technology with mediation and Open Bidding.Formats of Google AdMob\nThere are mainly four types of resilient, high-performing format available in Google AdMobNative: Ads that are designed to fit the app, seamlessly\nInterstitial: Full-screen ads that attract attention and become part of the experience.\nBanner: Traditional formats in a variety of placements.\nRewarded Video: An immersive, user-initiated video ad that rewards users for watching.1. Native Ads: Native is the newest ad format supported by Google AdMob. It gives the most adaptable design and placement to assist developers to build the perfect ad experience for the app users. As the name implies, native ads enable to design an ad experience that seems like a natural part of the app. One can customize the appearance and feel of native ads the way you\u2019d design the app content. Below is a sample image to demonstrate how the Banner ad looks like.2. Interstitial Ads: Interstitial ads are full-screen ads that cover the whole UI of the app. Interstitial ads give superb interactive ads for users on mobile apps. Interstitial ads are meant to be placed between content, so they are best placed at natural app transition points. AdMob publishers should thoroughly implement interstitial ads to give reliable UX and avoid unintentional clicks. Below is a sample image to demonstrate how the Banner ad looks like.3. Banner Ads: Banner ads are rectangular image or text ads that occupy a spot within an app\u2019s layout. If you\u2019re new to mobile advertising, banner ads are the simplest to implement. It can refresh automatically after a set period of time. This means users will see a new ad at regular periods, even if they stay on the same screen in the app. Banner ad units can display the following types of ads: text, image, rich media,and Video.Video ads that arise in banner ad units always start muted. Users can unmute the ad if wanted using the mute button provided by Google. Below is a sample image to demonstrate how the Banner ad looks like.4. Rewarded Video: Rewarded Video ad is full-screen ads that cover the whole UI of the app. The eCPM (Effective Cost Per Mille) of Rewarded Video ads are comparatively higher than banner and Interstitial ads and also leads to higher CTR(Click Through Rate) which results in more earning from your app. The user receives an in-App reward when they view the Rewarded Video from start to end. This type of ad is mostly used in games and also can be used in the app. Below is a sample video to demonstrate how the Banner ad looks like.https://media.geeksforgeeks.org/wp-content/uploads/20200826063519/Google-Admob-Rewarded-Video-Ad.mp4\n"}, {"text": "\nHow to Make a Phone Call From an Android Application?\n\nIn this article, you will make a basic android application that can be used to call some numbers through your android application. You can do so with the help of Intent with action as ACTION_CALL. Basically Intent is a simple message object that is used to communicate between android components such as activities, content providers, broadcast receivers, and services, here use to make phone calls. This application basically contains one activity with edit text to write the phone number on which you want to make a call and a button to call that number.\nStep By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Add Permission to AndroidManifest.xml File\nYou need to take permission from the user for a phone call and for that CALL_PHONE permission is added to the manifest file. Here is the code of the manifest file:\n\n \nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail. This file contains a Relative Layout which contains EditText to write the phone number on which you want to make a phone call and a button for starting intent or making calls:XML \n\n \n \n \n Step 4: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. In the MainActivity Intent, the object is created to redirect activity to the call manager, and the action attribute of intent is set as ACTION_CALL. Phone number input by the user is parsed through Uri and that is passed as data in the Intent object which is then used to call that phone number .setOnClickListener is attached to the button with the intent object in it to make intent with action as ACTION_CALL to make a phone call. Here is the complete code:Java import android.content.Intent; \nimport android.net.Uri; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport android.widget.EditText; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // define objects for edit text and button \nEditText edittext; \nButton button; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Getting instance of edittext and button \nbutton = findViewById(R.id.button); \nedittext = findViewById(R.id.editText); // Attach set on click listener to the button for initiating intent \nbutton.setOnClickListener(arg -> { \n// getting phone number from edit text and changing it to String \nString phone_number = edittext.getText().toString(); // Getting instance of Intent with action as ACTION_CALL \nIntent phone_intent = new Intent(Intent.ACTION_CALL); // Set data of Intent through Uri by parsing phone number \nphone_intent.setData(Uri.parse(\"tel:\" + phone_number)); // start Intent \nstartActivity(phone_intent); \n}); \n} \n}Kotlin import android.content.Intent \nimport android.net.Uri \nimport android.os.Bundle \nimport android.view.View \nimport android.widget.Button \nimport android.widget.EditText \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // define objects for edit text and button \nprivate lateinit var edittext: EditText \nprivate lateinit var button: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Getting instance of edittext and button \nbutton = findViewById(R.id.button) \nedittext = findViewById(R.id.editText) // Attach set on click listener to the button for initiating intent \nbutton.setOnClickListener(View.OnClickListener { \n// getting phone number from edit text and changing it to String \nval phone_number = edittext.text.toString() // Getting instance of Intent with action as ACTION_CALL \nval phone_intent = Intent(Intent.ACTION_CALL) // Set data of Intent through Uri by parsing phone number \nphone_intent.data = Uri.parse(\"tel:$phone_number\") // start Intent \nstartActivity(phone_intent) \n}) \n} \n}Output:"}, {"text": "\nPopup Menu in Android With Example\n\nIn android, the Menu is an important part of the UI component which is used to provide some common functionality around the application. With the help of the menu, users can experience smooth and consistent experiences throughout the application. In Android, we have three types of Menus available to define a set of options and actions in our android applications. The Menus in android applications are the following:Android Options Menu: Android Options Menu is a primary collection of menu items in an android application and is useful for actions that have a global impact on the search application.\nAndroid Context Menu: Android Context Menu is a floating menu that only appears when the user clicks for a long time on an element and is useful for elements that affect the selected content or context frame.\nAndroid Popup Menu: Android Popup Menu displays a list of items in a vertical list which presents the view that invoked the menu and is useful to provide an overflow of actions related to specific content.So in this article, we are going to discuss the Popup Menu. A PopupMenu displays a Menu in a popup window anchored to a View. The popup will be shown below the anchored View if there is room(space) otherwise above the View. If any IME(Input Method Editor) is visible the popup will not overlap it until the View(to which the popup is anchored) is touched. Touching outside the popup window will dismiss it.\nExample\nIn this example, we are going to make a popup menu anchored to a Button and on click, the popup menu will appear, and on a touch of the popup menu item, a Toast message will be shown. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file.XML \n \n Before moving further let\u2019s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes.XML \n#0F9D58 \n#16E37F \n#03DAC5 \n Step 3: Create Menu Directory and Menu file\nFirst, we will create a menu director which will contain the menu file. Go to app > res > right-click > New > Android Resource Directory and give the Directory name and Resource type as menu.Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it popup_menu. In the popup_menu file, we will add menu items. Below is the code snippet for the popup_menu.xml file.XML \n \n \n Step 4: Working with the MainActivity file\nIn the MainActivity file, we will get the reference of the Button and initialize it. Add onClick behavior to the button and inflate the popup menu to it. Below is the code snippet for the MainActivity file.Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.MenuItem; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.PopupMenu; \nimport android.widget.Toast; public class MainActivity extends AppCompatActivity { \nButton button; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // Referencing and Initializing the button \nbutton = (Button) findViewById(R.id.clickBtn); // Setting onClick behavior to the button \nbutton.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) { \n// Initializing the popup menu and giving the reference as current context \nPopupMenu popupMenu = new PopupMenu(MainActivity.this, button); // Inflating popup menu from popup_menu.xml file \npopupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu()); \npopupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { \n@Override\npublic boolean onMenuItemClick(MenuItem menuItem) { \n// Toast message on menu item clicked \nToast.makeText(MainActivity.this, \"You Clicked \" + menuItem.getTitle(), Toast.LENGTH_SHORT).show(); \nreturn true; \n} \n}); \n// Showing the popup menu \npopupMenu.show(); \n} \n}); \n} \n}Kotlin import android.os.Bundle \nimport android.widget.Button \nimport android.widget.PopupMenu \nimport android.widget.Toast \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \nlateinit var button: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Referencing and Initializing the button \nbutton = findViewById(R.id.clickBtn) // Setting onClick behavior to the button \nbutton.setOnClickListener { \n// Initializing the popup menu and giving the reference as current context \nval popupMenu = PopupMenu(this@MainActivity, button) // Inflating popup menu from popup_menu.xml file \npopupMenu.menuInflater.inflate(R.menu.popup_menu, popupMenu.menu) \npopupMenu.setOnMenuItemClickListener { menuItem -> \n// Toast message on menu item clicked \nToast.makeText(this@MainActivity, \"You Clicked \" + menuItem.title, Toast.LENGTH_SHORT).show() \ntrue\n} \n// Showing the popup menu \npopupMenu.show() \n} \n} \n}Output: Run On Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201124223252/Popup-Menu-in-Android.mp4"}, {"text": "\nRecyclerView using GridLayoutManager in Android With Example\n\nRecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View.\nHow to use RecyclerView as GridView?\nWhile implementing Recycler view in Android we generally have to set layout manager to display our Recycler View. There are two types of layout managers for Recycler View to implement.Linear Layout Manager: In linear layout manager, we can align our recycler view in a horizontal or vertical scrolling manner by specifying its orientation as vertical or horizontal.\nGrid Layout Manager: In Grid Layout manager we can align our recycler in the form of a grid. Here we have to mention the number of columns that are to be displayed in the Grid of Recycler View.Difference Between RecyclerView and GridView\n1. View Holder Implementation\nIn GridView it was not mandatory to use View holder implementation but in RecyclerView it is mandatory to use View Holder implementation for Recycler View. It makes the code complex but many difficulties that are faced in GridView are solved in RecyclerView.\n2. Performance of Recycler View\nRecyclerView is an improvised version of ListView. The performance of Recycler View has been improvised. In RecyclerView the items are ahead and behind the visible entries.\nExample of GridLayoutManager in RecyclerView\nA sample image is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step by Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Project just refer to this article on How to Create new Project in Android Studio and make sure that the language is Java. To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include:Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view.\nView Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data.\nData Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View.Step 2: Add google repository in the build.gradle file of the application project.buildscript {\nrepositories {\n google()\n mavenCentral()\n}All Jetpack components are available in the Google Maven repository, include them in the build.gradle fileallprojects {\nrepositories {\n google()\n mavenCentral()\n}\n}Step 3: Create a Card Layout for Recycler View Card Items\nGo to the app > res > layout> right-click > New >Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file.XML \n Step 4: Create a Java class for Modal Data\nGo to the app > java > Right-Click on your app\u2019s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed. Below is the code for the RecyclerData.java file.Java public class RecyclerData {private String title;\nprivate int imgid;public String getTitle() {\nreturn title;\n}public void setTitle(String title) {\nthis.title = title;\n}public int getImgid() {\nreturn imgid;\n}public void setImgid(int imgid) {\nthis.imgid = imgid;\n}public RecyclerData(String title, int imgid) {\nthis.title = title;\nthis.imgid = imgid;\n}\n}Step 5: Create a new java class for the Adapter\nSimilarly, create a new Java Class and name the file as RecyclerViewAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView.Note: View Holder Class is also implemented in Adapter Class itself.These methods to handle Recycler View includes: onCreateViewHolder: This method inflates card layout items for Recycler View.\nonBindViewHolder: This method sets the data to specific views of card items. It also handles methods related to clicks on items of Recycler view.\ngetItemCount: This method returns the length of the RecyclerView.Below is the code for the RecyclerViewAdapter.java file. Comments are added inside the code to understand the code in more detail.Java import android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.ArrayList;public class RecyclerViewAdapter extends RecyclerView.Adapter {private ArrayList courseDataArrayList;\nprivate Context mcontext;public RecyclerViewAdapter(ArrayList recyclerDataArrayList, Context mcontext) {\nthis.courseDataArrayList = recyclerDataArrayList;\nthis.mcontext = mcontext;\n}@NonNull\n@Override\npublic RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n// Inflate Layout\nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);\nreturn new RecyclerViewHolder(view);\n}@Override\npublic void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {\n// Set the data to textview and imageview.\nRecyclerData recyclerData = courseDataArrayList.get(position);\nholder.courseTV.setText(recyclerData.getTitle());\nholder.courseIV.setImageResource(recyclerData.getImgid());\n}@Override\npublic int getItemCount() {\n// this method returns the size of recyclerview\nreturn courseDataArrayList.size();\n}// View Holder Class to handle Recycler View.\npublic class RecyclerViewHolder extends RecyclerView.ViewHolder {private TextView courseTV;\nprivate ImageView courseIV;public RecyclerViewHolder(@NonNull View itemView) {\nsuper(itemView);\ncourseTV = itemView.findViewById(R.id.idTVCourse);\ncourseIV = itemView.findViewById(R.id.idIVcourseIV);\n}\n}\n}Step 6: Working with the activity_main.xml file\nThis is the main screen that displays all data in the form of a grid. Here we have to implement Recycler View. Below is the code snippet of the XML layout in the activity_main.xml file.XML \n\n Step 7: Working with the MainActivity.java file\nThis is the main java file where we will set LayoutManager, adapter, and set data to RecyclerView which is to be displayed in RecyclerView. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.GridLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.ArrayList;public class MainActivity extends AppCompatActivity {private RecyclerView recyclerView;\nprivate ArrayList recyclerDataArrayList;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);\nrecyclerView=findViewById(R.id.idCourseRV);// created new array list..\nrecyclerDataArrayList=new ArrayList<>();// added data to array list\nrecyclerDataArrayList.add(new RecyclerData(\"DSA\",R.drawable.ic_gfglogo));\nrecyclerDataArrayList.add(new RecyclerData(\"JAVA\",R.drawable.ic_gfglogo));\nrecyclerDataArrayList.add(new RecyclerData(\"C++\",R.drawable.ic_gfglogo));\nrecyclerDataArrayList.add(new RecyclerData(\"Python\",R.drawable.ic_gfglogo));\nrecyclerDataArrayList.add(new RecyclerData(\"Node Js\",R.drawable.ic_gfglogo));// added data from arraylist to adapter class.\nRecyclerViewAdapter adapter=new RecyclerViewAdapter(recyclerDataArrayList,this);// setting grid layout manager to implement grid view.\n// in this method '2' represents number of columns to be displayed in grid view.\nGridLayoutManager layoutManager=new GridLayoutManager(this,2);// at last set adapter to recycler view.\nrecyclerView.setLayoutManager(layoutManager);\nrecyclerView.setAdapter(adapter);\n}\n}Output: You can check out the project link mentioned below where you can get all code to implement RecyclerView with Grid Layout Manager. If you want to implement On Click Listener for Recycler Items in Grid Layout then check out this post for implementation of RecyclerView.\nProject Link: Click Here"}, {"text": "\nLine Graph View in Android with Example\n\nIf you are looking for a view to represent some statistical data or looking for a UI for displaying a graph in your app then in this article we will take a look on creating a line graph view in our Android App using the GraphView library.\nWhat we are going to build in this article?We will be building a simple Line Graph View in our Android app and we will be displaying some sample data in our application. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.\nStep-by-Step ImplementationStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add dependency to the build.gradle(Module:app) file\nNavigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. \nimplementation \u2018com.jjoe64:graphview:4.2.2\u2019 \nAfter adding this dependency sync your project and now we will move towards its implementation. \nStep 3: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML\n \n Step 4: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Javaimport android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import com.jjoe64.graphview.GraphView;\nimport com.jjoe64.graphview.series.DataPoint;\nimport com.jjoe64.graphview.series.LineGraphSeries;public class MainActivity extends AppCompatActivity { // creating a variable \n // for our graph view.\n GraphView graphView; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n \n // on below line we are initializing our graph view.\n graphView = findViewById(R.id.idGraphView);\n \n // on below line we are adding data to our graph view.\n LineGraphSeries series = new LineGraphSeries(new DataPoint[]{\n // on below line we are adding \n // each point on our x and y axis.\n new DataPoint(0, 1),\n new DataPoint(1, 3),\n new DataPoint(2, 4),\n new DataPoint(3, 9),\n new DataPoint(4, 6),\n new DataPoint(5, 3),\n new DataPoint(6, 6),\n new DataPoint(7, 1),\n new DataPoint(8, 2)\n });\n \n // after adding data to our line graph series.\n // on below line we are setting \n // title for our graph view.\n graphView.setTitle(\"My Graph View\");\n \n // on below line we are setting \n // text color to our graph view.\n graphView.setTitleColor(R.color.purple_200);\n \n // on below line we are setting\n // our title text size.\n graphView.setTitleTextSize(18);\n \n // on below line we are adding \n // data series to our graph view.\n graphView.addSeries(series);\n }\n}Now run your app and see the output of the app.\nOutput:\n"}, {"text": "\nHow to Integrate Facebook Audience Network (FAN) Banner Ads in Android?\n\nIn order to earn money from the Android app or game, there are many ways such as in-App Purchases, Sponsorship, Advertisements, and many more. But there is another popular method to earn money from the Android app is by integrating a third party advertisement e.g known as Facebook Audience Network (FAN). Facebook Audience Network is designed to help monetize with the user experience in mind. By using high-value formats, quality ads, and innovative publisher tools it helps to grow the business while keeping people engaged.\nWhy Facebook Audience Network?Facebook Audience Network is one of the best alternatives for Google Admob to monetize the Android or IOS App.\nMinimum Payout is $100\nWide Range of Ad Formats\nMaximum Fill Rates\nHigh eCPM(Effective Cost Per Mille)\nQuality Ads\nPersonalized AdsFormats of Facebook Audience Network\nThere are mainly five types of flexible, high-performing format available in Facebook Audience NetworkNative: Ads that you design to fit the app, seamlessly\nInterstitial: Full-screen ads that capture attention and become part of the experience.\nBanner: Traditional formats in a variety of placements.\nRewarded Video: An immersive, user-initiated video ad that rewards users for watching.\nPlayables: A try-before-you-buy ad experience allowing users to preview a game before installing.In this article let\u2019s integrate Facebook Audience Network Banner ads in the Android app. Banner ad is a rectangular image or text ad which occupies a small space in the app layout. Banner ad is easy to implement and it doesn\u2019t affect user interface and increases the revenue gradually.Approach\nStep 1: Creating a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language.\nStep 2: Before going to the coding section first do some pre-taskGo to app -> res -> values -> colors.xml file and set the colors for the app.colors.xml \n \n#0F9D58 \n#0F9D58 \n#05af9b \n Go to Gradle Scripts -> build.gradle (Module: app) section and import following dependencies and click the \u201csync now\u201d on the above pop up.implementation \u2018com.facebook.android:audience-network-sdk:5.+\u2019Go to app -> manifests -> AndroidManifests.xml section and allow \u201cInternet Permission\u201c.Step 3: Designing the UI\nIn the activity_main.xml file, there are simply three Buttons is used. So whenever the user clicked on that button the desired Banner Ad will pop up. To contain the Banner Ad a LinearLayout is added inside the XML file. Here is the code for the activity_main.xml file.activity_main.xml \n \n \n \n \n Step 4: Working with MainActivity.java fileOpen the MainActivity.java file there within the class, first create the object of the Button class.// Creating objects of Button class\nButton fbBanner_50, fbBanner_90, fbBanner_250;Now inside the onCreate() method, link those objects with their respective IDs that is given in activity_main.xml file.// link those objects with their respective id\u2019s that we have given in activity_main.xml file\nfbBanner_50 = (Button)findViewById(R.id.banner_50);\nfbBanner_90 = (Button)findViewById(R.id.banner_90);\nfbBanner_250 = (Button)findViewById(R.id.banner_250);Now inside onCreate() method, initialize the Facebook Audience Network SDK// initializing the Audience Network SDK\nAudienceNetworkAds.initialize(this);Create a private void showBanner() method outside onCreate() method and define it.\nshowBanner() method take AdSize as an Argument, to show banner with different Ad sizesprivate void showBanner(AdSize adSize)\n{\n // creating object of AdView\n AdView bannerAd;\n // initializing AdView Object\n // AdView Constructor Takes 3 Arguments\n // 1)Context\n // 2)Placement Id\n // 3)AdSize\n bannerAd = new AdView(this, \u201cIMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID\u201d,adSize);\n // Creating and initializing LinearLayout which contains the ads\n LinearLayout adLinearContainer = (LinearLayout) findViewById(R.id.fb_banner_ad_container);\n // removing the views inside linearLayout\n adLinearContainer.removeAllViewsInLayout();\n // adding ad to the linearLayoutContainer\n adLinearContainer.addView(bannerAd);\n // loading Ad\n bannerAd.loadAd();\n}Note: Replace \u201cIMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID\u201d with its own placement id to show real ads.So the next thing is to call the showBanner() method when a user clicks a respective banner ad button.\nNow in oncreate() method create a ClickListener for all the three buttons and call showBanner() with different AdSize. // click listener to show Banner_50 Ad\n fbBanner_50.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n showBanner(AdSize.BANNER_HEIGHT_50);\n }\n });\n // click listener to show Banner_90 Ad\n fbBanner_90.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n showBanner(AdSize.BANNER_HEIGHT_90);\n }\n });\n // click listener to show Banner_250 Ad\n fbBanner_250.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n showBanner(AdSize.RECTANGLE_HEIGHT_250);\n }\n });Now call setAdListener() for Banner Ad, so that users will know the status of the ads. To add adListener open showBanner() method and add the below code before bannerAd.loadAd(); // banner AdListener\n bannerAd.setAdListener(new AdListener() {\n @Override\n public void onError(Ad ad, AdError adError) {\n // Showing a toast message\n Toast.makeText(MainActivity.this, \u201conError\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onAdLoaded(Ad ad) {\n // Showing a toast message\n Toast.makeText(MainActivity.this, \u201conAdLoaded\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onAdClicked(Ad ad) {\n // Showing a toast message\n Toast.makeText(MainActivity.this, \u201conAdClicked\u201d, Toast.LENGTH_SHORT).show();\n }\n @Override\n public void onLoggingImpression(Ad ad) {\n // Showing a toast message\n Toast.makeText(MainActivity.this, \u201conLoggingImpression\u201d, Toast.LENGTH_SHORT).show();\n }\n });And inside AdListener Override methods to show a toast message so that users know the status of the ad. Below is the complete code for the MainActivity.java file.MainActivity.java package org.geeksforgeeks.project; import android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.LinearLayout; \nimport android.widget.Toast; \nimport androidx.appcompat.app.AppCompatActivity; \nimport com.facebook.ads.Ad; \nimport com.facebook.ads.AdError; \nimport com.facebook.ads.AdListener; \nimport com.facebook.ads.AdSize; \nimport com.facebook.ads.AdView; \nimport com.facebook.ads.AudienceNetworkAds; public class MainActivity extends AppCompatActivity { // Creating a objects of Button class \nButton fbBanner_50, fbBanner_90, fbBanner_250; @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // link those objects with their respective id's \n// that we have given in activity_main.xml file \nfbBanner_50 = (Button)findViewById(R.id.banner_50); \nfbBanner_90 = (Button)findViewById(R.id.banner_90); \nfbBanner_250 \n= (Button)findViewById(R.id.banner_250); // initializing the Audience Network SDK \nAudienceNetworkAds.initialize(this); // click listener to show Banner_50 Ad \nfbBanner_50.setOnClickListener( \nnew View.OnClickListener() { \n@Override public void onClick(View view) \n{ \nshowBanner(AdSize.BANNER_HEIGHT_50); \n} \n}); // click listener to show Banner_90 Ad \nfbBanner_90.setOnClickListener( \nnew View.OnClickListener() { \n@Override public void onClick(View view) \n{ \nshowBanner(AdSize.BANNER_HEIGHT_90); \n} \n}); // click listener to show Banner_250 Ad \nfbBanner_250.setOnClickListener( \nnew View.OnClickListener() { \n@Override public void onClick(View view) \n{ \nshowBanner(AdSize.RECTANGLE_HEIGHT_250); \n} \n}); \n} private void showBanner(AdSize adSize) \n{ \n// creating object of AdView \nAdView bannerAd; // initializing AdView Object \n// AdView Constructor Takes 3 Arguments \n// 1)Context \n// 2)Placement Id \n// 3)AdSize \nbannerAd = new AdView( \nthis, \"IMG_16_9_APP_INSTALL#YOUR_PLACEMENT_ID\", \nadSize); // Creating and initializing LinearLayout which \n// contains the ads \nLinearLayout adLinearContainer \n= (LinearLayout)findViewById( \nR.id.fb_banner_ad_container); // removing the views inside linearLayout \nadLinearContainer.removeAllViewsInLayout(); // adding ad to the linearLayoutContainer \nadLinearContainer.addView(bannerAd); // banner AdListener \nbannerAd.setAdListener(new AdListener() { \n@Override\npublic void onError(Ad ad, AdError adError) \n{ \n// Showing a toast message \nToast \n.makeText(MainActivity.this, \"onError\", \nToast.LENGTH_SHORT) \n.show(); \n} @Override public void onAdLoaded(Ad ad) \n{ \n// Showing a toast message \nToast \n.makeText(MainActivity.this, \n\"onAdLoaded\", \nToast.LENGTH_SHORT) \n.show(); \n} @Override public void onAdClicked(Ad ad) \n{ \n// Showing a toast message \nToast \n.makeText(MainActivity.this, \n\"onAdClicked\", \nToast.LENGTH_SHORT) \n.show(); \n} @Override public void onLoggingImpression(Ad ad) \n{ \n// Showing a toast message \nToast \n.makeText(MainActivity.this, \n\"onLoggingImpression\", \nToast.LENGTH_SHORT) \n.show(); \n} \n}); // loading Ad \nbannerAd.loadAd(); \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200902210442/Facebook-Audience-Network-Banner.mp4"}, {"text": "\nHow to Create Group BarChart in Android?\n\nAs we have seen how we can create a beautiful bar chart in Android but what if we have to represent data in the form of groups in our bar chart. So that we can plot a group of data in our bar chart. So we will be creating a Group Bar Chart in our Android app in this article.\nWhat we are going to build in this article?\nWe will be building a simple application in which we will be displaying a bar chart with multiple sets of data in our Android application. We will display the data in the form of the group in our bar chart. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add dependency and JitPack Repository\nNavigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation \u2018com.github.PhilJay:MPAndroidChart:v3.1.0\u2019Add the JitPack repository to your build file. Add it to your root build.gradle at the end of repositories inside the allprojects{ } section.allprojects {\nrepositories {\n \u2026\n maven { url \u201chttps://jitpack.io\u201d }\n }\n}After adding this dependency sync your project and now we will move towards its implementation. \nStep 3: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n \n Step 4: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.graphics.Color; \nimport android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.github.mikephil.charting.charts.BarChart; \nimport com.github.mikephil.charting.components.XAxis; \nimport com.github.mikephil.charting.data.BarData; \nimport com.github.mikephil.charting.data.BarDataSet; \nimport com.github.mikephil.charting.data.BarEntry; \nimport com.github.mikephil.charting.formatter.IndexAxisValueFormatter; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // variable for our bar chart \nBarChart barChart; // variable for our bar data set. \nBarDataSet barDataSet1, barDataSet2; // array list for storing entries. \nArrayList barEntries; // creating a string array for displaying days. \nString[] days = new String[]{\"Sunday\", \"Monday\", \"Tuesday\", \"Thursday\", \"Friday\", \"Saturday\"}; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // initializing variable for bar chart. \nbarChart = findViewById(R.id.idBarChart); // creating a new bar data set. \nbarDataSet1 = new BarDataSet(getBarEntriesOne(), \"First Set\"); \nbarDataSet1.setColor(getApplicationContext().getResources().getColor(R.color.purple_200)); \nbarDataSet2 = new BarDataSet(getBarEntriesTwo(), \"Second Set\"); \nbarDataSet2.setColor(Color.BLUE); // below line is to add bar data set to our bar data. \nBarData data = new BarData(barDataSet1, barDataSet2); // after adding data to our bar data we \n// are setting that data to our bar chart. \nbarChart.setData(data); // below line is to remove description \n// label of our bar chart. \nbarChart.getDescription().setEnabled(false); // below line is to get x axis \n// of our bar chart. \nXAxis xAxis = barChart.getXAxis(); // below line is to set value formatter to our x-axis and \n// we are adding our days to our x axis. \nxAxis.setValueFormatter(new IndexAxisValueFormatter(days)); // below line is to set center axis \n// labels to our bar chart. \nxAxis.setCenterAxisLabels(true); // below line is to set position \n// to our x-axis to bottom. \nxAxis.setPosition(XAxis.XAxisPosition.BOTTOM); // below line is to set granularity \n// to our x axis labels. \nxAxis.setGranularity(1); // below line is to enable \n// granularity to our x axis. \nxAxis.setGranularityEnabled(true); // below line is to make our \n// bar chart as draggable. \nbarChart.setDragEnabled(true); // below line is to make visible \n// range for our bar chart. \nbarChart.setVisibleXRangeMaximum(3); // below line is to add bar \n// space to our chart. \nfloat barSpace = 0.1f; // below line is use to add group \n// spacing to our bar chart. \nfloat groupSpace = 0.5f; // we are setting width of \n// bar in below line. \ndata.setBarWidth(0.15f); // below line is to set minimum \n// axis to our chart. \nbarChart.getXAxis().setAxisMinimum(0); // below line is to \n// animate our chart. \nbarChart.animate(); // below line is to group bars \n// and add spacing to it. \nbarChart.groupBars(0, groupSpace, barSpace); // below line is to invalidate \n// our bar chart. \nbarChart.invalidate(); \n} // array list for first set \nprivate ArrayList getBarEntriesOne() { // creating a new array list \nbarEntries = new ArrayList<>(); // adding new entry to our array list with bar \n// entry and passing x and y axis value to it. \nbarEntries.add(new BarEntry(1f, 4)); \nbarEntries.add(new BarEntry(2f, 6)); \nbarEntries.add(new BarEntry(3f, 8)); \nbarEntries.add(new BarEntry(4f, 2)); \nbarEntries.add(new BarEntry(5f, 4)); \nbarEntries.add(new BarEntry(6f, 1)); \nreturn barEntries; \n} // array list for second set. \nprivate ArrayList getBarEntriesTwo() { // creating a new array list \nbarEntries = new ArrayList<>(); // adding new entry to our array list with bar \n// entry and passing x and y axis value to it. \nbarEntries.add(new BarEntry(1f, 8)); \nbarEntries.add(new BarEntry(2f, 12)); \nbarEntries.add(new BarEntry(3f, 4)); \nbarEntries.add(new BarEntry(4f, 1)); \nbarEntries.add(new BarEntry(5f, 7)); \nbarEntries.add(new BarEntry(6f, 3)); \nreturn barEntries; \n} \n}Now run your app and see the output of the app.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210124150116/Screenrecorder-2021-01-24-15-00-24-765.mp4"}, {"text": "\nHow to Display the List of Sensors Present in an Android Device Programmatically?\n\nAll Android devices produced worldwide come with built-in sensors that measure motion, orientation, and various environmental conditions. These sensors generally facilitate Android architecture by providing the data from the sensor for various applications. For example, a temperature sensor provides the device\u2019s temperature, information from which could be used for shutting down a few unrequired services. Such a sensor is a general type, but broadly, sensors are divided into three types:Motion Sensors: Motion sensors measure the acceleration and rotational forces along the three axes x-y-z. Motion Sensors include accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.\nEnvironment Sensors: Environment sensors measure a variety of environmental parameters, such as pressure, ambient temperature (room temperature), illumination (light falling on the device), and humidity. They include barometers, photometers, and thermometers.\nPosition Sensors: Position Sensors measure the physical position of a device in the space. They include orientation sensors and magnetometers.Generally Available Sensors in an Android Device\nIn general, any Android Device on or above Android Version 4.4 (Kitkat) have these sensors present in them:Accelerometer \u2013 Hardware Sensor \u2013 Motion Sensor\nGravity Sensor \u2013 Program Based (Software) \u2013 Raw data derived from the Motion Sensors for Gravity calculation.\nAmbient Temperature \u2013 Hardware Sensor \u2013 Environment Sensor\nGyroscope \u2013 Hardware Sensor \u2013 Motion Sensor\nLight Sensor \u2013 Hardware Sensor \u2013 Environment Sensor\nOrientation Sensor \u2013 Program Based (Software) \u2013 Raw data derived from the Position and Motion Sensors\nProximity Sensor \u2013 Hardware Sensor \u2013 Position SensorApproach\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.\nStep 2: Working with the activity_main.xml file\nGo to the activity_main.xml file which represents the UI of the application, and create a TextView inside a ScrollView that shall list the sensors present in the device. Below is the code for theactivity_main.xml file.XML \n \n Step 4: Working with the MainActivity.kt file\nGo to the MainActivity.kt file, and refer to the following code. Below is the code for theMainActivity.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.content.Context \nimport android.hardware.Sensor \nimport android.hardware.SensorManager \nimport android.os.Bundle \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { // Information about Sensors present in the \n// device is supplied by Sensor Manager of the device \nprivate lateinit var sensorManager: SensorManager override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Initialize the variable sensorManager \nsensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager // getSensorList(Sensor.TYPE_ALL) lists all the sensors present in the device \nval deviceSensors: List = sensorManager.getSensorList(Sensor.TYPE_ALL) // Text View that shall display this list \nval textView = findViewById(R.id.tv) // Converting List to String and displaying \n// every sensor and its information on a new line \nfor (sensors in deviceSensors) { \ntextView.append(sensors.toString() + \"\\n\\n\") \n} \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201001130326/Screen-Recording-2020-09-28-at-12.50.45.mp4"}, {"text": "\nBounce Animation in Android\n\nTo make the android app more attractive we add many things and animation is one of the best things which makes the app more attractive and engages the user with the app. So in this article, we will add a bounce animation to the Button. One can use this tutorial to add Bounce animation to any View in android studio such as ImageView, TextView, EditText, etc. A sample GIF is given below to get an idea about what we are going to do in this article.Steps for Creating Bounce Animation\nStep 1: Creating a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that choose Java as language though we are going to implement this project in Java language.Step 2: Designing the UIGo to the app -> res right click on res folder then New -> Android Resource Directory and create an anim Directory.\nThen right-click on anim folder then go to New -> Animation Resource File and create a bounce.xml file.\nbounce.xml file contains the animation which is used to animate the Button in the next step. The complete code for bounce.xml is given below.bounce.xml \n \n Now Go to the app -> res -> layout -> activity_main.xml file and add a simple Button, which we want to animate. Here is the code for the activity_main.xml file.activity_main.xml \n \n Step 3: Working with MainActivity.java fileOpen the MainActivity.java call and inside the onCreate() method get the animation from the anim folder.// loading Animation from\nfinal Animation animation = AnimationUtils.loadAnimation(this,R.anim.bounce);Get the reference of the Button which we created in the activity_main.xml file// getting the Button from activity_main.xml file\nfinal Button button= findViewById(R.id.button);Create an OnClickListener for the Button and startAnimation inside onClick().// clickListener for Button\nbutton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n // start the animation\n button.startAnimation(animation);\n }\n});The complete code for the MainActivity.java file is given below.MainActivity.java import android.os.Bundle; \nimport android.view.View; \nimport android.view.animation.Animation; \nimport android.view.animation.AnimationUtils; \nimport android.widget.Button; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // loading Animation from \nfinal Animation animation = AnimationUtils.loadAnimation(this, R.anim.bounce); // getting the Button from activity_main.xml file \nfinal Button button = findViewById(R.id.button); \nbutton.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View view) { \n// start the animation \nbutton.startAnimation(animation); \n} \n}); \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200913005044/bounce-animation-in-android-studio.mp4\nResources:Download Complete Project from Github\nDownload the Apk file"}, {"text": "\nResource Raw Folder in Android Studio\n\nThe raw (res/raw) folder is one of the most important folders and it plays a very important role during the development of android projects in android studio. The raw folder in Android is used to keep mp3, mp4, sfb files, etc. The raw folder is created inside the res folder: main/res/raw. So we will simply create it inside the res folder. But before creating a raw folder let\u2019s have a look at the asset folder in android which acts the same role as the raw folder in android studio. So let discuss how the resource raw folder is different from the assets folder?\nHow the Resource raw folder is different from the Assets folder?\nIn Android one can store the raw asset file like JSON, Text, mp3, HTML, pdf, etc in two possible locations:assets\nres/raw folderBoth of them appear to be the same, as they can read the file and generate InputStream as below.// From assets\nassets.open(assetPathFilename)\n// From res/raw\nresources.openRawResource(resourceRawFilename)But when to use which folder?\nBelow is some guidance that might be helpful to choose\n1. Flexible File Name: (assets is better)assets: The developer can name the file name in any way, like having capital letters (fileName) or having space (filename).\nres/raw: In this case, the name of the file is restricted. File-based resource names must contain only lowercase a-z, 0-9, or underscore.2. Store in subdirectory: (possible in assets)assets: If the developer wants to categories the files into subfolders, then he/she can do it in assets like below.res/raw: In this case, files can only be in the root folder.3. Compile-time checking: (possible in res/raw)assets: Here, the way to read it into InputStream is given below. If the filename doesn\u2019t exist, then we need to catch it.assets.open(\u201cfilename\u201d)res/raw folder: Here, the way to read it into InputStream is:resources.openRawResource(R.raw.filename)So putting a file in the res/raw folder will provide ensure the correct file-name during compile time check.\n4. List filenames at runtime: (possible in assets)assets: If the developer wants to list all the files in the assets folder, he/she has used the list() function and provide the folder name or \u201d \u201c on the root folder as given below.assets.list(FOLDER_NAME)?.forEach { \n println(it)\n}res/raw: This is not possible in this folder. The developer has to know the filename during development, and not runtime.So, in assets, one can read the filename during runtime, list them, and use them dynamically. In res/raw, one needs to code them ready, perhaps in the string resources file.\n5. Filename accessible from XML: (possible in res/raw)assets: No simple way the developer can arrange an XML file (e.g. AndroidManifest.xml) to point to the file in the assets folder.\nres/raw: In any XML files like in Java, the developer can access the file in res/raw using @raw/filename easily.So if you need to access your file in any XML, put it in the res/raw folder. Let\u2019s make a table to remember the whole scenario easily.ScenarioAssets FolderRes/Raw FolderFlexible File NameYESNOStore in subdirectoryYESNOCompile-time checkingNOYESList filenames at runtimeYESNOFilename accessible from XMLNOYESHow to Create Resource Raw Folder in Android Studio?\nNow let\u2019s discuss how to create the Resource Raw folder in the android studio. Below is the step-by-step process to create the Resource Raw folder in Android studio.\nStep 1: To create the Resource Raw folder in Android studio open your project in Android mode first as shown in the below image.Step 2: Open your android studio go to the app > res > right-click > New > Android Resource Directory as shown in the below image.Step 3: Then a pop-up screen will arise like below. Here in Resource type choose raw.Step 4: After choosing the raw from the dropdown menu click on the OK button and keep all the things as it is.Step 5: Now you can see the raw folder has been created and you can find the folded in the app > res > raw as shown in the below image."}, {"text": "\nWorking With the EditText in Android\n\nEditText is one of the basic UI widgets, which is used to take the input from the user. The EditText is derived or is the extension of the TextView in Android. This article its been discussed in detail about the EditText in Android. The article also contains some of the redirections to other articles, also refer to them to get the detailed perspective of the EditText widget in Android. Have a look at the following list to get an idea of the overall discussion.Input Type for the EditText\nGetting the data or retrieving the data entered by the user\nInput Data Customization\nAdding hints for the placeholder\nChange the stroke color\nChange the highlighted color inside the EditText\nEvent Listener for the EditText\nError Message for the EditText filed\nImplementing Password visibility toggle\nCharacter counting using Material Design EditTextThe Detailed Perspective of EditText in Android\nStep 1: Create an empty activity projectCreate an empty activity Android Studio project. Refer to How to Create/Start a New Project in Android Studio, to know how to create an empty activity Android project.Step 2: Working with the activity_main.xml fileThe main layout of the application contains the EditText Widget and two buttons. To implement the UI invoke the following code inside the activity_main.xml file. To get an idea about how the basic EditText in android looks like.XML \n Output UI:Now let\u2019s discuss the various attributes of the EditText\n1. Input Type for the EditTextThis is one of the attributes which is needed to be specified under the EditText widget. Which defines the type of data to be entered by the user.\nThe following are attributes which are needed to be invoked and refer to its output to get a clear understanding.InputType AttributeType of the Data which is enterednumber\nMathematical numeric valuephone\nContact Number based on the country codedate\nTo take the date inputtime\nTo take the time is neededinputtextCapCharacters\nTo take the entire input in the upper case letterstextMultiLine\nMakes the user input multiple lines of texttextEmailAddress\nTo take the email address from the usertextPersonName\nTo take the name of the person as inputtextPassword\nTo take the text password from the user, which turns to asterisks dots after entering the datanumberPassword\nTo take only the numerical digits as a passwordtextVisiblePassword\nTo take the text password from the user, which do not turns to asterisks dots after entering the datatextUri\nTo take the particular URL of the websiteRefer to the following code, which contains only the phone as the input type, for demonstration purposes. Which the value of that can be replaced with the values mentioned in the above table.XML \n\n Output:https://media.geeksforgeeks.org/wp-content/uploads/20210119205957/Untitled-Project.mp4\n2. Getting the data or retrieving the data entered by the userTo get the data entered by the user, firstly the EditText widget has to be invoked with the id. which is used to point to the unique widgets in android.\nProvide the EditText with the id, by referring to the following code, which has to be invoked inside the activity_main.xml file.XML \n The following code needs to be invoked inside the MainActivity.kt file. Which performs the retrieving operation and provides the Toast message the same as the entered data.\nThere is one scenario, if the user left the EditText blank, it has to be checked whether it\u2019s blank or not. To check whether it is blank EditText.Kotlin import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.EditText\nimport android.widget.Toastclass MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// register editText with instance\nval editText: EditText = findViewById(R.id.editText)// also register the submit button with the appropriate id\nval submitButton: Button = findViewById(R.id.submitButton)// handle the button with the onClickListener\nsubmitButton.setOnClickListener {// get the data with the \"editText.text.toString()\"\nval enteredData: String = editText.text.toString()// check whether the retrieved data is empty or not\n// based on the emptiness provide the Toast Message\nif (enteredData.isEmpty()) {\nToast.makeText(applicationContext, \"Please Enter the Data\", Toast.LENGTH_SHORT)\n.show()\n} else {\nToast.makeText(applicationContext, enteredData, Toast.LENGTH_SHORT).show()\n}\n}\n}\n}Java import android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;\nimport androidx.appcompat.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {EditText editText;\nButton submitButton;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// register editText with instance\neditText = (EditText) findViewById(R.id.editText);// also register the submit button with the appropriate id\nsubmitButton = (Button) findViewById(R.id.submitButton);// handle the button with the onClickListener\nsubmitButton.setOnClickListener(\nnew View.OnClickListener() {\n@Override\npublic void onClick(View view) {// get the data with the\n// \"editText.text.toString()\"\nString enteredData = editText.getText().toString();// check whether the retrieved data is\n// empty or not based on the emptiness\n// provide the Toast Message\nif (enteredData.isEmpty()) {\nToast.makeText(getApplicationContext(), \"Please Enter the Data\", Toast.LENGTH_SHORT).show();\n} else {\nToast.makeText(getApplicationContext(), enteredData, Toast.LENGTH_SHORT).show();\n}\n}\n});\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20210119214853/Untitled-Project.mp4\n3. Input Data CustomizationThe EditText allows developers to make restrictions for the amount of data to be entered by the user. For example, the number of characters entered can be restricted, or the number of lines can be restricted, or the number of digits can be restricted.\nFollowing are some of the attributes:Input only particular numbers -> The following attribute takes only the digits 5 & 6 as input and no other numbers can be entered by the user.digits=\u201d56\u2033\ninputType=\u201dnumber\u201dRestrict the number of characters of the input -> The following attribute makes user to enter only 6 number of characters.maxLength=\u201d6\u2033Restrict the number of lines of input -> The following attribute makes user restricted to only single line, in which the EditText do not expand if the amount of the data gets more than single line.lines=\u201d1\u2033\nmaxLines=\u201d1\u2033Following is the example of the numberPassword with only 6 digits as maxLength.XML \n Output:https://media.geeksforgeeks.org/wp-content/uploads/20210120085607/Untitled-Project.mp4\n4. Adding hints for the placeholderThe hints for the EditText give confidence to the user, on what the data they have to enter into the EditText.The attribute which is used to provide the hint text for the EditText is:\nandroid:hint=\u201dFirst and Last Name\u201dRefer to the following code and its output for better understanding.XML \n Output:https://media.geeksforgeeks.org/wp-content/uploads/20210120090414/Untitled-Project.mp4\n5. Change the stroke colorThe stroke color which appears when it is in focus can also be changed, by the following attributeandroid:backgroundTint=\u201dcolorValue\u201dRefer to the following code and its output, for better understanding.XML \n Output:https://media.geeksforgeeks.org/wp-content/uploads/20210120090932/Untitled-Project.mp4\n6. Change the highlighted color inside the EditTextThe text inside the EditText gets highlighted when the user selects the particular text from it.\nThe color of the highlighted text inside the EditText can be changed using the following attribute.android:textColorHighlight=\u201dcolorValue\u201dRefer to the following code and its output for better understanding.XML \n Output:https://media.geeksforgeeks.org/wp-content/uploads/20210120091723/Untitled-Project.mp4\n7. Event Listener for the EditTextEvent listeners for the EditText can also be implemented to perform particular actions. Refer to the How to Implement TextWatcher in Android?8. Error Message for the EditText filedIf the user misses out on any of the EditText or left the EditText blank without inputting any data, the user has to be alerted with the error message.\nTo implement such functionality, refer to Implement Form Validation (Error to EditText) in Android9. Implementing Password visibility toggleImplement the password visibility toggle for the EditText by referring to How to Toggle Password Visibility in Android?.10. Character counting using Material Design EditTextInvoke the following dependency to access the Material Design components.implementation \u2018com.google.android.material:material:1.2.1\u2019The following attributes are to be invoked inside the TextInputLayoutapp:counterEnabled=\u201dtrue\u201d\napp:counterMaxLength=\u201d6\u2033Refer to the following code and its output for better understanding.XML \n Output:https://media.geeksforgeeks.org/wp-content/uploads/20210120094245/Untitled-Project.mp4"}, {"text": "\nwithContext in Kotlin Coroutines\n\nPrerequisite:Kotlin Coroutines on Android\nLaunch vs Async in Kotlin CoroutinesIt is known that async and launch are the two ways to start the coroutine. Since It is known that async is used to get the result back, & should be used only when we need the parallel execution, whereas the launch is used when we do not want to get the result back and is used for the operation such as updating of data, etc. As we know that async is the only way till now to start the coroutine and get the result back, but the problem with async arises when we do not want to make parallel network calls. It is known when async is used, one needs to use the await() function, which leads to blocking of the main thread, but here comes the concept of withContext which removes the problem of blocking the main thread.\nwithContext is nothing but another way of writing the async where one does not have to write await(). When withContext, is used, it runs the tasks in series instead of parallel. So one should remember that when we have a single task in the background and want to get back the result of that task, we should use withContext. Let us take an example which demonstrates the working of the withContext:Kotlin // two kotlin suspend functions\n// Suppose we have two tasks like belowprivate suspend fun doTaskOne(): String\n{\ndelay(2000)\nreturn \"One\"\n}private suspend fun doTaskTwo(): String\n{\ndelay(2000)\nreturn \"Two\"\n}Let\u2019s run the two tasks in parallel using async-await and then using withcontext and see the difference between the two.Kotlin // kotlin function using async\nfun startLongRunningTaskInParallel() \n{\nviewModelScope.launch \n{\nval resultOneDeferred = async { TaskOne() }\nval resultTwoDeferred = async { TaskTwo() }\nval combinedResult = resultOneDeferred.await() + resultTwoDeferred.await()\n}\n}Here using async, both the task run in parallel. Now let\u2019s use the withContext and do the same task in series with withContext.Kotlin // kotlin function using withContext\nfun startLongRunningTaskInParallel() \n{\nviewModelScope.launch\n{\nval resultOne = withContext(Dispatchers.IO) { TaskOne() }\nval resultTwo = withContext(Dispatchers.IO) { TaskTwo() }\nval combinedResult = resultOne + resultTwo\n}\n}Here one can see that in withContext everything is the same, the only difference is that here we do not have to use the await() function, and tasks are executed in a serial manner. Since here multiple tasks have been taken, one should remember that async should be used with multiple tasks and withContext should be used with a single task. Now let\u2019s take an example and try to understand withContext in detail and how it is executed.Kotlin // sample kotlin program for complete \n// demonstration of withContext\nfun testWithContext \n{\nvar resultOne = \"GFG\"\nvar resultTwo = \"Is Best\"\nLog.i(\"withContext\", \"Before\")\nresultOne = withContext(Dispatchers.IO) { function1() }\nresultTwo = withContext(Dispatchers.IO) { function2() }\nLog.i(\"withContext\", \"After\")\nval resultText = resultOne + resultTwo\nLog.i(\"withContext\", resultText)\n}suspend fun function1(): String\n{\ndelay(1000L)\nval message = \"function1\"\nLog.i(\"withContext\", message)\nreturn message\n}suspend fun function2(): String \n{\ndelay(100L)\nval message = \"function2\"\nLog.i(\"withContext\", message)\nreturn message\n}function 2 executes faster than function 1 since function 2 has less delay than function 1. Since withContext is a suspend call, that is it won\u2019t go to the next line until it finished. Since withContext is a suspend call and does not block the main thread, we can do other tasks while the IO thread is busy in executing function1 and function 2."}, {"text": "\nMVC (Model View Controller) Architecture Pattern in Android with Example\n\nDeveloping an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in the future. There are some architectures that are very popular among developers and one of them is the Model\u2014View\u2014Controller(MVC) Pattern. The MVC pattern suggests splitting the code into 3 components. While creating the class/file of the application, the developer must categorize it into one of the following three layers:Model: This component stores the application data. It has no knowledge about the interface. The model is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: It is the UI(User Interface) layer that holds components that are visible on the screen. Moreover, it provides the visualization of the data stored in the Model and offers interaction to the user.\nController: This component establishes the relationship between the View and the Model. It contains the core application logic and gets informed of the user\u2019s behavior and updates the Model as per the need.In spite of applying MVC schema to give a modular design to the application, code layers do depend on each other. In this pattern, View and Controller both depend upon the Model. Multiple approaches are possible to apply the MVC pattern in the project:Approach 1: Activities and fragments can perform the role of Controller and are responsible for updating the View.\nApproach 2: Use activity or fragments as views and controller while Model will be a separate class that does not extend any Android class.In MVC architecture, application data is updated by the controller and View gets the data. Since the Model component is separated, it could be tested independently of the UI. Further, if the View layer respects the single responsibility principle then their role is just to update the Controller for every user event and just display data from the Model, without implementing any business logic. In this case, UI tests should be enough to cover the functionalities of the View.\nExample of MVC Architecture\nTo understand the implementation of the MVC architecture pattern more clearly, here is a simple example of an android application. This application will have 3 buttons and each one of them displays the count that how many times the user has clicked that particular button. To develop this application the code has been separated in the following manner:Controller and View will be handled by the Activity. Whenever the user clicks the buttons, activity directs the Model to handle the further operations. The activity will act as an observer.\nThe Model will be a separate class that contains the data to be displayed. The operations on the data will be performed by functions of this class and after updating the values of the data this Observable class notifies the Observer(Activity) about the change.Below is the complete step-by-step implementation of this android application using the MVC architecture pattern:Note: Following steps are performed on Android Studio version 4.0Step 1: Create a new projectClick on File, then New => New Project.\nChoose Empty activity\nSelect language as Java/Kotlin\nSelect the minimum SDK as per your need.Step 2: Modify String.xml file\nAll the strings which are used in the activity are listed in this file.XML \nGfG | MVC Architecture \nMVC Architecture Pattern \nButton_1 \nCount:0 \n Step 3: Working with the activity_main.xml file\nOpen the activity_main.xml file and add 3 Buttons to it which will display the count values as per the number of times the user clicks it. Below is the code for designing a proper activity layout.XML \n \n \n \n \n \n \n Step 4: Creating the Model class\nCreate a new class named Model to separate all data and its operations. This class will not know the existence of View Class.Java import java.util.*; public class Model extends Observable { // declaring a list of integer \nprivate List List; // constructor to initialize the list \npublic Model(){ \n// reserving the space for list elements \nList = new ArrayList(3); // adding elements into the list \nList.add(0); \nList.add(0); \nList.add(0); \n} // defining getter and setter functions // function to return appropriate count \n// value at correct index \npublic int getValueAtIndex(final int the_index) throws IndexOutOfBoundsException{ \nreturn List.get(the_index); \n} // function to make changes in the activity button's \n// count value when user touch it \npublic void setValueAtIndex(final int the_index) throws IndexOutOfBoundsException{ \nList.set(the_index,List.get(the_index) + 1); \nsetChanged(); \nnotifyObservers(); \n} }Kotlin import java.util.* \nimport kotlin.collections.ArrayList class Model : Observable() { \n// declaring a list of integer \nval List: MutableList // constructor to initialize the list \ninit { \n// reserving the space for list elements \nList = ArrayList(3) // adding elements into the list \nList.add(0) \nList.add(0) \nList.add(0) \n} // defining getter and setter functions \n// function to return appropriate count \n// value at correct index \n@Throws(IndexOutOfBoundsException::class) \nfun getValueAtIndex(the_index: Int): Int { \nreturn List[the_index] \n} // function to make changes in the activity button's \n// count value when user touch it \n@Throws(IndexOutOfBoundsException::class) \nfun setValueAtIndex(the_index: Int) { \nList[the_index] = List[the_index] + 1\nsetChanged() \nnotifyObservers() \n} \n}Step 5: Define functionalities of View and Controller in the MainActivity file\nThis class will establish the relationship between View and Model. The data provided by the Model will be used by View and the appropriate changes will be made in the activity.Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport java.util.Observable; \nimport java.util.Observer; public class MainActivity extends AppCompatActivity implements Observer, View.OnClickListener { // creating object of Model class \nprivate Model myModel; // creating object of Button class \nprivate Button Button1; \nprivate Button Button2; \nprivate Button Button3; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // creating relationship between the \n// observable Model and the \n// observer Activity \nmyModel = new Model(); \nmyModel.addObserver(this); // assigning button IDs to the objects \nButton1 = findViewById(R.id.button); \nButton2 = findViewById(R.id.button2); \nButton3 = findViewById(R.id.button3); // transfer the control to Onclick() method \n// when a button is clicked by passing \n// argument \"this\" \nButton1.setOnClickListener(this); \nButton2.setOnClickListener(this); \nButton3.setOnClickListener(this); } @Override\n// calling setValueAtIndex() method \n// by passing appropriate arguments \n// for different buttons \npublic void onClick(View v) { \nswitch(v.getId()){ case R.id.button: \nmyModel.setValueAtIndex(0); \nbreak; case R.id.button2: \nmyModel.setValueAtIndex(1); \nbreak; case R.id.button3: \nmyModel.setValueAtIndex(2); \nbreak; \n} \n} @Override\n// function to update the view after \n// the values are modified by the model \npublic void update(Observable arg0, Object arg1) { // changing text of the buttons \n// according to updated values \nButton1.setText(\"Count: \"+myModel.getValueAtIndex(0)); \nButton2.setText(\"Count: \"+myModel.getValueAtIndex(1)); \nButton3.setText(\"Count: \"+myModel.getValueAtIndex(2)); } \n}Kotlin import android.os.Bundle \nimport android.view.View \nimport android.widget.Button \nimport androidx.appcompat.app.AppCompatActivity \nimport java.util.* class MainActivity : AppCompatActivity(), Observer, View.OnClickListener { // creating object of Model class \nvar myModel: Model? = null// creating object of Button class \nvar Button1: Button? = null\nvar Button2: Button? = null\nvar Button3: Button? = nulloverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // creating relationship between the \n// observable Model and the \n// observer Activity \nmyModel = Model() \nmyModel!!.addObserver(this) // assigning button IDs to the objects \nButton1 = findViewById(R.id.button) \nButton2 = findViewById(R.id.button2) \nButton3 = findViewById(R.id.button3) // transfer the control to Onclick() method \n// when a button is clicked by passing \n// argument \"this\" \nButton1?.setOnClickListener(this) \nButton2?.setOnClickListener(this) \nButton3?.setOnClickListener(this) \n} // calling setValueAtIndex() method \n// by passing appropriate arguments \n// for different buttons \noverride fun onClick(v: View) { \nwhen (v.id) { \nR.id.button -> myModel?.setValueAtIndex(0) \nR.id.button2 -> myModel?.setValueAtIndex(1) \nR.id.button3 -> myModel?.setValueAtIndex(2) \n} \n} // function to update the view after \n// the values are modified by the model \noverride fun update(arg0: Observable, arg1: Any?) { // changing text of the buttons \n// according to updated values \nButton1!!.text = \"Count: \" + myModel!!.getValueAtIndex(0) \nButton2!!.text = \"Count: \" + myModel!!.getValueAtIndex(1) \nButton3!!.text = \"Count: \" + myModel!!.getValueAtIndex(2) \n} \n}Outputhttps://media.geeksforgeeks.org/wp-content/uploads/20201023013240/MVC-Output-Recording.mp4\nAdvantages of MVC architecture patternMVC pattern increases the code testability and makes it easier to implement new features as it highly supports the separation of concerns.\nUnit testing of Model and Controller is possible as they do not extend or use any Android class.\nFunctionalities of the View can be checked through UI tests if the View respect the single responsibility principle(update controller and display data from the model without implementing domain logic)Disadvantages of MVC architecture patternCode layers depend on each other even if MVC is applied correctly.\nNo parameter to handle UI logic i.e., how to display the data."}, {"text": "\nHow to Draw a Track on Google Maps in Android?\n\nIn many android apps, we have seen that there is a route marker from a source location to the destination location. In this article, we will take a look at How we can draw a track on Google Maps in Android.\nWhat we are going to build in this article?\nWe will be building a simple application in which we will be displaying two EditText fields inside that fields we have to enter a source location and a destination location and we will display a button to display a route. After clicking on that button we will display a route on Google Maps for that location along with time. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210127150850/1611740152955.mp4\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Working with the activity_main.xml file\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n \n \n \n Step 3: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.content.ActivityNotFoundException; \nimport android.content.Intent; \nimport android.net.Uri; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.EditText; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // creating variables for \n// edit texts and button. \nEditText sourceEdt, destinationEdt; \nButton trackBtn; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // initializing our edit text and buttons \nsourceEdt = findViewById(R.id.idEdtSource); \ndestinationEdt = findViewById(R.id.idEdtDestination); \ntrackBtn = findViewById(R.id.idBtnTrack); // adding on click listener to our button. \ntrackBtn.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \n// calling a method to draw a track on google maps. \ndrawTrack(sourceEdt.getText().toString(), destinationEdt.getText().toString()); \n} \n}); \n} private void drawTrack(String source, String destination) { \ntry { \n// create a uri \nUri uri = Uri.parse(\"https://www.google.co.in/maps/dir/\" + source + \"/\" + destination); // initializing a intent with action view. \nIntent i = new Intent(Intent.ACTION_VIEW, uri); // below line is to set maps package name \ni.setPackage(\"com.google.android.apps.maps\"); // below line is to set flags \ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // start activity \nstartActivity(i); \n} catch (ActivityNotFoundException e) { \n// when the google maps is not installed on users device \n// we will redirect our user to google play to download google maps. \nUri uri = Uri.parse(\"https://play.google.com/store/apps/details?id=com.google.android.apps.maps\"); // initializing intent with action view. \nIntent i = new Intent(Intent.ACTION_VIEW, uri); // set flags \ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // to start activity \nstartActivity(i); \n} \n} \n}Run your app and see the output of the app.\nOutput:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210127150850/1611740152955.mp4"}, {"text": "\nAssets Folder in Android Studio\n\nIt can be noticed that unlike Eclipse ADT (App Development Tools), Android Studio doesn\u2019t contain an Assets folder in which we usually use to keep the web files like HTML. Assets provide a way to add arbitrary files like text, XML, HTML, fonts, music, and video in the application. If one tries to add these files as \u201cresources\u201c, Android will treat them into its resource system and you will be unable to get the raw data. If one wants to access data untouched, Assets are one way to do it. But the question arises is why in the asset folder? We can do the same things by creating a Resource Raw Folder. So let discuss how the assets folder is different from the Resource Raw folder?\nHow the asset folder is different from the Resource Raw folder?\nIn Android one can store the raw asset file like JSON, Text, mp3, HTML, pdf, etc in two possible locations:assets\nres/raw folderBoth of them appears to be the same, as they can read the file and generate InputStream as below// From assets\nassets.open(assetPathFilename)\n// From res/raw\nresources.openRawResource(resourceRawFilename)But when to use which folder?\nBelow is some guidance that might be helpful to choose\n1. Flexible File Name: (assets is better)assets: The developer can name the file name in any way, like having capital letters (fileName) or having space (file name).\nres/raw: In this case, the name of the file is restricted. File-based resource names must contain only lowercase a-z, 0-9, or underscore.2. Store in subdirectory: (possible in assets)assets: If the developer wants to categories the files into subfolders, then he/she can do it in assets like below.res/raw: In this case, files can only be in the root folder.3. Compile-time checking: (possible in res/raw)assets: Here, the way to read it into InputStream is given below. If the filename doesn\u2019t exist, then we need to catch it.assets.open(\u201cfilename\u201d)res/raw folder: Here, the way to read it into InputStream is:resources.openRawResource(R.raw.filename)So putting a file in the res/raw folder will provide ensure the correct file-name during compile time check.\n4. List filenames at runtime: (possible in assets)assets: If the developer wants to list all the files in the assets folder, he/she has used the list() function and provide the folder name or \u201d \u201c on the root folder as given below.assets.list(FOLDER_NAME)?.forEach { \n println(it)\n}res/raw: This is not possible in this folder. The developer has to know the filename during development, and not runtime.So, in assets, one can read the filename during runtime, list them, and use them dynamically. In res/raw, one needs to code them ready, perhaps in the string resources file.\n5. Filename accessible from XML: (possible in res/raw)assets: No simple way the developer can arrange an XML file (e.g. AndroidManifest.xml) to point to the file in the assets folder.\nres/raw: In any XML files like in Java, the developer can access the file in res/raw using @raw/filename easily.So if you need to access your file in any XML, put it in the res/raw folder. Let\u2019s make a table to remember the whole scenario easily.ScenarioAssets FolderRes/Raw FolderFlexible File NameYESNOStore in subdirectoryYESNOCompile-time checkingNOYESList filenames at runtimeYESNOFilename accessible from XMLNOYESHow to Create Assets Folder in Android Studio?\nNow let\u2019s discuss how to create an assets folder in the android studio. Below is the step-by-step process to create an assets folder in Android studio.\nStep 1: To create an asset folder in Android studio open your project in Android mode first as shown in the below image.Step 2: Go to the app > right-click > New > Folder > Asset Folder and create the asset folder.Step 3: Android Studio will open a dialog box. Keep all the settings default. Under the target source set, option main should be selected. and click on the finish button.Step 4: Now open the app folder and you will find the assets folder by the name of \u201cassets\u201d as shown in the below image."}, {"text": "\nTreeView in Android with Example\n\nIf you are looking for new UI designs to represent huge data, then there are so many ways to represent this type of data. You can use pie charts, graphs, and many more view types to implement these views. For displaying such huge data then we can prefer using a TreeView. TreeView is similar to that of a tree in which it has a parent node and inside that parent node, you can create multiple nodes according to requirement. In this example, we can take a look at creating a TreeView in your Android application. Now we will move towards the implementation of Tree View. We are going toimplement this project using both Java and Kotlin Programming Language for Android.\nWhat is TreeView and How it looks?\nTreeView is a pattern for the representation of data in the form of a tree so that it becomes easier for users to understand the organization of data in our app. A sample image is given below to get an idea of what TreeView looks like.Step By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Adding Dependency to the build.gradle File\nGo to Module build.gradle file and add this dependency and click on Sync Now button.\nimplementation 'de.blox.treeview:treeview:0.1.0'\nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n \n Create a new XML file\nAfter adding this TreeView create a new XML file for your node which we have to display inside our TreeView. For creating a new XML file navigate to the app > res > layout > Right-click > New > Layout Resource file. Give a name to your file (Here we have given tree_view_node) and click on create. After creating this file add the below code to it. Below is the code for thetree_view_node.xml file.XML \n \n Step 4: Working with the Java/Kotlin Files\nNow create a new class as View Holder for handling our nodes in Tree View. Here we have named the class as ViewHolder. Below is the code for the ViewHolder File.Java import android.view.View; \nimport android.widget.TextView; public class ViewHolder { TextView textView; ViewHolder(View view) { \ntextView = view.findViewById(R.id.idTvnode); \n} \n}Kotlin import android.view.View \nimport android.widget.TextView class ViewHolder internal constructor(view: View) { \nvar textView: TextView init { \ntextView = view.findViewById(R.id.idTvnode) \n} \n}After creating the Viewholder class then we will move towards the implementation of TreeView in our MainActivity File.\nIn MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle; \nimport android.view.View; \nimport androidx.annotation.NonNull; \nimport androidx.appcompat.app.AppCompatActivity; \nimport de.blox.treeview.BaseTreeAdapter; \nimport de.blox.treeview.TreeNode; \nimport de.blox.treeview.TreeView; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // creating a variable for tree view. \nTreeView treeView = findViewById(R.id.idTreeView); // creating adapter class for our treeview using basetree adapter. Inside base tree adapter \n// you have to pass viewholder class along with context and your layout file for treeview node. \nBaseTreeAdapter adapter = new BaseTreeAdapter(this, R.layout.tree_view_node) { \n@NonNull\n@Override\npublic Viewholder onCreateViewHolder(View view) { \nreturn new Viewholder(view); \n} @Override\npublic void onBindViewHolder(Viewholder viewHolder, Object data, int position) { \n// inside our on bind view holder method we are setting data from object to text view. \nviewHolder.textView.setText(data.toString()); } \n}; // below line is setting adapter for our tree. \ntreeView.setAdapter(adapter); // below tree node is a parent node of our tree node \n// which is Geeks for Geeks. \nTreeNode root = new TreeNode(\"Geeks for Geeks\"); // below node is the first child node of our \n// root node ie Geeks for Geeks. \nTreeNode DSAchildNode = new TreeNode(\"DSA\"); // below node is the second child of our \n// root node ie Geeks for Geeks. \nTreeNode AlgoChildNode = new TreeNode(\"Algorithm\"); // below node is the third child of our \n// root node ie Geeks for Geeks. \nTreeNode languageNode = new TreeNode(\"Language\"); // below node is the first child of our language node. \nTreeNode CchildNode = new TreeNode(\"C++\"); // below node is the second child of our language node. \nTreeNode javaChildNode = new TreeNode(\"Java\"); // below node is the first child of our DSA node. \nTreeNode arrayChild = new TreeNode(\"Arrays\"); // below node is the second child of our DSA node. \nTreeNode stringChild = new TreeNode(\"Strings\"); // below node is the first child of our Algorithm node. \nTreeNode sortingChildNode = new TreeNode(\"Sorting\"); // below lines is used for adding child nodes to our root nodes. \nroot.addChild(DSAchildNode); \nroot.addChild(languageNode); \nroot.addChild(AlgoChildNode); // below lines is used to add languages to our \n// Language node. we are adding c++, java \n// to our language node. \nlanguageNode.addChild(CchildNode); \nlanguageNode.addChild(javaChildNode); // below line is used to add arrays, strings \n// to our dsa node. we are adding Arrays, \n// Strings to our DSA node. \nDSAchildNode.addChild(arrayChild); \nDSAchildNode.addChild(stringChild); // below line is used for adding sorting \n// algo to our Algorithm node. \nAlgoChildNode.addChild(sortingChildNode); // below line is for setting our root node. \n// Inside our root node we are passing \n// \"root\" as our root node. \nadapter.setRootNode(root); \n} \n}Kotlin import android.os.Bundle \nimport android.view.View \nimport androidx.appcompat.app.AppCompatActivity \nimport de.blox.treeview.BaseTreeAdapter \nimport de.blox.treeview.TreeNode \nimport de.blox.treeview.TreeView class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // creating a variable for tree view. \nval treeView = findViewById(R.id.idTreeView) // creating adapter class for our treeview \n// using basetree adapter. Inside base tree adapter \n// you have to pass viewholder class along with \n// context and your layout file for treeview node. \nval adapter: BaseTreeAdapter = object : BaseTreeAdapter(this, R.layout.tree_view_node) { \nfun onCreateViewHolder(view: View?): Viewholder { \nreturn Viewholder(view) \n} fun onBindViewHolder(viewHolder: Viewholder, data: Any, position: Int) { \n// inside our on bind view holder method we \n// are setting data from object to text view. \nviewHolder.textView.setText(data.toString()) \n} \n} // below line is setting adapter for our tree. \ntreeView.setAdapter(adapter) // below tree node is a parent node of our \n// tree node which is Geeks for Geeks. \nval root = TreeNode(\"Geeks for Geeks\") // below node is the first child node of \n// our root node ie Geeks for Geeks. \nval DSAchildNode = TreeNode(\"DSA\") // below node is the second child of our \n// root node ie Geeks for Geeks. \nval AlgoChildNode = TreeNode(\"Algorithm\") // below node is the third child of our \n// root node ie Geeks for Geeks. \nval languageNode = TreeNode(\"Language\") // below node is the first child \n// of our language node. \nval CchildNode = TreeNode(\"C++\") // below node is the second \n// child of our language node. \nval javaChildNode = TreeNode(\"Java\") // below node is the first child of our DSA node. \nval arrayChild = TreeNode(\"Arrays\") // below node is the second child of our DSA node. \nval stringChild = TreeNode(\"Strings\") // below node is the first child of our Algorithm node. \nval sortingChildNode = TreeNode(\"Sorting\") // below lines is used for adding \n// child nodes to our root nodes. \nroot.addChild(DSAchildNode) \nroot.addChild(languageNode) \nroot.addChild(AlgoChildNode) // below lines is used to add languages \n// to our Language node. we are adding \n// c++, java to our language node. \nlanguageNode.addChild(CchildNode) \nlanguageNode.addChild(javaChildNode) // below line is used to add arrays, \n// strings to our dsa node. we are adding \n// Arrays,Strings to our DSA node. \nDSAchildNode.addChild(arrayChild) \nDSAchildNode.addChild(stringChild) // below line is used for adding sorting \n// algo to our Algorithm node. \nAlgoChildNode.addChild(sortingChildNode) // below line is for setting our root node. \n// Inside our root node we are passing \n// \"root\" as our root node. \nadapter.setRootNode(root) \n} \n}Output:"}, {"text": "\nHow to Create Classes in Android Studio?\n\nIn Android during the project development most of the time there is a need for classes in the projects. For example, in the case of CRUD operation, we need a model class to insert and retrieve data. Also to hold the info in our custom view we need to create a getter setter class. So basically in android, there are two types of classes we can create and we use frequently.Creating Java Class\nCreating Kotlin ClassSo in this article, we are going to create both Java and Kotlin class in Android studio.\nCreating Java Class in Android Studio\nA class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, java class declarations can include these components, in order:Modifiers: A class can be public or has default access (Refer this for details).\nclass keyword: class keyword is used to create a class.\nClass name:The name should begin with an initial letter (capitalized by convention).\nSuperclass(if any): The name of the class\u2019s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.\nInterfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.\nBody: The class bodysurrounded by braces, { }.Step by Step Implementation\nStep 1: Go to Android Studio and open the project in Android mode as shown in the below image.Step 2: Now go to the app > java > your package name > right-click > New > Java Class as shown in the below image.Step 3: After completing step 2 a pop-up screen will arise like below. Here enter your class name and choose Class and click the Enter button.After completing the above steps successfully you can find your Java class here. Go to the app > java > your package name> GeeksforGeeks.java. And you can write your own Java code here.Creating Kotlin Class in Android Studio\nLike Java, the class is a blueprint for the objects having similar properties. We need to define a class before creating an object and the class keyword is used to define a class. The kotlin class declaration consists of the class name, class header, and class body enclosed with curly braces.Syntax:\n// class header\nclass className { \n // class body\n}\nWhere:\nClass name: every class has a specific nameClass header: header consist of parameters and constructors of a classClass body: surrounded by curly braces, contains member functions and other propertyBoth the header and the class body are optional; if there is nothing in between curly braces then the class body can be omitted. For example:class emptyClassStep by Step Implementation\nStep 1: Go to Android Studio and open the project in Android mode as shown in the below image.Step 2: Now go to the app > java > your package name > right-click > New > Kotlin File/Class as shown in the below image.Step 3: After completing step 2 a pop-up screen will arise like below. Here enter your class name and choose Class and click the Enter button.After completing the above steps successfully you can find your Kotlin class here. Go to the app > java > your package name> GeeksforGeeks.kt. And you can write your own Kotlin code here."}, {"text": "\nHow to Use Firebase Firestore as a Realtime Database in Android?\n\nFirebase Firestore is the backend database that is used to add, read, update and delete data from Android. But in Firebase Firestore there is a separate method that is used to read data from Firebase Firestore in Realtime Database. In this article, we will read data from Firebase Firestore in Realtime Database. Note that we are going toimplement this project using theJavalanguage.\nWhat we are going to build in this article?We will be building a simple application in which we will be showing a simple TextView. Inside that TextView, we will be updating the data from Firebase Firestore on a real-time basis.\nStep by Step ImplementationStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Connect your app to Firebase\nAfter creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. \nimplementation \u2018com.google.firebase:firebase-firestore:22.0.1\u2019\nAfter adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. \nStep 3: Working with the AndroidManifest.xml file\nFor adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. XML\n \n Step 4: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML\n \n \n Step 5: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Javaimport android.os.Bundle;\nimport android.widget.TextView;\nimport android.widget.Toast;import androidx.annotation.Nullable;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.firebase.firestore.DocumentReference;\nimport com.google.firebase.firestore.DocumentSnapshot;\nimport com.google.firebase.firestore.EventListener;\nimport com.google.firebase.firestore.FirebaseFirestore;\nimport com.google.firebase.firestore.FirebaseFirestoreException;public class MainActivity extends AppCompatActivity { // creating a variable for text view.\n TextView updatedTV;\n \n // initializing the variable for firebase firestore\n FirebaseFirestore db = FirebaseFirestore.getInstance(); @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n // initializing our text view.\n updatedTV = findViewById(R.id.idTVUpdate);\n \n // creating a variable for document reference.\n DocumentReference documentReference = db.collection(\"MyData\").document(\"Data\");\n \n // adding snapshot listener to our document reference.\n documentReference.addSnapshotListener(new EventListener() {\n @Override\n public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) {\n // inside the on event method.\n if (error != null) {\n // this method is called when error is not null \n // and we get any error\n // in this case we are displaying an error message.\n Toast.makeText(MainActivity.this, \"Error found is \" + error, Toast.LENGTH_SHORT).show();\n return;\n }\n if (value != null && value.exists()) {\n // if the value from firestore is not null then we are getting\n // our data and setting that data to our text view.\n updatedTV.setText(value.getData().get(\"updateValue\").toString());\n }\n }\n });\n }\n}Step 6: Adding data to the Firebase Firestore console\nGo to the browser and open Firebase in your browser. After opening Firebase you will get to see the below page and on this page Click on Go to Console option in the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. Inside that screen click n Firebase Firestore Database in the left window. After clicking on the Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting on test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. To add data just click on the Start Collection button and provide the Collection ID as MyData. After that provide the Document ID as Data and inside the Field write down updateValue, and inside the Value provide your Text you want to display. And click on the Save button.You will get to see the data added inside the Firebase Console. After adding the data to Firebase. Now run your app and see the output of the app. You can change the value in the updateValue field and you can get to see Realtime update on your device.\nOutput:In the below video we are updating the data when the app is running and it is showing the Realtime Updates in our app.\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210113231717/Screenrecorder-2021-01-13-22-28-22-866.mp4\n"}, {"text": "\nLayouts in Android UI Design\n\nLayout Managers (or simply layouts) are said to be extensions of the ViewGroup class. They are used to set the position of child Views within the UI we are building. We can nest the layouts, and therefore we can create arbitrarily complex UIs using a combination of layouts.\nThere is a number of layout classes in the Android SDK. They can be used, modified or can create your own to make the UI for your Views, Fragments and Activities. You can display your contents effectively by using the right combination of layouts.\nThe most commonly used layout classes that are found in Android SDK are:FrameLayout- It is the simplest of the Layout Managers that pins each child view within its frame. By default the position is the top-left corner, though the gravity attribute can be used to alter its locations. You can add multiple children stacks each new child on top of the one before, with each new View potentially obscuring the previous ones.LinearLayout- A LinearLayout aligns each of the child View in either a vertical or a horizontal line. A vertical layout has a column of Views, whereas in a horizontal layout there is a row of Views. It supports a weight attribute for each child View that can control the relative size of each child View within the available space.RelativeLayout- It is flexible than other native layouts as it lets us to define the position of each child View relative to the other views and the dimensions of the screen.GridLayout- It was introduced in Android 4.0 (API level 14), the Grid Layout used a rectangular grid of infinitely thin lines to lay out Views in a series of rows and columns. The Grid Layout is incredibly flexible and can be used to greatly simplify layouts and reduce or eliminate the complex nesting often required to construct UIs using the layouts described before.Each of these layouts is designed to scale to suit the screen size of the host device by avoiding the used of absolute co- ordinates of the positions or predetermined pixel values. This makes the app suitable for the diverse set of Android devices.\n"}, {"text": "\nZigzag View in Android\n\nZig zag View is another best feature to beautify the user Experience in an Android app. You can get to see this Zig zag view in most of the eCommerce app. The main use of this Zig zag view is to make attractive banner ads in an app. Or to display images and text in this view. In this article, we are going to see how to implement Zig zag View in Android. A sample image is given below to get an idea about what we are going to do in this article.\nZig zag View in Android\nApplications of Zigzag ViewThe main use of the Zigzag view is to display attractive banner ads in an Android app.\nWith the help of this Zigzag view, we can display images and text in various patterns.\nUsing the Zigzag view in an app beautifies the User Experience.Attributes of Zigzag ViewAttributesDescriptionzigzagBackgroundColor\nTo give background color.zigzagPadding\nTo give padding from all sides.zigzagPaddingRight\nGive padding from the right.zigzagPaddingLeft\nGive Padding from Left.zigzagPaddingTop\nGive Padding from Top.zigzagPaddingBottom\nGive Padding from Bottom.zigzagSides\nTo give Zig zag pattern from sides (left, right, top, bottom).zigzagHeight\nheight of zigzag jagszigzagElevation\nside of shadowStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.\nStep 2: Add dependency of the library in build.gradle file\nFirst Navigate to gradle scripts and then to build.gradle(Project) level. Add the line given below in allprojects{} section.maven { url \u201chttps://jitpack.io\u201d }Then Navigate to gradle scripts and then to build.gradle(Module) level. Add below line in build.gradle file in the dependencies section.implementation \u2018com.github.beigirad:ZigzagView:1.2.0\u2019After adding dependency click on the \u201csync now\u201d option on the top right corner to sync the project.\nStep 3: Create a new Zigzag View in your activity_main.xml\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n \n \n \n \n Now click on the run button. It will take some time to build Gradle. And you will get an output on your device as given below.\nOutput:\nZigzag View in Android Output"}, {"text": "\nAndroid Animations in Kotlin\n\nAnimation is a method in which a collection of images are combined in a specific way and processed then they appear as moving images. Building animations make on-screen objects seem to be alive. Android has quite a few tools to help you create animations with relative ease. so in this article we will learn to create animations using Kotlin. below are some attributes which we are using while writing the code in xml.\nTable of Attributes :XML ATTRIBUTES\nDESCRIPTIONandroid:duration\nIt is used to specify the duration of animation to runandroid:fromAlpha\nIt is the starting alpha value for the animation,where 1.0 means fully opaque and 0.0 means fully transparentandroid:toAlpha\nIt is the ending alpha valueandroid:id\nSets unique id of the viewandroid:fromYDelta\nIt is the change in Y coordinate to be applied at the start of the animationandroid:toYDelta\nIt is the change in Y coordinate to be applied at the end of the animationandroid:startOffset\nDelay occur when an animation runs (in milliseconds), once start time is reached.android:pivotX\nIt represents the X-axis coordinates to zoom from starting point.android:pivotY\nIt represents the Y-axis coordinates to zoom from starting point.android:fromXScale\nStarting X size offset,android:fromYScale\nStarting Y size offset,android:toXScale\nEnding of X size offsetandroid:toYScale\nEnding of Y size offsetandroid:fromDegrees\nStarting angular position, in degrees.android:toDegrees\nEnding angular position, in degrees.android:interpolator\nAn interpolator defines the rate of change of an animationAt first, we will create a new android application. Then, we will create some animations.If you already created the project then ignore step 1.\nCreate New ProjectOpen Android Studio\nGo to File => New => New Project.\nThen, select Empty Activity and click on nextWrite application name as DynamicEditTextKotlin\nSelect minimum SDK as you need, here we have selected 21 as minimum SDK\nChoose language as Kotlin and click on finish button.If you have followed above process correctly, you will get a newly created project successfully.After creating project we will modify xml files. In xml file we will create one TextView where all the animations are performed and Eight Buttons for Eight different animations.\nModify activity_main.xml file\nOpen res/layout/activity_main.xml file and add code into it.XML \n\n \n\n\n \n \n \n\n \n \n \n\n \n \n \n\n \n \n \n \n After modifying the layout we will create xml files for animations. so we will first create a folder name anim.In this folder, we will be adding the XML files which will be used to produce the animations. For this to happen, go to app/res right click and then select, Android Resource Directory and name it as anim.\nbounce.xml\nIn this animation the text is bounce like a ball.XML \n\n \n \n \n fade_in.xml\nIn Fade In animation the text will appear from background.XML \n\n \n fade_out.xml\nIn Fade Out animation the colour of text is faded for a particular amount of time.XML \n\n \n rotate.xml\nIn rotate animation the text is rotated for a particular amount of time.XML \n slide_down.xml\nIn this animation the text will come from top to bottom.XML \n\n \n slide_up.xml\nIn this animation the text will go from bottom to top.XML \n \n zoom_in.xml\nIn this animation the text will appear bigger for a particular amount of time.XML \n\n\n \n zoom_out.xml\nIn this animation the text will appear smaller for a particular amount of time.XML \n\n\n \n After creating all animations in xml. we will create MainActivity.\nCreate MainActivity.kt file\nOpen app/src/main/java/net.geeksforgeeks.AnimationsInKotlin/MainActivity.kt file and add below code into it.Kotlin package net.geeksforgeeks.animationsinkotlinimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.os.Handler\nimport android.view.View\nimport android.view.animation.AnimationUtils\nimport kotlinx.android.synthetic.main.activity_main.*class MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)\nfade_in.setOnClickListener {\ntextView.visibility = View.VISIBLE\nval animationFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in)\ntextView.startAnimation(animationFadeIn)\n}\nfade_out.setOnClickListener {\nval animationFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out)\ntextView.startAnimation(animationFadeOut)\nHandler().postDelayed({\ntextView.visibility = View.GONE\n}, 1000)\n}\nzoom_in.setOnClickListener {\nval animationZoomIn = AnimationUtils.loadAnimation(this, R.anim.zoom_in)\ntextView.startAnimation(animationZoomIn)\n}\nzoom_out.setOnClickListener {\nval animationZoomOut = AnimationUtils.loadAnimation(this, R.anim.zoom_out)\ntextView.startAnimation(animationZoomOut)\n}\nslide_down.setOnClickListener {\nval animationSlideDown = AnimationUtils.loadAnimation(this, R.anim.slide_in)\ntextView.startAnimation(animationSlideDown)\n}\nslide_up.setOnClickListener {\nval animationSlideUp = AnimationUtils.loadAnimation(this, R.anim.slide_out)\ntextView.startAnimation(animationSlideUp)\n}\nbounce.setOnClickListener {\nval animationBounce = AnimationUtils.loadAnimation(this, R.anim.bounce)\ntextView.startAnimation(animationBounce)\n}\nrotate.setOnClickListener {\nval animationRotate = AnimationUtils.loadAnimation(this, R.anim.rotate)\ntextView.startAnimation(animationRotate)\n}\n}\n}As, AndroidManifest.xml file is very important file in android application, so below is the code of manifest file.\nAndroidManifest.xml file\nCode inside src/main/AndroidManifest.xml file would look like belowXML \n\n\n\n \n \n \n Run as Emulator:https://media.geeksforgeeks.org/wp-content/uploads/20191203180727/WhatsApp-Video-2019-12-03-at-6.04.23-PM.mp4\nYou can find the complete code here: https://github.com/missyadavmanisha/AnimationsInKotlin"}, {"text": "\nHow to add ColorSeekBar in Android\n\nSeekbar is a type of progress bar. We can drag the seekbar from left to right and vice versa and hence changes the current progress. ColorSeekbar is similar to seekbar but we use this to select a color from multiple colors and can select any custom color. With the help of this widget, we can give more control to the user to customize its application according to his need.\nApproach:Add the support Library in your root build.gradle file (not your module build.gradle file). This library jitpack is a novel package repository. It is made for JVM so that any library which is present in github and bigbucket can be directly used in the application. allprojects { \nrepositories { \nmaven { url \"https://jitpack.io\" } \n} \n} Add the support Library in build.gradle file and add dependency in the dependencies section. This library provides various inbuilt function which we can use to give users maximum independence to customize. dependencies { \nimplementation 'com.github.rtugeek:colorseekbar:1.7.7' \n} Now add a array of colors, custom_colors in strings.xml file in values directory.strings.xml - #219806
\n- #F44336
\n- #FFEB3B
Now add the following code in the activity_main.xml file.This will add a textview and a colorSeekbar in activity_main. In this file we add our array, custom_colors to the Seekbar.activity_main.xml \n Now add the following code in the MainActivity.java file. onClickListener is added with the seekbar. As the value is changes via seekbar the onClickListener is invoked and color of texts in textview changes.MainActivity.java package org.geeksforgeeks.colorseekbar; import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.widget.TextView; \nimport com.rtugeek.android.colorseekbar.ColorSeekBar; public class MainActivity \nextends AppCompatActivity { TextView textView; @Override\nprotected void onCreate( \nBundle savedInstanceState) \n{ super.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); textView = findViewById( \nR.id.text_view); \nColorSeekBar \ncolorSeekBar \n= findViewById( \nR.id.color_seek_bar); colorSeekBar.setOnColorChangeListener( \nnew ColorSeekBa \nr.OnColorChangeListener() { @Override\npublic void\nonColorChangeListener( \nint i, int i1, int i2) \n{ \ntextView \n.setTextColor(i2); \n} \n}); \n} \n} Output:https://media.geeksforgeeks.org/wp-content/uploads/20200515132427/Record_2020-05-15-13-23-04_1a4811e1943b5c025442b43456dabc2c.mp4"}, {"text": "\nScrollView in Android\n\nIn Android, a ScrollView is a view group that is used to make vertically scrollable views. A scroll view contains a single direct child only. In order to place multiple views in the scroll view, one needs to make a view group(like LinearLayout) as a direct child and then we can define many views inside it. A ScrollView supports Vertical scrolling only, so in order to create a horizontally scrollable view, HorizontalScrollView is used.\nXML attributes of ScrollViewAttributeDescriptionandroid:fillViewport\nDefines whether the scrollview should stretch its content to fill the viewport.Inherited Attributes:\nFrom FrameLayoutAttributesDescriptionandroid:measureAllChildren\nDetermines whether to measure all children or just those in the VISIBLE or INVISIBLE state when measuring. Defaults to false.From ViewAttributesDescriptionandroid:alpha\nalpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque).android:background\nA drawable to use as the background.android:clickable\nDefines whether this view reacts to click events.android:contentDescription\nDefines text that briefly describes content of the view.android:id\nSupply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById().android:isScrollContainer\nSet this if the view will serve as a scrolling container, meaning that it can be resized to shrink its overall window so that there will be space for an input method.android:minHeight\nDefines the minimum height of the view.android:minWidth\nDefines the minimum width of the view.android:onClick\nName of the method in this View\u2019s context to invoke when the view is clicked.android:padding\nSets the padding, in pixels, of all four edges.android:scrollbars\nDefines which scrollbars should be displayed on scrolling or not.From ViewGroupAttributesDescriptionandroid:addStatesFromChildren\nSets whether this ViewGroup\u2019s drawable states also include its children\u2019s drawable states.android:animateLayoutChanges\nDefines whether changes in layout should cause a LayoutTransition to run.android:clipChildren\nDefines whether a child is limited to draw inside of its bounds or not.android:clipToPadding\nDefines whether the ViewGroup will clip its children and resize any EdgeEffect to its padding, if padding is not zero.android:layoutAnimation\nDefines the layout animation to use the first time the ViewGroup is laid out.android:layoutMode\nDefines the layout mode of this ViewGroup.android:splitMotionEvents\nSets whether this ViewGroup should split MotionEvents to separate child views during touch event dispatch.Approach\nThis example demonstrates the steps involved to create a ScrollView in Android using Kotlin.\nStep 1: Create a new projectClick on File, then New => New Project.\nChoose \u201cEmpty Activity\u201d for the project template.\nSelect language as Kotlin.\nSelect the minimum SDK as per your need.Step 2: Modify strings.xml\nAdd some strings inside the strings.xml file to display those strings in the app.strings.xml \ngfgapp_scrollview \nKotlin is a statically typed, \ngeneral-purpose programming language developed \nby JetBrains, that has built world-class IDEs \nlike IntelliJ IDEA, PhpStorm, Appcode, etc. \nIt was first introduced by JetBrains in 2011 \nand a new language for the JVM. Kotlin is \nobject-oriented language, and a \u201cbetter language\u201d \nthan Java, but still be fully interoperable \nwith Java code. Kotlin is sponsored by Google, \nannounced as one of the official languages for \nAndroid Development in 2017. \nAdvantages of Kotlin language: \nEasy to learn \u2013 Basic is almost similar to java. \nIf anybody worked in java then easily understand \nin no time. Kotlin is multi-platform \u2013 Kotlin is \nsupported by all IDEs of java so you can write \nyour program and execute them on any machine \nwhich supports JVM. It\u2019s much safer than Java. \nIt allows using the Java frameworks and libraries \nin your new Kotlin projects by using advanced \nframeworks without any need to change the whole \nproject in Java. Kotlin programming language, \nincluding the compiler, libraries and all the \ntooling is completely free and open source and \navailable on github. Here is the link for \nGithub https://github.com/JetBrains/kotlin \nApplications of Kotlin language: \nYou can use Kotlin to build Android Application. \nKotlin can also compile to JavaScript, and making \nit available for the frontend. It is also designed \nto work well for web development and server-side \ndevelopment.Kotlin is a statically typed, general-purpose \nprogramming language developed by JetBrains that \nhas built world-class IDEs like IntelliJ IDEA, \nPhpStorm, Appcode, etc. It was first introduced \nby JetBrains in 2011.Kotlin is object-oriented \nlanguage and a better language than Java, but still \nbe fully interoperable with Java code. A constructor \nis a special member function that is invoked when \nan object of the class is created primarily to initialize \nvariables or properties. A class needs to have a constructor \nand if we do not declare a constructor, then the compiler \ngenerates a default constructor. \nKotlin has two types of constructors \u2013 \nPrimary Constructor \nSecondary Constructor \nA class in Kotlin can have at most one primary \nconstructor, and one or more secondary constructors. \nThe primary constructor \ninitializes the class, while the secondary \nconstructor is used \nto initialize the class and introduce some extra logic. \nExplanation: \nWhen we create the object add for the class then \nthe values 5 and 6 \npasses to the constructor. The constructor \nparameters a and b \ninitialize with the parameters 5 and 6 respectively. \nThe local variable c contains the sum of variables. \nIn the main, we access the property of \ncontructor using ${add.c}. \nExplanation: \nHere, we have initialized the constructor \nparameters with some \ndefault values emp_id = 100 and emp_name = \u201cabc\u201d. \nWhen the object emp is created we passed the values for \nboth the parameters so it prints those values. \nBut, at the time of object emp2 creation, \nwe have not passed \nthe emp_name so initializer block uses \nthe default values and \nprint to the standard output. \n Step 3: Modify activity_main.xml\nAdd the ScrollView and inside the ScrollView add a TextView to display the strings that are taken in the strings.xml file.activity_main.xml \n \n \n As already mentioned above, Scrollview can only contain one direct child. In this case, the child is textview. On noticing this textview you will realize that the text added inside textview is mentioned as @string/scrolltext which refers to a string resource inside the strings.xml file.\nStep 4: MainActivity.kt file\nThere is nothing to do with the MainActivity.kt file, so keep it as it is.MainActivity.kt package com.example.gfgapp_scrollview import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200706184324/scrollviewoutput.webm"}, {"text": "\nHow to Align Navigation Drawer and its Elements towards the Left or Right of the Screen in Android?\n\nThe Navigation Drawer is a layout that can be seen in certain applications, that consists of some other activity shortcuts (Intents). This drawer generally can be seen at the left edge of the screen, which is by default. A Button to access the Navigation Drawer is by default provided at the action bar.So now the question is why is it is necessary to align the Navigation Drawer and its elements towards the left or right of the screen. It is necessary because a screen can represent multiple layouts at a time. To keep all these elements fixed at desired positions, and sizes, each and every entity of these elements must be initialized. Though it is not necessary to initiate these entities in applications representing a single layout, it is always a better practice to initiate all the entities. In view of generating different styling for an application, one would like to implement a drawer toward the right of the screen with elements aligned towards left and other possible versions. Through this article, we want to extend the implementation of a Navigation Drawer and align it and its elements respectively.\nApproach\nStep 1: Create a New Project\nCreate a Navigation Drawer Activity in Android Studio. To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. As you click finish, the project builds, might take a minute or two.\nStep 2: Working with the activity_main.xml file\nWhen the setup is ready, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file for different cases. Note that we are going to modify only the activity_main.xml file in each case.\nAlign Navigation Drawer towards the Left of the screen:PS: \u201cltr\u201d means left to right.XML \n Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201001101902/Screen-Recording-2020-09-20-at-18.28.43.mp4\nAlign Navigation Drawer towards the Right of the screen:\nThe approach is quite similar to the previous one. Changes are made only within the drawer layout.PS: \u201crtl\u201d means right to leftXML \n Output: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201001101832/Screen-Recording-2020-09-20-at-18.10.16.mp4Align Navigation Drawer Elements towards the left of the Drawer (by Default):XML \n Output: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201001101951/Screen-Recording-2020-09-20-at-18.37.08.mp4\nAlign Navigation Drawer Elements towards the Right of the Drawer:XML \n Output: Run on Emulator\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201001101902/Screen-Recording-2020-09-20-at-18.28.43.mp4"}, {"text": "\nHow to Create an Animated Splash Screen in Android?\n\nPrerequisites: How to Create a Splash Screen in Android using Kotlin?\nAndroid Splash Screen is the first screen visible to the user when the application\u2019s launched. Splash Screen is the user\u2019s first experience with the application that\u2019s why it is considered to be one of the most vital screens in the application. It is used to display some information about the company logo, company name, etc. We can also add some animations to the Splash screen as well. In this article, we will be making an animated Splash Screen Using Kotlin.A sample GIF is given below to get an idea about what we are going to do in this article.Steps to Create an Animated Splash Screen\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.\nStep 2: Create an animation file\nTo create an animation file in android studio please follow the given instructions carefully. Go to the app > res > right-click > New > Android Resource Directory.Then name the directory name as anim and resource type anim (then it will show into your directory). And then click on OK.Go to the anim > right-click > New > Animation Resource File And name the file name as side_slide and click on OK.Now add this code to the animated XML file. Below is the code for theside_slide.xml file.XML \n\n \n Step 3: Create another activity\nGo to app > java > first package name > right-click > New > Activity > Empty Activity and create another activity and named it as SplashScreen. Edit the activity_splash_screen.xml file and add image, text in the splash screen as per the requirement. Here we are adding an image to the splash screen. Below is the code for theactivity_splash_screen.xml file.XML \n\n\n Go to the SplashScreen.kt file, and refer to the following code. Below is the code for theSplashScreen.kt file. Comments are added inside the code to understand the code in more detail.Kotlin import android.content.Intent\nimport android.os.Bundle\nimport android.os.Handler\nimport android.view.WindowManager\nimport android.view.animation.AnimationUtils\nimport android.widget.ImageView\nimport androidx.appcompat.app.AppCompatActivity@Suppress(\"DEPRECATION\")\nclass SplashScreen : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_splash_screen)// This is used to hide the status bar and make \n// the splash screen as a full screen activity.\nwindow.setFlags(\nWindowManager.LayoutParams.FLAG_FULLSCREEN,\nWindowManager.LayoutParams.FLAG_FULLSCREEN\n)// HERE WE ARE TAKING THE REFERENCE OF OUR IMAGE \n// SO THAT WE CAN PERFORM ANIMATION USING THAT IMAGE\nval backgroundImage: ImageView = findViewById(R.id.SplashScreenImage)\nval slideAnimation = AnimationUtils.loadAnimation(this, R.anim.side_slide)\nbackgroundImage.startAnimation(slideAnimation)// we used the postDelayed(Runnable, time) method \n// to send a message with a delayed time.\nHandler().postDelayed({\nval intent = Intent(this, MainActivity::class.java)\nstartActivity(intent)\nfinish()\n}, 3000) // 3000 is the delayed time in milliseconds.\n}\n}Step 4: Working with the AndroidManifest.xml file\nGo to the AndroidManifest.xml file and add the following code in the Splash Screen Activity. This is used to hide the status bar or action bar.android:theme=\u201d@style/Theme.AppCompat.Light.NoActionBar\u201dAlso, add inside the Splash Screen Activity to make this activity as the starting activity. So whenever the app will execute the user can see the splash screen at the beginning. Below is the complete code for theAndroidManifest.xml file.XML \n\n \n\n\n \n \n \n Step 5: Working with the activity_main.xml file\nGo to the activity_main.xml file and add a text which will show \u201cWelcome to GeeksforGeeks\u201d when the user will enter into the MainActivity. Below is the code for theactivity_main.xml file.XML \n\n Step 6: Working with the MainActivity.kt file\nDo nothing in the MainActivity.kt file as we already created a new activity for the Splash Screen. Below is the code for theMainActivity.kt fileKotlin import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Toastclass MainActivity : AppCompatActivity() {\noverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)\n}\n}Outputhttps://media.geeksforgeeks.org/wp-content/uploads/20201021231819/VID_20201021223534.mp4"}, {"text": "\nAndroid ListView in Kotlin\n\nAndroid ListView is a ViewGroup which is used to display the list of items in multiple rows and contains an adapter which automatically inserts the items into the list. The main purpose of the adapter is to fetch data from an array or database and insert each item that is placed into the list for the desired result. So, it is the main source to pull data from strings.xml file which contains all the required strings in Kotlin or XML files. \nIn this article, we will learn how to use Android ListView in Kotlin.\nAndroid Adapter The adapter holds the data fetched from an array and iterates through each item in the data set and generates the respective views for each item of the list. So, we can say it act as an intermediate between the data sources and adapter views such as ListView, and Gridview. \nTypes of AdaptersDifferent Types of Adapter are mentioned below:\nAdapter Type\nDescription\nArrayAdapter\nIt always accepts an Array or List as input. We can store the list items in the strings.xml file also.\nCursorAdapter\nIt always accepts an instance of the cursor as an input means \nSimpleAdapter\nIt mainly accepts static data defined in the resources like arrays or databases.\nBaseAdapter\n It is a generic implementation for all three adapter types and it can be used in the views according to our requirements.\nNow, we going to create an Android application named as ListViewInKotlin using an array adapter. Open an activity_main.xml file from \\res\\layout path and write the code like as shown below. \nactivity_main.xml file In this file, we declare the LisitView within LinearLayout and set its attributes. Later, we will access the ListView in the Kotlin file using the id. activity_main.xml\n\n \n \n MainActivity.ktWhen we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById. MainActivity.ktimport android.widget.ArrayAdapter\nimport android.widget.ListView\nclass MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) // use arrayadapter and define an array\n val arrayAdapter: ArrayAdapter<*>\n val users = arrayOf(\n \"Virat Kohli\", \"Rohit Sharma\", \"Steve Smith\",\n \"Kane Williamson\", \"Ross Taylor\"\n )\n \n // access the listView from xml file\n var mListView = findViewById(R.id.userlist)\n arrayAdapter = ArrayAdapter(this,\n android.R.layout.simple_list_item_1, users)\n mListView.adapter = arrayAdapter\n }\n}ListView Output: We need to run using Android Virtual Device(AVD) to see the output. Click Here to Learn More about Android Application Development with Kotlin\n"}, {"text": "\nAndroid | How to display Analog clock and Digital clock\n\nPre-requisites:Android App Development Fundamentals for Beginners\nGuide to Install and Set up Android Studio\nAndroid | Starting with first app/android project\nAndroid | Running your first Android appAnalog and digital clocks are used for display the time in android application.Analog clock: Analog clock is a subclass of View class. It represents a circular clock. Around the circle, numbers 1 to 12 appear to represent the hour and two hands are used to show instant of the time- shorter one for the hour and longer is for minutes.\nDigital clock: Digital clock is subclass of TextView Class and uses numbers to display the time in \u201cHH:MM\u201d format.For ExampleIn this Article, a simple android application is built to display the Analog clock and Digital clock. \nHow to create a Android Analog clock and Digital clock?\nThis example will help to develop an Android App that displays an Analog clock and a Digital clock according to the example shown above:\nBelow are the steps for Creating the Analog and Digital clock Android Application:Step1: Firstly create a new Android Application. This will create an XML file \u201cactivity_main.xml\u201d and a Java File \u201cMainActivity.Java\u201d. Please refer the pre-requisites to learn more about this step.Step2: Open \u201cactivity_main.xml\u201d file and add following widgets in a Relative Layout:An Analog clock\nA Digital clockThis will make the UI of the Application. There is no need for assignment of IDs as these widgets will display the time by themselves.Step3: Leave the Java file as it is.\nStep4: Now Run the app. Both clocks are displayed on the screen. The complete code of MainActivity.java and activity_main.xml of Analog Digital clock is given below: activity_main.xml \n \n MainActivity.java package org.geeksforgeeks.navedmalik.analogdigital; import android.support.v7.app.AppCompatActivity; \nimport android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \n} \n} Output:"}, {"text": "\nImageView in Android with Example\n\nImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kotlin. AnyClass.Application of ImageView is also in applying tints to an image in order to reuse a drawable resource and create overlays on background images. Moreover, ImageView is also used to control the size and movement of an image.\nAdding an ImageView to an Activity\nWhenever ImageView is added to an activity, it means there is a requirement for an image resource. Thus it is oblivious to provide an Image file to that ImageView class. It can be done by adding an image file that is present in the Android Studio itself or we can add our own image file. Android Studio owns a wide range of drawable resources which are very common in the android application layout. The following are the steps to add a drawable resource to the ImageView class.Note: The steps are performed on Android Studio version 4.0Open the activity_main.xml File in which the Image is to be AddedSwitch from the Code View to the Design View of the activity_main.xml FileFor adding an image from Android Studio, Drag the ImageView widget to the activity area of the application, a pop-up dialogue box will open choose from the wide range of drawable resources and click \u201cOK\u201c.For Adding an Image File other than Android Studio Drawable Resources:\nClick on the \u201cResource Manager\u201d tab on the leftmost panel and select the \u201cImport Drawables\u201d option.Select the path of the image file on your computer and click \u201cOK\u201c. After that set, the \u201cQualifier type\u201d and \u201cvalue\u201d of the image file according to your need and click \u201cNext\u201d then \u201cImport\u201c.Drag the ImageView class in the activity area, a pop-up dialogue box will appear which contains your imported image file. Choose your image file and click \u201cOK\u201c, your image will be added to the activity.Note: After adding an image set its constraints layout both vertically and horizontally otherwise it will show an error.XML Attributes of ImageViewXML AttributeDescriptionandroid:id\nTo uniquely identify an image viewandroid:src/app:srcCompat\nTo add the file path of the inserted imageandroid:background\nTo provide a background color to the inserted imageandroid:layout_width\nTo set the width of the imageandroid:layout_height\nTo set the height of the imageandroid:padding\nTo add padding to the image from the left, right, top, or bottom of the viewandroid:scaleType\nTo re-size the image or to move it in order to fix its sizeStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Working with the activity_main.xml FileWorking with the activity_main.xml File\nGo to the activity_main.xml File and refer to the following code. Below is the code for the activity_main.xml File.\nNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML \n \n Note: All the attributes of the ImageView which are starting with app:layout_constraint are the vertical and horizontal constraints to fix the image position in the activity. This is very necessary to add the constraint to the ImageView otherwise, all the images will take the position (0, 0) of the activity layout.Step 4: Working with the MainActivity File\nGo to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Since in the activity, only 2 images have been added and nothing else is being done like touching a button, etc. So, the MainActivity file will simply look like the below code i.e. no change.Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); \n} \n}Kotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) \n} \n}Output:"}, {"text": "\nThread Priority in Kotlin & Android\n\nEvery thread in a process has a Priority. They are in the range of 1 to 10. Threads are scheduled according to their priorities with the help of a Thread Scheduler.\nThere can be 3 priority constant set for a Thread which are:MIN_PRIORITY which equals to 1\nMAX_PRIORITY which equals to 10\nNORM_PRIORITY which is a default value and equals to 5Below is a code to check the priorities of two threads.\nChecking the current priorities of Threads: val t1 = Thread(Runnable{ \n// Some Activity \n}) val t2 \n= Thread(Runnable{ \n// Some Activity \n}) println(\"${t1.priority} ${t2.priority}\") Output: 5 5The output for both the threads are same as Default priority of a thread is 5.\nAssigning new priorities to Threads:\nBelow the two threads are assigned different priorities.Thread t1 is assigned 1 and thread t2 is assigned 10. Since Thread t1 has more priority, it shall start first and the remaining threads according to the priority. The priority can be declared implicitly or explicitly. val t1 = Thread(Runnable{ \n// Some Activity \n}) val t2= Thread(Runnable{ \n// Some Activity \n}) t1.priority= 1\nt2.priority = 10println(\"${t1.priority} ${t2.priority}\") Output : 1 10The same can be implemented in an Android application, below is an example.\nExample in Android:\nTry running the below program in Android to check the priorities of two threads declared within the code. When the user clicks the button, the thread with more priority starts. package com.example.gfg import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { \noverride fun onCreate(savedInstanceState: Bundle?) \n{ \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) val tv = findViewById(R.id.tv) \nval btn1= findViewById(R.id.btn1) val t1 = Thread(Runnable{ \ntv.text = \"t1 had more priority\" }) val t2= Thread(Runnable{ \ntv.text = \"t2 had more priority\" }) t1.priority= 1\nt2.priority = 10btn1.setOnClickListener{ \nwhen{ \nt1.priority < t2.priority -> t1.start() t2.priority < t1.priority -> t2.start() else -> tv.text = \n\"Both had same priority\"\n} \nbtn1.isEnabled = false\n} \n} \n} The below XML code is for the Layout. \n Output:"}, {"text": "\nHow to Create Dynamic GridView in Android using Firebase Firestore?\n\nGridView is also one of the most used UI components which is used to display items in the Grid format inside our app. By using this type of view we can display the items in the grid format. We have seen this type of GridView in most of the apps. We have also seen the implementation of GridView in our app. In this article, we will take a look at the implementation of GridView using Firebase Firestore in Android.\nWhat we are going to build in this article?We will be building a simple application in which we will be displaying the data in the grid format and we will load this data from Firebase Firestore inside our GridView. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.\nStep by Step ImplementationStep 1: Create a new Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. \nStep 2: Connect your app to Firebase\nAfter creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file to check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.\nimplementation \u2018com.google.firebase:firebase-firestore:22.0.1\u2019\nAfter adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. \nStep 3: Working with the AndroidManifest.xml file\nFor adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and Inside that file add the below permissions to it. XML\n \n Step 4: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML\n \n Step 5: Now we will create a new Java class for storing our data\nFor reading data from the Firebase Firestore database, we have to create an Object class and we will read data inside this class. For creating an object class, navigate to the app > java > your app\u2019s package name > Right-click on it and click on New > Java Class > Give a name to your class. Here we have given the name as DataModal and add the below code to it. Javapublic class DataModal { // variables for storing our image and name.\n private String name;\n private String imgUrl; public DataModal() {\n // empty constructor required for firebase.\n } // constructor for our object class.\n public DataModal(String name, String imgUrl) {\n this.name = name;\n this.imgUrl = imgUrl;\n } // getter and setter methods\n public String getName() {\n return name;\n } public void setName(String name) {\n this.name = name;\n } public String getImgUrl() {\n return imgUrl;\n } public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n}Step 6: Create a layout file for our item of GridView\nNavigate to the app > res > layout > Right-click on it and click on New > Layout Resource File and give a name to that file. After creating that file add the below code to it. Here we have given the name as image_gv_item and add the below code to it. XML\n \n \n Step 7: Now create an Adapter class for our GridView\nFor creating a new Adapter class navigate to the app > java > your app\u2019s package name > Right-click on it and Click on New > Java class and name your java class as CoursesGVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.Javaimport android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ArrayAdapter;\nimport android.widget.ImageView;\nimport android.widget.TextView;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.annotation.Nullable;import com.squareup.picasso.Picasso;import java.util.ArrayList;public class CoursesGVAdapter extends ArrayAdapter { // constructor for our list view adapter.\n public CoursesGVAdapter(@NonNull Context context, ArrayList dataModalArrayList) {\n super(context, 0, dataModalArrayList);\n } @NonNull\n @Override\n public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // below line is use to inflate the \n // layout for our item of list view.\n View listitemView = convertView;\n if (listitemView == null) {\n listitemView = LayoutInflater.from(getContext()).inflate(R.layout.image_gv_item, parent, false);\n }\n \n // after inflating an item of listview item\n // we are getting data from array list inside \n // our modal class.\n DataModal dataModal = getItem(position);\n \n // initializing our UI components of list view item.\n TextView nameTV = listitemView.findViewById(R.id.idTVtext);\n ImageView courseIV = listitemView.findViewById(R.id.idIVimage);\n \n // after initializing our items we are\n // setting data to our view.\n // below line is use to set data to our text view.\n nameTV.setText(dataModal.getName());\n \n // in below line we are using Picasso to load image\n // from URL in our Image VIew.\n Picasso.get().load(dataModal.getImgUrl()).into(courseIV); // below line is use to add item \n // click listener for our item of list view.\n listitemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // on the item click on our list view.\n // we are displaying a toast message.\n Toast.makeText(getContext(), \"Item clicked is : \" + dataModal.getName(), Toast.LENGTH_SHORT).show();\n }\n });\n return listitemView;\n }\n}Step 8: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Javaimport android.os.Bundle;\nimport android.widget.GridView;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.android.gms.tasks.OnFailureListener;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.firebase.firestore.DocumentSnapshot;\nimport com.google.firebase.firestore.FirebaseFirestore;\nimport com.google.firebase.firestore.QuerySnapshot;import java.util.ArrayList;\nimport java.util.List;public class MainActivity extends AppCompatActivity { // creating a variable for our \n // grid view, arraylist and \n // firebase Firestore.\n GridView coursesGV;\n ArrayList dataModalArrayList;\n FirebaseFirestore db; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n // below line is use to initialize our variables.\n coursesGV = findViewById(R.id.idGVCourses);\n dataModalArrayList = new ArrayList<>(); // initializing our variable for firebase\n // firestore and getting its instance.\n db = FirebaseFirestore.getInstance();\n \n // here we are calling a method \n // to load data in our list view.\n loadDatainGridView();\n } private void loadDatainGridView() {\n // below line is use to get data from Firebase\n // firestore using collection in android.\n db.collection(\"Data\").get()\n .addOnSuccessListener(new OnSuccessListener() {\n @Override\n public void onSuccess(QuerySnapshot queryDocumentSnapshots) {\n // after getting the data we are calling on success method\n // and inside this method we are checking if the received \n // query snapshot is empty or not.\n if (!queryDocumentSnapshots.isEmpty()) {\n // if the snapshot is not empty we are hiding our\n // progress bar and adding our data in a list.\n List list = queryDocumentSnapshots.getDocuments();\n for (DocumentSnapshot d : list) {\n \n // after getting this list we are passing\n // that list to our object class.\n DataModal dataModal = d.toObject(DataModal.class);\n \n // after getting data from Firebase \n // we are storing that data in our array list\n dataModalArrayList.add(dataModal);\n }\n // after that we are passing our array list to our adapter class.\n CoursesGVAdapter adapter = new CoursesGVAdapter(MainActivity.this, dataModalArrayList);\n \n // after passing this array list \n // to our adapter class we are setting \n // our adapter to our list view.\n coursesGV.setAdapter(adapter);\n } else {\n // if the snapshot is empty we are displaying a toast message.\n Toast.makeText(MainActivity.this, \"No data found in Database\", Toast.LENGTH_SHORT).show();\n }\n }\n }).addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n // we are displaying a toast message \n // when we get any error from Firebase.\n Toast.makeText(MainActivity.this, \"Fail to load data..\", Toast.LENGTH_SHORT).show();\n }\n });\n }\n}After adding the above code add the data to Firebase Firestore in Android. \nStep 9: Adding the data to Firebase Firestore in Android\nSearch for Firebase in your browser and go to that website and you will get to see the below screen. \nAfter clicking on Go to Console option. Click on your project which is shown below.\nAfter clicking on your project you will get to see the below screen. After clicking on this project you will get to see the below screen. After clicking on the Create Database option you will get to see the below screen. Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting test mode click on the Next option and you will get to see the below screen. Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we have to add the data inside our Firebase Console. For adding data to our Firebase Console.\nYou have to click on Start Collection Option and give the collection name as Data. After creating a collection you have to click on Autoid option for creating the first document. Then create two fields, one filed for \u201cname\u201d and one filed for \u201cimgUrl\u201d and enter the corresponding values for them. Note that specify the image URL link in the value for the imgUrl filed. And click on the Save button. Your first image to the Data has been added.\nSimilarly, add more images by clicking on the \u201cAdd document\u201d button.\nAfter adding these images run your app and you will get to see the output on the below screen.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210112113825/1610431550215.mp4\n"}, {"text": "\nRadioGroup in Kotlin\n\nRadioGroup class of Kotlin programming language is used to create a container which holds multiple RadioButtons. The RadioGroup class is beneficial for placing a set of radio buttons inside it because this class adds multiple-exclusion scope feature to the radio buttons. This feature assures that the user will be able to check only one of the radio buttons among all which belongs to a RadioGroup class. If the user checks another radio button, the RadioGroup class unchecks the previously checked radio button. This feature is very important when the developer wants to have only one answer to be selected such as asking the gender of a user.\nThe class hierarchy of the RadioGroup class in KotlinXML attributes of RadioGroup widgetXML Attributes\nDescriptionandroid:id\nTo uniquely identify the RadioGroupandroid:background\nTo set a background colourandroid:onClick\nA method to perform certain action when RadioGroup is clickedandroid:onClick\nIt\u2019s a name of the method to invoke when the radio button clicked.android:visibility\nUsed to control the visibility i.e., visible, invisible or goneandroid:layout_width\nTo set the widthandroid:layout_height\nTo set the heightandroid:contentDescription\nTo give a brief description of the viewandroid:checkedButton\nStores id of child radio button that needs to be checked by default within this radio groupandroid:orientation\nTo fix the orientation constant of the viewExample\nIn this example step by step demonstration of creating a RadioGroup will be covered, it consists of 5 RadioButton children which ask the user to choose a course offered by GeeksforGeeks. When the user checks one of the RadioButtons and clicks the Submit button a toast message appears which displays the selected option. \nNote: Following steps are performed on Android Studio version 4.0\nCreate new projectClick on File, then New => New Project.\nChoose \u201cEmpty Activity\u201d for the project template.\nSelect language as Kotlin.\nSelect the minimum SDK as per your need.Open activity_main.xml file\nBelow is the code for activity_main.xml file to add a RadioGroup and its 5 RadioButton children. A normal submit button is also added to accept and display the response selected by the user. \n \n \n Open MainActivity.kt file\nBelow is the code for MainActivity.kt file to access RadioGroup widget in kotlin file and show a proper message whenever a radio button is selected by the user. package com.example.sampleproject import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport android.view.View \nimport android.widget.Button \nimport android.widget.RadioButton \nimport android.widget.RadioGroup \nimport android.widget.Toast \nimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { \nvar radioGroup: RadioGroup? = null\nlateinit var radioButton: RadioButton \nprivate lateinit var button: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // Display name of the Application \ntitle = \"RadioGroup in Kotlin\"// Assigning id of RadioGroup \nradioGroup = findViewById(R.id.radioGroup1) // Assigning id of Submit button \nbutton = findViewById(R.id.submitButton) // Actions to be performed \n// when Submit button is clicked \nbutton.setOnClickListener { // Getting the checked radio button id \n// from the radio group \nval selectedOption: Int = radioGroup!!.checkedRadioButtonId // Assigning id of the checked radio button \nradioButton = findViewById(selectedOption) // Displaying text of the checked radio button in the form of toast \nToast.makeText(baseContext, radioButton.text, Toast.LENGTH_SHORT).show() \n} \n} \n} Modify strings.xml file\nAll the strings which are used in the activity, from the application name to the option of various RadioButtons are listed in this file. \nRadioGroup in Kotlin \nChoose a GfG course \nAmazon SDE Test Series \nPlacement 100 \nC++ STL \nCS Core Subjects \nDSA Self paced \nSubmit \n Output"}, {"text": "\nIntroduction to Fragments | Android\n\nFragment is a piece of an activity that enables a more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layouts for landscape and portrait orientation on a smartphone. The below image shows how two UI modules defined by fragments can be combined into one activity for a tablet design but separated for a handset design.Fragment Life Cycle\nAndroid fragments have their own life cycle very similar to an android activity.onAttach() : The fragment instance is associated with an activity instance. The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.onCreate() : The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.onCreateView() : The system calls this callback when it\u2019s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment\u2019s layout. You can return null if the fragment does not provide a UI.onActivityCreated() : The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context objectonStart() : The onStart() method is called once the fragment gets visible.onResume() : Fragment becomes active.onPause() : The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.onStop() : Fragment going to be stopped by calling onStop()onDestroyView() : Fragment view will destroy after call this methodonDestroy() :called to do final clean up of the fragment\u2019s state but Not guaranteed to be called by the Android platform.Types of Fragments\nSingle frame fragments : Single frame fragments are using for hand hold devices like mobiles, here we can show only one fragment as a view.List fragments : fragments having special list view is called as list fragmentFragments transaction : Using with fragment transaction. we can move one fragment to another fragment.Handling the Fragment Lifecycle\nA Fragment exist in three states:\nResumed : The fragment is visible in the running activity.Paused : Another activity is in the foreground and has focus, but the activity in which this fragment lives is still visible (the foreground activity is partially transparent or doesn\u2019t cover the entire screen).Stopped : The fragment is not visible. Either the host activity has been stopped or the fragment has been removed from the activity but added to the back stack. A stopped fragment is still alive (all state and member information is retained by the system). However, it is no longer visible to the user and will be killed if the activity is killed.The effect of the activity lifecycle on the fragment lifecycle : \nDefining and using fragments To define a new fragment we either extend the android.app.Fragment class or one of its subclasses.Javapackage com.saket.geeksforgeeks.demo;import android.app.Fragment;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\npublic class DetailFragment extends Fragment { \n \n @Override \n public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){ \n View view = inflater.inflate(R.layout.fragment_rssitem_detail,container, false); \n return view; \n } \n public void setText(String text){ \n TextView view = (TextView) getView().findViewById(R.id.detailsText); \n view.setText(text); \n }\n}Kotlin//code conntribute by rony \npackage com.example.databinding.fragment\nimport android.os.Bundle\nimport androidx.fragment.app.Fragment\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport com.example.databinding.R\nclass fragment2 : Fragment() {\n override fun onCreateView(\n inflater: LayoutInflater, container: ViewGroup?,\n savedInstanceState: Bundle?\n ): View? {\n // Inflate the layout for this fragment\n var view =inflater.inflate(R.layout.fragment_fragment2, container, false)\n return view\n }\n}Fragment Transaction: While for an dynamic activity we are set buttons for an interactive UI. If we are set after clicking the button the fragment should appear then we have to get help from Fragment Manager. It handle all the fragment in an activity. We need to set fragment transaction with the help of fragment manager and and begin transaction, and then simply replace the layout of the fragment with desired place.Java /* this code is contributed by rohansadhukhan9 */\n Button B = findViewById(R.id.button);\n B.setOnClickListener(new View.OnClickListener) {\n @Override\n public void onClick(View v) {\n fragment f = new fragment();\n FragmentTransaction t = getSupportFragmentManeger().beginTransaction();\n t.replace(R.id.fragment_layout, f).commit();\n }\n }Kotlin//code contribute by rony\nval B = findViewById(R.id.button)\nB.setOnClickListener {\n replace(fragment2())\n }\n }\n private fun replace(fragment: Fragment) {\n val fragmentManager=supportFragmentManager\n val fragmentTransaction=fragmentManager.beginTransaction()\n fragmentTransaction.replace(R.id.fragment_layout,fragment)\n fragmentTransaction.commit()\n }\n} "}, {"text": "\nMVP (Model View Presenter) Architecture Pattern in Android with Example\n\nIn the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing mechanism. Further, it causes difficulties in the maintenance and scaling of such mobile applications. To avoid such problems in maintainability, readability, scalability, and refactoring of applications, developers prefer to define well-separated layers of code. By applying software architecture patterns, one can organize the code of the application to separate the concerns. MVP (Model \u2014 View \u2014 Presenter) architecture is one of the most popular architecture patterns and is valid in organizing the project.\nMVP (Model \u2014 View \u2014 Presenter) comes into the picture as an alternative to the traditional MVC (Model \u2014 View \u2014 Controller) architecture pattern. Using MVC as the software architecture, developers end up with the following difficulties:Most of the core business logic resides in Controller. During the lifetime of an application, this file grows bigger and it becomes difficult to maintain the code.\nBecause of tightly-coupled UI and data access mechanisms, both Controller and View layer falls in the same activity or fragment. This cause problem in making changes in the features of the application.\nIt becomes hard to carry out Unit testing of the different layer as most of the part which are under testing needs Android SDK components.MVP pattern overcomes these challenges of MVC and provides an easy way to structure the project codes. The reason why MVP is widely accepted is that it provides modularity, testability, and a more clean and maintainable codebase. It is composed of the following three components:Model: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: UI(User Interface) layer. It provides the visualization of the data and keep a track of the user\u2019s action in order to notify the Presenter.\nPresenter: Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user\u2019s input notification from the View.Key Points of MVP ArchitectureCommunication between View-Presenter and Presenter-Model happens via an interface(also called Contract).\nOne Presenter class manages one View at a time i.e., there is a one-to-one relationship between Presenter and View.\nModel and View class doesn\u2019t have knowledge about each other\u2019s existence.Example of MVP Architecture\nTo show the implementation of the MVP architecture pattern on projects, here is an example of a single activity android application. The application will display some strings on the View(Activity) by doing a random selection from the Model. The role of the Presenter class is to keep the business logic of the application away from the activity. Below is the complete step-by-step implementation of this android application. Note that we are going to implement the project using both Java and Kotlin language.Note: Following steps are performed on Android Studio version 4.0Step 1: Create a new projectClick on File, then New => New Project.\nChoose Empty activity\nSelect language as Java/Kotlin\nSelect the minimum SDK as per your need.Step 2: Modify String.xml file\nAll the strings which are used in the activity are listed in this file.XML \nGfG | MVP Architecture \nDisplay Next Course \nMVP Architecture Pattern \nGeeksforGeeks Computer Science Online Courses \nCourse Description \n Step 3: Working with the activity_main.xml file\nOpen the activity_main.xml file and add a Button, a TextView to display the string, and a Progress Bar to give a dynamic feel to the application. Below is the code for designing a proper activity layout.XML \n \n \n \n \n \n Step 4: Defining the Contract Interface file for the Model, View, and Presenter\nTo establish communication between View-Presenter and Presenter-Model, an interface is needed. This interface class will contain all abstract methods which will be defined later in the View, Model, and Presenter class.Java public interface Contract { \ninterface View { \n// method to display progress bar \n// when next random course details \n// is being fetched \nvoid showProgress(); // method to hide progress bar \n// when next random course details \n// is being fetched \nvoid hideProgress(); // method to set random \n// text on the TextView \nvoid setString(String string); \n} interface Model { // nested interface to be \ninterface OnFinishedListener { \n// function to be called \n// once the Handler of Model class \n// completes its execution \nvoid onFinished(String string); \n} void getNextCourse(Contract.Model.OnFinishedListener onFinishedListener); \n} interface Presenter { // method to be called when \n// the button is clicked \nvoid onButtonClick(); // method to destroy \n// lifecycle of MainActivity \nvoid onDestroy(); \n} \n}Kotlin interface Contract { \ninterface View { \n// method to display progress bar \n// when next random course details \n// is being fetched \nfun showProgress() // method to hide progress bar \n// when next random course details \n// is being fetched \nfun hideProgress() // method to set random \n// text on the TextView \nfun setString(string: String?) \n} interface Model { \n// nested interface to be \ninterface OnFinishedListener { \n// function to be called \n// once the Handler of Model class \n// completes its execution \nfun onFinished(string: String?) \n} fun getNextCourse(onFinishedListener: OnFinishedListener?) \n} interface Presenter { \n// method to be called when \n// the button is clicked \nfun onButtonClick() // method to destroy \n// lifecycle of MainActivity \nfun onDestroy() \n} \n}Step 5: Creating the Model class\nCreate a new class named Model to separate all string data and the methods to fetch those data. This class will not know the existence of View Class.Java import android.os.Handler; import java.util.Arrays; \nimport java.util.List; \nimport java.util.Random; public class Model implements Contract.Model { // array list of strings from which \n// random strings will be selected \n// to display in the activity \nprivate List arrayList = Arrays.asList( \n\"DSA Self Paced: Master the basics of Data Structures and Algorithms to solve complex problems efficiently. \", \n\"Placement 100: This course will guide you for placement with theory,lecture videos, weekly assignments \" + \n\"contests and doubt assistance.\", \n\"Amazon SDE Test Series: Test your skill & give the final touch to your preparation before applying for \" + \n\"product based against like Amazon, Microsoft, etc.\", \n\"Complete Interview Preparation: Cover all the important concepts and topics required for the interviews. \" + \n\"Get placement ready before the interviews begin\", \n\"Low Level Design for SDE 1 Interview: Learn Object-oriented Analysis and Design to prepare for \" + \n\"SDE 1 Interviews in top companies\"\n); @Override\n// this method will invoke when \n// user clicks on the button \n// and it will take a delay of \n// 1200 milliseconds to display next course detail \npublic void getNextCourse(final OnFinishedListener listener) { \nnew Handler().postDelayed(new Runnable() { \n@Override\npublic void run() { \nlistener.onFinished(getRandomString()); \n} \n}, 1200); \n} // method to select random \n// string from the list of strings \nprivate String getRandomString() { \nRandom random = new Random(); \nint index = random.nextInt(arrayList.size()); \nreturn arrayList.get(index); \n} \n}Kotlin import android.os.Handler \nimport java.util.* class Model : Contract.Model { \n// array list of strings from which \n// random strings will be selected \n// to display in the activity \nprivate val arrayList = \nArrays.asList( \n\"DSA Self Paced: Master the basics of Data Structures and Algorithms to solve complex problems efficiently. \", \n\"Placement 100: This course will guide you for placement with theory,lecture videos, weekly assignments \" + \n\"contests and doubt assistance.\", \n\"Amazon SDE Test Series: Test your skill & give the final touch to your preparation before applying for \" + \n\"product based against like Amazon, Microsoft, etc.\", \n\"Complete Interview Preparation: Cover all the important concepts and topics required for the interviews. \" + \n\"Get placement ready before the interviews begin\", \n\"Low Level Design for SDE 1 Interview: Learn Object-oriented Analysis and Design to prepare for \" + \n\"SDE 1 Interviews in top companies\"\n) // this method will invoke when \n// user clicks on the button \n// and it will take a delay of \n// 1200 milliseconds to display next course detail \noverride fun getNextCourse(onFinishedListener: Contract.Model.OnFinishedListener?) { \nHandler().postDelayed({ onFinishedListener!!.onFinished(getRandomString) }, 1200) \n} // method to select random \n// string from the list of strings \nprivate val getRandomString: String \nprivate get() { \nval random = Random() \nval index = random.nextInt(arrayList.size) \nreturn arrayList[index] \n} \n}Step 6: Creating the Presenter class\nThe methods of this class contain core business logic which will decide what to display and how to display. It triggers the View class to make the necessary changes to the UI.Java public class Presenter implements Contract.Presenter, Contract.Model.OnFinishedListener { // creating object of View Interface \nprivate Contract.View mainView; // creating object of Model Interface \nprivate Contract.Model model; // instantiating the objects of View and Model Interface \npublic Presenter(Contract.View mainView, Contract.Model model) { \nthis.mainView = mainView; \nthis.model = model; \n} @Override\n// operations to be performed \n// on button click \npublic void onButtonClick() { \nif (mainView != null) { \nmainView.showProgress(); \n} \nmodel.getNextCourse(this); \n} @Override\npublic void onDestroy() { \nmainView = null; \n} @Override\n// method to return the string \n// which will be displayed in the \n// Course Detail TextView \npublic void onFinished(String string) { \nif (mainView != null) { \nmainView.setString(string); \nmainView.hideProgress(); \n} \n} \n}Kotlin // instantiating the objects of View and Model Interface \n// creating object of View Interface \n// creating object of Model Interface \nclass Presenter( \nprivate var mainView: Contract.View?, \nprivate val model: Contract.Model) : Contract.Presenter, \nContract.Model.OnFinishedListener { // operations to be performed \n// on button click \noverride fun onButtonClick() { \nif (mainView != null) { \nmainView!!.showProgress() \n} \nmodel.getNextCourse(this) \n} override fun onDestroy() { \nmainView = null\n} // method to return the string \n// which will be displayed in the \n// Course Detail TextView \noverride fun onFinished(string: String?) { \nif (mainView != null) { \nmainView!!.setString(string) \nmainView!!.hideProgress() \n} \n} }Step 7: Define functionalities of View in the MainActivity file\nThe View class is responsible for updating the UI according to the changes triggered by the Presenter layer. The data provided by the Model will be used by View and the appropriate changes will be made in the activity.Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.view.View; \nimport android.widget.Button; \nimport android.widget.ProgressBar; \nimport android.widget.TextView; import static android.view.View.GONE; public class MainActivity extends AppCompatActivity implements Contract.View { // creating object of TextView class \nprivate TextView textView; // creating object of Button class \nprivate Button button; // creating object of ProgressBar class \nprivate ProgressBar progressBar; // creating object of Presenter interface in Contract \nContract.Presenter presenter; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // assigning ID of the TextView \ntextView = findViewById(R.id.textView); // assigning ID of the Button \nbutton = findViewById(R.id.button); // assigning ID of the ProgressBar \nprogressBar = findViewById(R.id.progressBar); // instantiating object of Presenter Interface \npresenter = new Presenter(this, new Model()); // operations to be performed when \n// user clicks the button \nbutton.setOnClickListener(new View.OnClickListener() { \n@Override\npublic void onClick(View v) { \npresenter.onButtonClick(); \n} \n}); \n} @Override\nprotected void onResume() { \nsuper.onResume(); \n} @Override\nprotected void onDestroy() { \nsuper.onDestroy(); \npresenter.onDestroy(); \n} @Override\n// method to display the Course Detail TextView \npublic void showProgress() { \nprogressBar.setVisibility(View.VISIBLE); \ntextView.setVisibility(View.INVISIBLE); \n} @Override\n// method to hide the Course Detail TextView \npublic void hideProgress() { \nprogressBar.setVisibility(GONE); \ntextView.setVisibility(View.VISIBLE); \n} @Override\n// method to set random string \n// in the Course Detail TextView \npublic void setString(String string) { \ntextView.setText(string); \n} \n}Kotlin import android.os.Bundle \nimport android.view.View \nimport android.widget.Button \nimport android.widget.ProgressBar \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity(), Contract.View { \n// creating object of TextView class \nprivate var textView: TextView? = null// creating object of Button class \nprivate var button: Button? = null// creating object of ProgressBar class \nprivate var progressBar: ProgressBar? = null// creating object of Presenter interface in Contract \nvar presenter: Presenter? = null\noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // assigning ID of the TextView \ntextView = findViewById(R.id.textView) // assigning ID of the Button \nbutton = findViewById(R.id.button) // assigning ID of the ProgressBar \nprogressBar = findViewById(R.id.progressBar) // instantiating object of Presenter Interface \npresenter = Presenter(this, Model()) // operations to be performed when \n// user clicks the button \nthis.button!!.setOnClickListener(View.OnClickListener { presenter!!.onButtonClick() }) \n} override fun onResume() { \nsuper.onResume() \n} override fun onDestroy() { \nsuper.onDestroy() \npresenter!!.onDestroy() \n} // method to display the Course Detail TextView \noverride fun showProgress() { \nprogressBar!!.visibility = View.VISIBLE \ntextView!!.visibility = View.INVISIBLE \n} // method to hide the Course Detail TextView \noverride fun hideProgress() { \nprogressBar!!.visibility = View.GONE \ntextView!!.visibility = View.VISIBLE \n} // method to set random string \n// in the Course Detail TextView \noverride fun setString(string: String?) { \ntextView!!.text = string \n} \n}Outputhttps://media.geeksforgeeks.org/wp-content/uploads/20201025195251/MVP-Output-Recording.mp4\nAdvantages of MVP ArchitectureNo conceptual relationship in android components\nEasy code maintenance and testing as the application\u2019s model, view, and presenter layer are separated.Disadvantages of MVP ArchitectureIf the developer does not follow the single responsibility principle to break the code then the Presenter layer tends to expand to a huge all-knowing class."}, {"text": "\nSimpleAdapter in Android with Example\n\nIn Android, whenever we want to bind some data which we get from any data source (e.g. ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView, etc.) then Adapter comes into the picture. Basically Adapter acts as a bridge between the UI component and data sources. Here Simple Adapter is one type of Adapter. It is basically an easy adapter to map static data to views defined in our XML file(UI component) and is used for customization of List or Grid items. Here we use an ArrayList of Map (e.g. hashmap, mutable map, etc.) for data-backing. Each entry in an ArrayList is corresponding to one row of a list. The Map contains the data for each row. Now to display the row we need a view for which we used to specify a custom list item file (an XML file).\nGeneral Syntax of SimpleAdapterSimpleAdapter(Context context, List extends Map> data, int resource, String[] from, int[] to)\n***Here context, data, resource, from, and to are five parameters*** Parameters DataTypeExplanationcontext\nContext\nWhen we make an object of SimpleAdapter class It is used to pass the context ( The reference of current activity).dataList extends Map>\n*** it means a List of Maps whose key\u2018s type is String and Value can be any datatype.Each element of the List is different Maps that contain the data of each row and should include all the entries specified in the \u201cfrom\u201d string array. In our project, we shall use ArrayList.resourceint\n***Integer DatatypeThis parameter is used to pass the resource id of the layout ( XML file ) which should contain the different views of each row of the list. The layout file should include at least those named views defined in \u201cto\u201d.from\nAn array of String type\nA list of column names that will be added to the Map associated with each item. In this array, there should be a column name for each item (Views) of each row of the list.to\nAn array of int type.\nThis array parameter stores the ids of different views that should display the column in the \u201cfrom\u201d parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the \u201cfrom\u201d parameter.Example\nA sample image is given below to get an idea about what we are going to do in this article. In this project, we are going to make this application which has a list of some fruits and in each row of the list has a fruit image and name. Note that we are going to implement this same project in both Kotlin and Java languages. Now you choose your preferred language. Step by Step Implementation\nStep 1: Create a New Project\nOpen Android Studio > Create New Project > Select an Empty Activity > Give a project name (Here our project name is \u201cGFG_SimpleAdapter\u201c).*** Here you can choose either Kotlin or Java which you preferred and choose the API level according to your choice.\n***After creating the project successfully, please paste some pictures into the drawable folder in the res directory. Now you can use the same pictures which I have used in my project otherwise you can choose pictures of your own choice. To download the same pictures please click on the below-given link:\nCLICK HERE\n***please note that it is optional***Step 2: Working with the activity_main.xml file\nIn the activity_main.xml file, create a ListView inside a RelativeLayout. Below is the code for the activity_main.xml file.XML \n\n activity_main.xml Interface:Step 3: Create another XML file (named list_row_items) and create UI for each row of the ListView\nCreate a new Layout Resource file and name it as list_row_items. Below is the code for the list_row_items.xml file.XML \n\n \n list_row_items.xml Interface:Step 4: Working with the MainActivity file\nHere we will show you how to implement SimpleAdapter both in Java and Kotlin. Now you choose your preferred one. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.widget.ListView;\nimport android.widget.SimpleAdapter;\nimport androidx.appcompat.app.AppCompatActivity;\nimport java.util.ArrayList;\nimport java.util.HashMap;public class MainActivity extends AppCompatActivity {ListView listView;// creating a String type array (fruitNames)\n// which contains names of different fruits' images\nString fruitNames[] = {\"Banana\", \"Grape\", \"Guava\", \"Mango\", \"Orange\", \"Watermelon\"};// creating an Integer type array (fruitImageIds) which\n// contains IDs of different fruits' images\nint fruitImageIds[] = {R.drawable.banana,\nR.drawable.grape,\nR.drawable.guava,\nR.drawable.mango,\nR.drawable.orange,\nR.drawable.watermelon};@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// Binding the ListView of activity_main.xml file\n// with this java code in MainActivity.java\nlistView = findViewById(R.id.listView);// creating an ArrayList of HashMap.The kEY of the HashMap\n// is a String and VALUE is of any datatype(Object)\nArrayList> list = new ArrayList<>();// By a for loop, entering different types of data in HashMap,\n// and adding this map including it's datas into the ArrayList\n// as list item and this list is the second parameter of the SimpleAdapter\nfor (int i = 0; i < fruitNames.length; i++) {// creating an Object of HashMap class\nHashMap map = new HashMap<>();// Data entry in HashMap\nmap.put(\"fruitName\", fruitNames[i]);\nmap.put(\"fruitImage\", fruitImageIds[i]);// adding the HashMap to the ArrayList\nlist.add(map);\n}// creating A string type array(from) which contains\n// column names for each View in each row of the list\n// and this array(form) is the fourth parameter of the SimpleAdapter\nString[] from = {\"fruitName\", \"fruitImage\"};// creating an integer type array(to) which contains\n// id of each View in each row of the list\n// and this array(form) is the fifth parameter of the SimpleAdapter\nint to[] = {R.id.textView, R.id.imageView};// creating an Object of SimpleAdapter class and\n// passing all the required parameters\nSimpleAdapter simpleAdapter = new SimpleAdapter(getApplicationContext(), list, R.layout.list_row_items, from, to);// now setting the simpleAdapter to the ListView\nlistView.setAdapter(simpleAdapter);\n}\n}Kotlin import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.ListView\nimport android.widget.SimpleAdapter\nimport java.util.ArrayList\nimport java.util.HashMapclass MainActivity : AppCompatActivity() {private lateinit var listView:ListView// creating a String type array \n// (fruitNames) which contains \n// names of different fruits' images \nprivate val fruitNames=arrayOf(\"Banana\",\"Grape\",\"Guava\",\"Mango\",\"Orange\",\"Watermelon\")// creating an Integer type array (fruitImageIds) which\n// contains IDs of different fruits' images \nprivate val fruitImageIds=arrayOf(R.drawable.banana,\nR.drawable.grape,\nR.drawable.guava,\nR.drawable.mango,\nR.drawable.orange,\nR.drawable.watermelon) override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// ViewBinding the ListView of activity_main.xml file \n// with this kotlin code in MainActivity.kt\nlistView=findViewById(R.id.listView) // creating an ArrayList of HashMap.The kEY of the HashMap is\n// a String and VALUE is of any datatype(Any)\nval list=ArrayList>()// By a for loop, entering different types of data in HashMap,\n// and adding this map including it's datas into the ArrayList\n// as list item and this list is the second parameter of the SimpleAdapter\nfor(i in fruitNames.indices){\nval map=HashMap()// Data entry in HashMap\nmap[\"fruitName\"] = fruitNames[i]\nmap[\"fruitImage\"]=fruitImageIds[i]// adding the HashMap to the ArrayList\nlist.add(map)\n}// creating A string type array(from) which contains \n// column names for each View in each row of the list\n// and this array(form) is the fourth parameter of the SimpleAdapter\nval from=arrayOf(\"fruitName\",\"fruitImage\") // creating an integer type array(to) which contains \nid of each View in each row of the list\nand this array(form) is the fifth parameter of the SimpleAdapter*/val to= intArrayOf(R.id.textView,R.id.imageView) // creating an Object of SimpleAdapter\n// class and passing \n// all the required parameters\nval simpleAdapter=SimpleAdapter(this,list,R.layout.list_row_items,from,to) // now setting the simpleAdapter\n// to the ListView\nlistView.adapter = simpleAdapter\n}\n}Thus SimpleAdapter holds data and sends the data to the adapter view then the view can take the data from the adapter view and shows the data on the ListView which we have created earlier.\n***Please note you have to choose any one language between Java and Kotlin as MainActivity for a particular project***Output:https://media.geeksforgeeks.org/wp-content/uploads/20201130004640/video-output.mp4"}, {"text": "\nButton in Android\n\nIn Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio.\nThe Class Hierarchy of the Button Class in KotlinXML Attributes of Button WidgetXML Attributes\nDescription\nandroid:idUsed to specify the id of the view.android:textUsed to the display text of the button.android:textColorUsed to the display color of the text.android:textSizeUsed to the display size of the text.android:textStyleUsed to the display style of the text like Bold, Italic, etc.android:textAllCapsUsed to display text in Capital letters.android:backgroundUsed to set the background of the view.android:paddingUsed to set the padding of the view.android:visibilityUsed to set the visibility of the view.android:gravityUsed to specify the gravity of the view like center, top, bottom, etcExampleIn this example step by step demonstration of creating a Button will be covered. The application will consist of a button that displays a toast message when the user taps on it.\nNote: Following steps are performed on Android Studio version 4.0\nStep 1: Create a new projectClick on File, then New => New Project.Choose \u201cEmpty Activity\u201d for the project template.Select language as Kotlin.Select the minimum SDK as per your need.Step 2: Modify the strings.xml fileNavigate to the strings.xml file under the \u201cvalues\u201d directory of the resource folder. This file will contain all strings that are used in the Application. Below is the appropriate code.strings.xml\n GfG | Button In Kotlin \n Button \n Hello Geeks!! This is a Button. \n Step 3: Modify the activity_main.xml fileAdd a button widget in the layout of the activity. Below is the code of the activity_main.xml file which does the same. activity_main.xml\n \n Step 4: Accessing the button in the MainActivity fileAdd functionality of button in the MainActivity file. Here describe the operation to display a Toast message when the user taps on the button. Below is the code to carry out this task.Javaimport androidx.appcompat.app.AppCompatActivity;\nimport android.content.Context;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.Toast;public class MainActivity extends AppCompatActivity { @Override\n protected void onCreate( Bundle savedInstanceState ) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); // storing ID of the button\n // in a variable\n Button button = (Button)findViewById(R.id.button); // operations to be performed\n // when user tap on the button\n if (button != null) {\n button.setOnClickListener((View.OnClickListener)(new View.OnClickListener() {\n public final void onClick(View it) { // displaying a toast message\n Toast.makeText((Context)MainActivity.this, R.string.message, Toast.LENGTH_LONG).show();\n }\n }));\n }\n }\n}Kotlinimport androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.Toastclass MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) // storing ID of the button\n // in a variable\n val button = findViewById(R.id.button) // operations to be performed\n // when user tap on the button\n button?.setOnClickListener()\n {\n // displaying a toast message\n Toast.makeText(this@MainActivity, R.string.message, Toast.LENGTH_LONG).show() }\n }\n}Output:\n"}, {"text": "\nSimpleExpandableListAdapter in Android with Example\n\nAndroid ExpandableListView is a view that is used to shows items as a vertically scrolling two-level list. The basic difference with ListView is it allows two levels of the display which are groups that can be easily expanded and collapsed by touching to view and their respective children\u2019s items. In order to show the view, ExpandableListViewAdapter is used in android. In many apps, an ExpandableListView facility is required. For example:In a \u201ccity\u201d app(for any city), if the user wants to see a list of engineering colleges/list of art colleges/list of medical colleges, etc.,\nList of vegetables/List of fruits/List of Nuts etc., for a \u201cjiomart\u201d kind of app\nList of Hatchback/List of crosscut/List of Sedan etc., for a \u201cUber\u201d kind of appImportant MethodsMethodsDescriptionsetChildIndicator(Drawable)Current state indicator for each item If the child is\nthe last child for a group, the state state_last will be setsetGroupIndicator(Drawable)To represent the state either expanded or collapsed.state_expanded is the\nstate if the group is expanded, state_collapsed if the state of the group\nis collapsed, state_empty if there are no groups.getGroupView()\nUsed to get the view for the list group headergetChildView()\nUsed to get the view for list child itemThe Notable InterfacesInterfacesDescriptionExpandableListView.OnChildClickListener\nWhen a child in the expanded list is clicked, this is overriddenExpandableListView.OnGroupClickListener\nWhen a group header in the expanded list is clicked, this is overriddenExpandableListView.OnGroupCollapseListener\nWhen a group is collapsed, this method notifiesExpandableListView.OnGroupExpandListener\nWhen a group is expanded, this method notifiesExample\nLet us see the ways to implement SimpleExpandableListAdapter in Android with a List of vegetables/List of fruits/List of Nuts in the ExpandableListAdapter. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theJavalanguage.Step 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Create the dimens.xml file\nGo to app > res > values > right-click > New > Values Resource File and name the file as dimens. In this file dimension related information is given here. Below is the code for the dimens.xml file.XML \n\n16dp \n16dp \n Step 3: Working with the XML filesTo design the UI, code is present under the res\\layout folder in the form of XML. They are used in the Activity files and once the XML file is in scope inside the activity, one can access the components present in the XML. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n\n \nGo to app > res > layout > New > Layout Resource File and name the file as list_group. Below is the code for the list_group.xml file.XML \n Next is for layout row for child items. This is done via a list_item.xml file. Go to app > res > layout > New > Layout Resource File and name the file as list_item. Below is the code for the list_item.xml file.XML \n With the above XML, UI design elements are complete. Next is, a java file to populate the contents of the list.Step 4: Working with the Java filesGo to app > java > your package name > Right-click > New > Java Class and name the file as ExpandableListDataItems. Below is the code for the ExpandableListDataItems.java file. Comments are added inside the code to understand the code in more detail.Java import java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;public class ExpandableListDataItems {\npublic static HashMap> getData() {\nHashMap> expandableDetailList = new HashMap>();// As we are populating List of fruits, vegetables and nuts, using them here\n// We can modify them as per our choice.\n// And also choice of fruits/vegetables/nuts can be changed\nList fruits = new ArrayList();\nfruits.add(\"Apple\");\nfruits.add(\"Orange\");\nfruits.add(\"Guava\");\nfruits.add(\"Papaya\");\nfruits.add(\"Pineapple\");List vegetables = new ArrayList();\nvegetables.add(\"Tomato\");\nvegetables.add(\"Potato\");\nvegetables.add(\"Carrot\");\nvegetables.add(\"Cabbage\");\nvegetables.add(\"Cauliflower\");List nuts = new ArrayList();\nnuts.add(\"Cashews\");\nnuts.add(\"Badam\");\nnuts.add(\"Pista\");\nnuts.add(\"Raisin\");\nnuts.add(\"Walnut\");// Fruits are grouped under Fruits Items. Similarly the rest two are under\n// Vegetable Items and Nuts Items respectively.\n// i.e. expandableDetailList object is used to map the group header strings to\n// their respective children using an ArrayList of Strings.\nexpandableDetailList.put(\"Fruits Items\", fruits);\nexpandableDetailList.put(\"Vegetable Items\", vegetables);\nexpandableDetailList.put(\"Nuts Items\", nuts);\nreturn expandableDetailList;\n}\n}Go to app > java > your package name > Right-click > New > Java Class and name the file as CustomizedExpandableListAdapter. Below is the code for the CustomizedExpandableListAdapter.java file. This java class extends BaseExpandableListAdapter and it overrides the methods which are required for the ExpandableListView. Comments are added inside the code to understand the code in more detail.Java import android.content.Context;\nimport android.graphics.Typeface;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.BaseExpandableListAdapter;\nimport android.widget.TextView;\nimport java.util.HashMap;\nimport java.util.List;public class CustomizedExpandableListAdapter extends BaseExpandableListAdapter {private Context context;\nprivate List expandableTitleList;\nprivate HashMap> expandableDetailList;// constructor\npublic CustomizedExpandableListAdapter(Context context, List expandableListTitle,\nHashMap> expandableListDetail) {\nthis.context = context;\nthis.expandableTitleList = expandableListTitle;\nthis.expandableDetailList = expandableListDetail;\n}@Override\n// Gets the data associated with the given child within the given group.\npublic Object getChild(int lstPosn, int expanded_ListPosition) {\nreturn this.expandableDetailList.get(this.expandableTitleList.get(lstPosn)).get(expanded_ListPosition);\n}@Override\n// Gets the ID for the given child within the given group.\n// This ID must be unique across all children within the group. Hence we can pick the child uniquely\npublic long getChildId(int listPosition, int expanded_ListPosition) {\nreturn expanded_ListPosition;\n}@Override\n// Gets a View that displays the data for the given child within the given group.\npublic View getChildView(int lstPosn, final int expanded_ListPosition, \nboolean isLastChild, View convertView, ViewGroup parent) {\nfinal String expandedListText = (String) getChild(lstPosn, expanded_ListPosition);\nif (convertView == null) {\nLayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\nconvertView = layoutInflater.inflate(R.layout.list_item, null);\n}\nTextView expandedListTextView = (TextView) convertView.findViewById(R.id.expandedListItem);\nexpandedListTextView.setText(expandedListText);\nreturn convertView;\n}@Override\n// Gets the number of children in a specified group.\npublic int getChildrenCount(int listPosition) {\nreturn this.expandableDetailList.get(this.expandableTitleList.get(listPosition)).size();\n}@Override\n// Gets the data associated with the given group.\npublic Object getGroup(int listPosition) {\nreturn this.expandableTitleList.get(listPosition);\n}@Override\n// Gets the number of groups.\npublic int getGroupCount() {\nreturn this.expandableTitleList.size();\n}@Override\n// Gets the ID for the group at the given position. This group ID must be unique across groups.\npublic long getGroupId(int listPosition) {\nreturn listPosition;\n}@Override\n// Gets a View that displays the given group.\n// This View is only for the group--the Views for the group's children\n// will be fetched using getChildView()\npublic View getGroupView(int listPosition, boolean isExpanded, View convertView, ViewGroup parent) {\nString listTitle = (String) getGroup(listPosition);\nif (convertView == null) {\nLayoutInflater layoutInflater = (LayoutInflater) this.context.\ngetSystemService(Context.LAYOUT_INFLATER_SERVICE);\nconvertView = layoutInflater.inflate(R.layout.list_group, null);\n}\nTextView listTitleTextView = (TextView) convertView.findViewById(R.id.listTitle);\nlistTitleTextView.setTypeface(null, Typeface.BOLD);\nlistTitleTextView.setText(listTitle);\nreturn convertView;\n}@Override\n// Indicates whether the child and group IDs are stable across changes to the underlying data.\npublic boolean hasStableIds() {\nreturn false;\n}@Override\n// Whether the child at the specified position is selectable.\npublic boolean isChildSelectable(int listPosition, int expandedListPosition) {\nreturn true;\n}\n}Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.view.View;\nimport android.widget.ExpandableListAdapter;\nimport android.widget.ExpandableListView;\nimport android.widget.Toast;\nimport androidx.appcompat.app.AppCompatActivity;\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;public class MainActivity extends AppCompatActivity {ExpandableListView expandableListViewExample;\nExpandableListAdapter expandableListAdapter;\nList expandableTitleList;\nHashMap> expandableDetailList;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);\nexpandableListViewExample = (ExpandableListView) findViewById(R.id.expandableListViewSample);\nexpandableDetailList = ExpandableListDataItems.getData();\nexpandableTitleList = new ArrayList(expandableDetailList.keySet());\nexpandableListAdapter = new CustomizedExpandableListAdapter(this, expandableTitleList, expandableDetailList);\nexpandableListViewExample.setAdapter(expandableListAdapter);// This method is called when the group is expanded\nexpandableListViewExample.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {\n@Override\npublic void onGroupExpand(int groupPosition) {\nToast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + \" List Expanded.\", Toast.LENGTH_SHORT).show();\n}\n});// This method is called when the group is collapsed\nexpandableListViewExample.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {\n@Override\npublic void onGroupCollapse(int groupPosition) {\nToast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition) + \" List Collapsed.\", Toast.LENGTH_SHORT).show();\n}\n});// This method is called when the child in any group is clicked\n// via a toast method, it is shown to display the selected child item as a sample\n// we may need to add further steps according to the requirements\nexpandableListViewExample.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {\n@Override\npublic boolean onChildClick(ExpandableListView parent, View v,\nint groupPosition, int childPosition, long id) {\nToast.makeText(getApplicationContext(), expandableTitleList.get(groupPosition)\n+ \" -> \"\n+ expandableDetailList.get(\nexpandableTitleList.get(groupPosition)).get(\nchildPosition), Toast.LENGTH_SHORT\n).show();\nreturn false;\n}\n});\n}\n}Output: Run On Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20200924151037/Sample-Emulator-Output.mp4\nConclusion\nExpandableListView is a very useful mandatory feature used in many apps. In mobile app sizes and in the available space, in order to show multiple items, one should need features like ExpandableListView and ExpandableListAdapter the view can be fit perfectly. As the scrolling is available, we can keep information on many levels. The methods support expanding the header, collapsing the header, selecting the child items perfectly as seen in the emulator output. For simplicity, we have provided with Toast messages. Depends upon the requirements, we can able to add further coding to match with it."}, {"text": "\nView Binding with Fragments in Android Jetpack\n\nIn the Previous article View Binding in Android Jetpack, it\u2019s been discussed why acquiring the ViewBinding feature in the Android project provides a lot of benefits. But when it comes to ViewBinding with fragments the scenario changes. Because the lifecycle of the Fragment is different and that of activity is different Here also things go the same as discussed in the above article the naming conventions of the fragment layout are changed to pascal case and properties of the fragment layout to camel case. For Example, fragment1.xml -> Fragment1Binding and edit_text(id) which is under the fragment\u2019s layout changes to eEditText(camel case) So in this article ViewBinding is discussed using Fragments. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going toimplement this project using theKotlinlanguage.https://media.geeksforgeeks.org/wp-content/uploads/20210121173103/Untitled-Project.mp4\nStep by Step Implementation\nStep 1: Create a new empty activity projectUsing Android Studio create an empty Activity Android Studio project. Refer to Android | How to Create/Start a New Project in Android Studio?.Step 2: Enable the ViewBinding featureEnable the ViewBinding feature by invoking the following code snippet inside the app-level build.gradle file, and click on the \u201cSync Now\u201d buttons which appear on the top-right corner.buildFeatures {\n viewBinding = true\n}Refer to the following image if unable to locate the app-level build.gradle file invokes the above build feature.Step 3: Working with the activity_main.xml fileThe main layout of the activity contains two buttons, to toggle fragment 1 and fragment 2, and one Framelayout to hold the fragments inside the CardView. And one Submit button to check when pressed whose fragment\u2019s data is submitted.\nTo implement the same invoke the following code inside the activity_main.xml file.XML \n Output UI:Step 4: Creating two fragmentsCreate two fragments, which include text view to represent fragment number edit text and a button. To implement the UI of each fragment you may refer to the following codes.\nFragment 1:XML \n\n Fragment 2:XML \n\n Step 5: Working with the Fragments.kt filesFirstly the binding variable which is nullable is assigned to null initially, and also when the view of the fragment gets destroyed, again it has to be set null (which in this case _binding).\nAnd to avoid the null check of the nullable binding object, by using the backing property of the kotlin we make another copy of the binding variable (which in this case binding).\nHowever, if the fragment wants to access the views from the host activity, can be done using the findViewById() method.\nInvoke the following code inside each of the fragment\u2019s .kt files. Comments are added for better understanding.\nFragment 1:Kotlin import android.os.Bundle \nimport android.view.LayoutInflater \nimport android.view.View \nimport android.view.ViewGroup \nimport android.widget.Button \nimport android.widget.Toast \nimport androidx.fragment.app.Fragment // Enter your package name here \nimport com.adityamshidlyali.gfgarticle.databinding.Fragment1Binding class ExampleFragment1 : Fragment() { // assign the _binding variable initially to null and \n// also when the view is destroyed again it has to be set to null \nprivate var _binding: Fragment1Binding? = null// with the backing property of the kotlin we extract \n// the non null value of the _binding \nprivate val binding get() = _binding!! override fun onCreateView( \ninflater: LayoutInflater, container: ViewGroup?, \nsavedInstanceState: Bundle? \n): View { // inflate the layout and bind to the _binding \n_binding = Fragment1Binding.inflate(inflater, container, false) // retrieve the entered data by the user \nbinding.doneButton1.setOnClickListener { \nval str: String = binding.editText1.text.toString() \nif (str.isNotEmpty()) { \nToast.makeText(activity, str, Toast.LENGTH_SHORT).show() \n} else { \nToast.makeText(activity, \"Please Enter Data\", Toast.LENGTH_SHORT).show() \n} \n} // handle the button from the host activity using findViewById method \nval submitButton: Button = activity!!.findViewById(R.id.submit_button) \nsubmitButton.setOnClickListener { \nToast.makeText(activity, \"Host Activity Element Clicked from Fragment 1\", Toast.LENGTH_SHORT).show() \n} // Inflate the layout for this fragment \nreturn binding.root \n} override fun onDestroyView() { \nsuper.onDestroyView() \n_binding = null\n} \n}Fragment 2:Kotlin import android.os.Bundle \nimport android.view.LayoutInflater \nimport android.view.View \nimport android.view.ViewGroup \nimport android.widget.Button \nimport android.widget.Toast \nimport androidx.fragment.app.Fragment // Enter your package name here \nimport com.adityamshidlyali.gfgarticle.databinding.Fragment2Binding class ExampleFragment2 : Fragment() { // assign the _binding variable initially to null and \n// also when the view is destroyed again it has to be \n// set to null \nprivate var _binding: Fragment2Binding? = null// with the backing property of the kotlin \n// we extract \n// the non null value of the _binding \nprivate val binding get() = _binding!! override fun onCreateView( \ninflater: LayoutInflater, container: ViewGroup?, \nsavedInstanceState: Bundle? \n): View { // inflate the layout and bind to the _binding \n_binding = Fragment2Binding.inflate(inflater, container, false) // retrieve the entered data by the user \nbinding.doneButton2.setOnClickListener { \nval str: String = binding.editText2.text.toString() \nif (str.isNotEmpty()) { \nToast.makeText(activity, str, Toast.LENGTH_SHORT).show() \n} else { \nToast.makeText(activity, \"Please Enter Data\", Toast.LENGTH_SHORT).show() \n} \n} // handle the button from the host activity using findViewById method \nval submitButton: Button = activity!!.findViewById(R.id.submit_button) \nsubmitButton.setOnClickListener { \nToast.makeText(activity, \"Host Activity Element Clicked from Fragment 2\", Toast.LENGTH_SHORT).show() \n} // Inflate the layout for this fragment \nreturn binding.root \n} override fun onDestroyView() { \nsuper.onDestroyView() \n_binding = null\n} \n}Step 6: Working with the MainActivity.kt fileIn the MainActivity.kt file only the transaction functionality of the fragments is implemented. Refer to the following code and its output for better understanding.Kotlin import androidx.appcompat.app.AppCompatActivity \nimport android.os.Bundle \nimport androidx.fragment.app.Fragment \nimport com.adityamshidlyali.gfgarticle.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { // create binding instance for the activity_main.xml \nprivate lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nbinding = ActivityMainBinding.inflate(layoutInflater) \nsetContentView(binding.root) // when app is initially opened the Fragment 1 should be visible \nsupportFragmentManager.beginTransaction().apply { \nreplace(binding.fragmentHolder.id, ExampleFragment1()) \naddToBackStack(null) \ncommit() \n} // handle the fragment 2 button to toggle the fragment 2 \nbinding.fragment1B.setOnClickListener { \nchangeFragment(ExampleFragment1()) \n} // handle the fragment 2 button to toggle the fragment 2 \nbinding.fragment2B.setOnClickListener { \nchangeFragment(ExampleFragment1()) \n} \n} // function to change the fragment which is used to reduce the lines of code \nprivate fun changeFragment(fragmentToChange: Fragment): Unit { \nsupportFragmentManager.beginTransaction().apply { \nreplace(binding.fragmentHolder.id, fragmentToChange) \naddToBackStack(null) \ncommit() \n} \n} \n}Output:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210121173103/Untitled-Project.mp4"}, {"text": "\nFirebase Authentication with Phone Number OTP in Android\n\nMany apps require their users to be authenticated. So for the purpose of authenticating the apps uses phone number authentication inside their apps. In phone authentication, the user has to verify his identity with his phone number. Inside the app user has to enter his phone number after that he will receive a verification code on his mobile number. He has to enter that verification code and verify his identity. So this is how phone authentication works. Firebase provides so many ways for authentication users such as Google, Email and Password, Phone, and many more. In this article, we will take a look at the implementation of Phone Authentication inside our App using Firebase.\nWhat we are going to build in this article?\nWe will be creating a simple application which is having two screens. The first screen will be our Verification screen on which the user has to add his phone number. After adding his phone number, the user will click on the Get OTP button after that Firebase will send OTP on that number which is mentioned above. After receiving that OTP user has to enter that OTP in the below text filed and click on the below button to verify with entered OTP. After clicking on the verify button Firebase will verify that OTP and allow the user to enter into the home screen only when entered OTP is correct else the user will get an error message. Note that we are going toimplement this project using theJavalanguage.\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Connect your app to Firebase\nAfter creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Authentication and then email and password authentication.After clicking on email and password authentication you will get to see the below screen. Inside this screen click on the first option connect to firebase and after that click on the second option to add Firebase authentication to your app. Step 3: Verify that dependency for Firebase authentication is added inside your app\nAfter connecting your app to Firebase. Make sure to add this dependency in your build.gradle file if not added. After adding this dependency sync your project. Note: Make sure to add the exact dependency version in the above image because the latest dependency is not having the implementation for auto-detection of OTP.Step 4: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n\n \n \n \n Step 5: Add permissions for the internet in your Manifest.xml file\nNavigate to the app > AndroidManifest.xml file and add the below permissions to it. XML \n Step 6: Create a new Activity for our Home Page\nNavigate to the app > java > your app\u2019s package name > Right-click on your app\u2019s package name and click on New > Activity > Empty Activity and name your activity. Here we have given it a name as HomeActivity.\nStep 7: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.content.Intent;\nimport android.os.Bundle;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.android.gms.tasks.OnCompleteListener;\nimport com.google.android.gms.tasks.Task;\nimport com.google.android.gms.tasks.TaskExecutors;\nimport com.google.firebase.FirebaseException;\nimport com.google.firebase.auth.AuthResult;\nimport com.google.firebase.auth.FirebaseAuth;\nimport com.google.firebase.auth.PhoneAuthCredential;\nimport com.google.firebase.auth.PhoneAuthProvider;import java.util.concurrent.TimeUnit;public class MainActivity extends AppCompatActivity {// variable for FirebaseAuth class\nprivate FirebaseAuth mAuth;// variable for our text input \n// field for phone and OTP.\nprivate EditText edtPhone, edtOTP;// buttons for generating OTP and verifying OTP\nprivate Button verifyOTPBtn, generateOTPBtn;// string for storing our verification ID\nprivate String verificationId;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// below line is for getting instance\n// of our FirebaseAuth.\nmAuth = FirebaseAuth.getInstance();// initializing variables for button and Edittext.\nedtPhone = findViewById(R.id.idEdtPhoneNumber);\nedtOTP = findViewById(R.id.idEdtOtp);\nverifyOTPBtn = findViewById(R.id.idBtnVerify);\ngenerateOTPBtn = findViewById(R.id.idBtnGetOtp);// setting onclick listener for generate OTP button.\ngenerateOTPBtn.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {\n// below line is for checking whether the user\n// has entered his mobile number or not.\nif (TextUtils.isEmpty(edtPhone.getText().toString())) {\n// when mobile number text field is empty\n// displaying a toast message.\nToast.makeText(MainActivity.this, \"Please enter a valid phone number.\", Toast.LENGTH_SHORT).show();\n} else {\n// if the text field is not empty we are calling our \n// send OTP method for getting OTP from Firebase.\nString phone = \"+91\" + edtPhone.getText().toString();\nsendVerificationCode(phone);\n}\n}\n});// initializing on click listener\n// for verify otp button\nverifyOTPBtn.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {\n// validating if the OTP text field is empty or not.\nif (TextUtils.isEmpty(edtOTP.getText().toString())) {\n// if the OTP text field is empty display \n// a message to user to enter OTP\nToast.makeText(MainActivity.this, \"Please enter OTP\", Toast.LENGTH_SHORT).show();\n} else {\n// if OTP field is not empty calling \n// method to verify the OTP.\nverifyCode(edtOTP.getText().toString());\n}\n}\n});\n}private void signInWithCredential(PhoneAuthCredential credential) {\n// inside this method we are checking if \n// the code entered is correct or not.\nmAuth.signInWithCredential(credential)\n.addOnCompleteListener(new OnCompleteListener() {\n@Override\npublic void onComplete(@NonNull Task task) {\nif (task.isSuccessful()) {\n// if the code is correct and the task is successful\n// we are sending our user to new activity.\nIntent i = new Intent(MainActivity.this, HomeActivity.class);\nstartActivity(i);\nfinish();\n} else {\n// if the code is not correct then we are\n// displaying an error message to the user.\nToast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();\n}\n}\n});\n}private void sendVerificationCode(String number) {\n// this method is used for getting\n// OTP on user phone number.\nPhoneAuthOptions options =\nPhoneAuthOptions.newBuilder(mAuth)\n.setPhoneNumber(number) // Phone number to verify\n.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit\n.setActivity(this) // Activity (for callback binding)\n.setCallbacks(mCallBack) // OnVerificationStateChangedCallbacks\n.build();\nPhoneAuthProvider.verifyPhoneNumber(options);\n}// callback method is called on Phone auth provider.\nprivate PhoneAuthProvider.OnVerificationStateChangedCallbacks// initializing our callbacks for on\n// verification callback method.\nmCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {// below method is used when \n// OTP is sent from Firebase\n@Override\npublic void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {\nsuper.onCodeSent(s, forceResendingToken);\n// when we receive the OTP it \n// contains a unique id which \n// we are storing in our string \n// which we have already created.\nverificationId = s;\n}// this method is called when user \n// receive OTP from Firebase.\n@Override\npublic void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {\n// below line is used for getting OTP code\n// which is sent in phone auth credentials.\nfinal String code = phoneAuthCredential.getSmsCode();// checking if the code\n// is null or not.\nif (code != null) {\n// if the code is not null then\n// we are setting that code to \n// our OTP edittext field.\nedtOTP.setText(code);// after setting this code \n// to OTP edittext field we \n// are calling our verifycode method.\nverifyCode(code);\n}\n}// this method is called when firebase doesn't\n// sends our OTP code due to any error or issue.\n@Override\npublic void onVerificationFailed(FirebaseException e) {\n// displaying error message with firebase exception.\nToast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();\n}\n};// below method is use to verify code from Firebase.\nprivate void verifyCode(String code) {\n// below line is used for getting \n// credentials from our verification id and code.\nPhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationId, code);// after getting credential we are \n// calling sign in method.\nsignInWithCredential(credential);\n}\n}Step 8: Working on HomeActivity\nNow we have authenticated our user and move towards our Home Activity. Now we will display a welcome message to our user on successful authentication. For this Navigate to the app > res > layout > activity_home.xml and add the below code to it.XML \n Step 9: Enable Firebase Phone Authentication in our Firebase Console\nFor enabling Phone authentication in the Firebase console go to the Firebase Console. Now click on Go to Console option and navigate to your project. After that click on your project. You can get to see the below screen.After clicking on Authentication you will get to see the below screen. On this screen click on the Sign-in method tab.After clicking on Sign in-method you will get to see below list of authentication screens. Click on the Phone option and enable it.Click on the Phone option and you will get to see the below pop-up screen. Inside this screen click on the enable option and save it.Note: For getting OTP don\u2019t enter your phone number with country code because we are already adding that country code in our code itself.Output:https://media.geeksforgeeks.org/wp-content/uploads/20201226174523/Screenrecorder-2020-12-26-17-41-59-768.mp4\nSource: Click here to download the project files."}, {"text": "\nChronometer in Kotlin\n\nAndroid ChronoMeter is user interface control which shows timer in the view. We can easily start up or down counter with base time using the chronometer widget. By default, start() method can assume base time and starts the counter.Generally, we can create use ChronoMeter widget in XML layout but we can do it programmatically also.\nFirst we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Different attributes for ChronoMeter widgetXML attributes\nDescriptionandroid:id\nUsed to specify the id of the view.android:textAlignment\nUsed to the text alignment in the dropdown list.android:background\nUsed to set the background of the view.android:padding\nUsed to set the padding of the view.android:visibility\nUsed to set the visibility of the view.android:gravity\nUsed to specify the gravity of the view like center, top, bottom, etcandroid:format\nUsed to define the format of the string to be displayed.android:countDown\nUsed to define whether the chronometer will count up or count down.Modify activity_main.xml file\nIn this file, we use the ChronoMeter widget along with a button to start or stop the meter and also set attributes for both of them.XML \n Update strings.xml file\nHere, we update the name of the application using the string tag. We also other strings which can be used in MainActivity.kt file.XML \nChronometerInKotlin \nStop Timer \nStart Timer \nStarted \nStopped \n Access ChronoMeter in MainActivity.kt file\nFirst, we declare a variable meter to access the Chronometer from the XML layout file.\nval meter = findViewById(R.id.c_meter)\nthen, we access the button from the xml file and set setOnClickListener to start and stop the timer.\nval btn = findViewById(R.id.btn)\n btn?.setOnClickListener(object : View.OnClickListener {...}Kotlin package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle \nimport android.widget.Button \nimport android.view.View \nimport android.widget.Chronometer \nimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // access the chronometer from XML file \nval meter = findViewById(R.id.c_meter) //access the button using id \nval btn = findViewById(R.id.btn) \nbtn?.setOnClickListener(object : View.OnClickListener { var isWorking = falseoverride fun onClick(v: View) { \nif (!isWorking) { \nmeter.start() \nisWorking = true\n} else { \nmeter.stop() \nisWorking = false\n} btn.setText(if (isWorking) R.string.start else R.string.stop) Toast.makeText(this@MainActivity, getString( \nif (isWorking) \nR.string.working \nelse\nR.string.stopped), \nToast.LENGTH_SHORT).show() \n} \n}) \n} \n} AndroidManifest.xml fileXML \n \n \n \n \n \n \n Run as Emulator:"}, {"text": "\nHow to Improve RecyclerView Scrolling Performance in Android?\n\nRecyclerView is the main UI component in Android which is used to represent the huge list of data. If the RecyclerView is not implemented properly then it will not smoothly scrollable and it may lead to a bad user experience. To make it scrollable smoothly we have to optimize it and follow some tips to improve its performance. In this article, we will see the steps to follow for optimizing the Scrolling performance of our RecyclerView. Note:\nIf you are looking for the implementation guide of RecyclerView. Then do check out: How to implement RecyclerView in Android1. Set a specific width and height to ImageView in RecyclerView items\nIn RecyclerView if you\u2019re using ImageView to display an image from your server in your RecyclerView items then specify the constant size for your ImageView. If the size of ImageView in RecyclerView items is not fixed then RecyclerView will take some time to load and adjust the RecyclerView item size according to the size of Image. So to improve the performance of our RecyclerView we should keep the size of our ImageView to make it RecyclerView load faster.2. Avoid using NestedView\nWhile creating an item for RecyclerView avoid using NestedView for RecyclerView item. Nesting will reduce the performance of RecyclerView. So it is better to avoid using Nested View. Nested View means adding a Horizontal RecyclerView in a Vertical RecyclerView. This type of Nesting may reduce RecyclerView performance. Below is the image of Nested RecyclerView.3. Use the setHasFixedsize method\nIf the height of our RecyclerView items is fixed then we should use the setHasFixedsize method in our XML of our card item. This will fix the height of our RecyclerView item and prevent it from increasing or decreasing the size of our Card Layout. We can use this method in our JAVA class as well where we are declaring our RecyclerView adapter and layout manager.recyclerView.setHasFixedSize(true)4. Use the image loading library for loading images\nRecyclerView is composed of so many images and if you are loading an image in all cards then loading each image from the server will take so much time. As the Garbage Collection runs on the main thread so this is the reason which results in unresponsive UI. Continuous allocation and deallocation of memory lead to the frequent GC run. This can be prevented by using the bitmap pool concept. The simple solution to tackle this problem is to use Image Loading libraries such as Picasso, Glide, Fresco, and many more. These libraries will handle all bitmap pool concept and all delegate tasks related to images.Note: You may also refer to the Top 5 Image Loading Libraries in Android5. Do less work in the OnBindViewHolder method\nOnBindViewHolder method is used to set data in each item of RecyclerView. This method will set the data in each RecyclerView item. We should do less work in this method. We only have to set data in this method and not to do any comparison or any heavy task. If we perform any heavy task in this method then this will degrade the performance of our RecyclerView because setting data for each item will take a specific amount of time. So to improve the performance of RecyclerView we should do less work in the OnBindViewHolder method.\n6. Use the NotifyItem method for your RecyclerView\nWhenever you are performing actions in RecyclerView such as adding an item in RecyclerView at any position or deleting an item from a specific position of RecyclerView then you should use NotifyItemChange() method.Java // below method will notify the adapter \n// of our RecyclerView when an item \n// from RecyclerView is removed. \nadapter.notifyItemRemoved(position) // below method will be used when \n// we update the data of any RecyclerView \n// item at a fixed position. \nadapter.notifyItemChanged(position) // below method is used when we add \n// any item at a specific position \n// of our RecyclerView. \nadapter.notifyItemInserted(position) // below method is used when we add multiple \n// number of items in our recyclerview. \n// start represents the position from \n// which the items are added. \n// end represents the position upto \n// which we have to add items. \nadapter.notifyItemRangeInserted(start, end)When we will call the notifyDataSetChanged() method it will not handle the complete reordering of the RecyclerView adapter but it will find if the item at that position is the same as before to do less work."}, {"text": "\nAndroid | How to add Radio Buttons in an Android Application?\n\nAndroid radio button is a widget that can have more than one option to choose from. The user can choose only one option at a time. Each option here refers to a radio button and all the options for the topic are together referred to as Radio Group. Hence, Radio Buttons are used inside a RadioGroup.\nPre-requisites:Android App Development Fundamentals for Beginners\nGuide to Install and Set up Android Studio\nAndroid | Starting with the first app/android project\nAndroid | Running your first Android appFor Example:This image shows 4 options of the subjects for a question. In this, each mentioned subject is a Radio Button and all the 4 subjects together are enclosed in a Radio Group.\nHow to create an Android App to use Radio Buttons?\nThis example will help in developing an Android App that creates Radio Buttons according to the above example:\nStep 1: First create a new Android Application. This will create an XML file \u201cactivity_main.xml\u201d and a Java File \u201cMainActivity.Java\u201d. Please refer the pre-requisites to learn more about this step.Step 2: Open the \u201cactivity_main.xml\u201d file and add the following widgets in a Relative Layout:A TextView to display the question message\nA RadioGroup to hold the option Radio Buttons which are the possible answers\n4 RadioButtons to hold an answer each.\nA Submit and a Clear button to store the response.Also, Assign the ID to each of the components along with other attributes as shown in the given image and the code below. The assigned ID on a component helps that component to be easily found and used in the Java files.\nSyntax:\nandroid:id=\"@+id/id_name\"\nHere the given IDs are as follows:RadioGroup: groupradio\nRadioButton1: radia_id1\nRadioButton2: radia_id2\nRadioButton3: radia_id3\nRadioButton4: radia_id4\nSubmit Button: submit\nClear Button: clearThis will make the UI of the Application.Step 3: Now, after the UI, this step will create the Backend of Application. For this, open the \u201cMainActivity.java\u201d file and instantiate the components made in the XML file (RadioGroup, TextView, Clear, and Submit Button) using findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.\nSyntax: General\nComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);\nSyntax: Components used\nButton submit = (Button)findViewById(R.id.submit);\nButton clear = (Button)findViewById(R.id.clear);\nRadioGroup radioGroup = (RadioGroup)findViewById(R.id.groupradio);\nStep 4: This step involves setting up the operations on the RadioGroup, RadioButtons, and the Submit and Clear Buttons.\nThese operations are as follows:Unset all the Radio Buttons initially as the default value. This is done by the following command:radioGroup.clearCheck();Add the Listener on the RadioGroup. This will help to know whenever the user clicks on any Radio Button, and the further operation will be performed. The listener can be added as follows:radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){}Define the operations to be done when a radio button is clicked. This involves getting the specific radio button that has been clicked, using its id. Then this radio button gets set and the rest of the radio button is reset.\nAdd the listener on Submit button and clear button. This will be used to check when the user clicks on the button. This is done as follows:submit.setOnClickListener(new View.OnClickListener() {}clear.setOnClickListener(new View.OnClickListener() {}In the Submit Button Listener, set the operations to be performed. This involves displaying the marked answer in the form of Toast.\nIn the Clear Button Listener, set the operations to be performed. This involves resetting all the radio buttons.Step5: Now run the app and operate as follows:When the app is opened, it displays a question with 4 answers and a clear and submit button.\nWhen any answer is clicked, that radio button gets set.\nClicking on any other radio button sets that one and resets the others.\nClicking on Submit button displays the currently marked answer as a Toast.\nClicking on Clear button resets all the radio buttons to their default state.The complete code of MainActivity.java and activity_main.xml of RadioButton is below as follows:\nFilename: activity_main.xmlXML \n \n\n\n \n \n \n Filename: MainActivity.JavaJava package org.geeksforgeeks.navedmalik.radiobuttons;import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.RadioButton;\nimport android.widget.RadioGroup;\nimport android.widget.Toast;public class MainActivity extends AppCompatActivity {// Define the object for Radio Group,\n// Submit and Clear buttons\nprivate RadioGroup radioGroup;\nButton submit, clear;@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// Bind the components to their respective objects\n// by assigning their IDs\n// with the help of findViewById() method\nsubmit = (Button)findViewById(R.id.submit);\nclear = (Button)findViewById(R.id.clear);\nradioGroup = (RadioGroup)findViewById(R.id.groupradio);// Uncheck or reset the radio buttons initially\nradioGroup.clearCheck();// Add the Listener to the RadioGroup\nradioGroup.setOnCheckedChangeListener(\nnew RadioGroup\n.OnCheckedChangeListener() {\n@Override// The flow will come here when\n// any of the radio buttons in the radioGroup\n// has been clicked// Check which radio button has been clicked\npublic void onCheckedChanged(RadioGroup group,\nint checkedId)\n{// Get the selected Radio Button\nRadioButton\nradioButton\n= (RadioButton)group\n.findViewById(checkedId);\n}\n});// Add the Listener to the Submit Button\nsubmit.setOnClickListener(new View.OnClickListener() {@Override\npublic void onClick(View v)\n{// When submit button is clicked,\n// Ge the Radio Button which is set\n// If no Radio Button is set, -1 will be returned\nint selectedId = radioGroup.getCheckedRadioButtonId();\nif (selectedId == -1) {\nToast.makeText(MainActivity.this,\n\"No answer has been selected\",\nToast.LENGTH_SHORT)\n.show();\n}\nelse {RadioButton radioButton\n= (RadioButton)radioGroup\n.findViewById(selectedId);// Now display the value of selected item\n// by the Toast message\nToast.makeText(MainActivity.this,\nradioButton.getText(),\nToast.LENGTH_SHORT)\n.show();\n}\n}\n});// Add the Listener to the Submit Button\nclear.setOnClickListener(new View.OnClickListener() {@Override\npublic void onClick(View v)\n{// Clear RadioGroup\n// i.e. reset all the Radio Buttons\nradioGroup.clearCheck();\n}\n});\n}\n}Output"}, {"text": "\nHow to Open Camera Through Intent and Display Captured Image in Android?\n\nPre-requisites:Android App Development Fundamentals for Beginners\nGuide to Install and Set up Android Studio\nAndroid | Starting with first app/android project\nAndroid | Running your first Android appThe purpose of this article is to show how to open a Camera from inside an App and click the image and then display this image inside the same app. An android application has been developed in this article to achieve this. The opening of the Camera from inside our app is achieved with the help of the ACTION_IMAGE_CAPTURE Intent of MediaStore class.\nThis image shows the Image clicked by the camera and set in Imageview. When the app is opened, it displays the \u201cCamera\u201d Button to open the camera. When pressed, ACTION_IMAGE_CAPTURE Intent gets started by the MediaStore class. When the image is captured, it is displayed in the image view.\nStep-by-Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android. This will create an XML file \u201cactivity_main.xml\u201d and a Java/Kotlin File \u201cMainActivity\u201d. Please refer to the prerequisites to learn more about this step.Step 2: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.A Button to open the Camera\nAn ImageView to display the captured imageAlso, Assign the ID to each component along with other attributes as shown in the image and the code below.\nSyntax:\nandroid:id=\"@+id/id_name\"\nHere the given IDs are as follows:Camera Button: camera_button\nImageView: click_imageThis step will make the UI of the Application.XML \n \n \n \n Step 3: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. We will instantiate the components made in the XML file (Camera Button, ImageView) using the findViewById() method. This method binds the created object to the UI Components with the help of the assigned ID.\nGeneral Syntax:\nComponentType object = (ComponentType)findViewById(R.id.IdOfTheComponent);\nThe Syntax for Components Used:\nButton camera_open_id= findViewById(R.id.camera_button);\nImageView click_image_id = findViewById(R.id.click_image);\nSetting up Operations on the Camera Button and ImageView.\nFirst, define the variable pic_id which is the request-id of the clicked image.\nThis is done as follows:\nprivate static final int pic_id = 123\nAdd the listener to the Camera button. This will be used to open the camera when the user clicks on the button.\nThis is done as follows:\ncamera_open_id.setOnClickListener(new View.OnClickListener() {}\nNow create the ACTION_IMAGE_CAPTURE Intent provided by MediaStore. This Intent will help to open the camera for capturing the image. Start the intent with the requested pic_id.\nThis is done as follows:\nIntent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);\nstartActivityForResult(camera_intent, pic_id);\nNow use the onActivityResult() method to get the result, here is the captured image.\nThis is done as follows:\nprotected void onActivityResult(int requestCode, int resultCode, Intent data) { }\n \nThen set the image received as a result of Camera intent in the ImageView for display.\nBitmap photo = (Bitmap) data.getExtras().get(\"data\");\nclicked_image_id.setImageBitmap(photo);Java import android.content.Intent; \nimport android.graphics.Bitmap; \nimport android.os.Bundle; \nimport android.provider.MediaStore; \nimport android.widget.Button; \nimport android.widget.ImageView; \nimport androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { // Define the pic id \nprivate static final int pic_id = 123; \n// Define the button and imageview type variable \nButton camera_open_id; \nImageView click_image_id; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // By ID we can get each component which id is assigned in XML file get Buttons and imageview. \ncamera_open_id = findViewById(R.id.camera_button); \nclick_image_id = findViewById(R.id.click_image); // Camera_open button is for open the camera and add the setOnClickListener in this button \ncamera_open_id.setOnClickListener(v -> { \n// Create the camera_intent ACTION_IMAGE_CAPTURE it will open the camera for capture the image \nIntent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); \n// Start the activity with camera_intent, and request pic id \nstartActivityForResult(camera_intent, pic_id); \n}); \n} // This method will help to retrieve the image \nprotected void onActivityResult(int requestCode, int resultCode, Intent data) { \nsuper.onActivityResult(requestCode, resultCode, data); \n// Match the request 'pic id with requestCode \nif (requestCode == pic_id) { \n// BitMap is data structure of image file which store the image in memory \nBitmap photo = (Bitmap) data.getExtras().get(\"data\"); \n// Set the image in imageview for display \nclick_image_id.setImageBitmap(photo); \n} \n} \n}Kotlin import android.content.Intent \nimport android.graphics.Bitmap \nimport android.os.Bundle \nimport android.provider.MediaStore \nimport android.view.View \nimport android.widget.Button \nimport android.widget.ImageView \nimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { \n// Define the button and imageview type variable \nprivate lateinit var cameraOpenId: Button \nlateinit var clickImageId: ImageView \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) // By ID we can get each component which id is assigned in XML file get Buttons and imageview. \ncameraOpenId = findViewById(R.id.camera_button) \nclickImageId = findViewById(R.id.click_image) // Camera_open button is for open the camera and add the setOnClickListener in this button \ncameraOpenId.setOnClickListener(View.OnClickListener { v: View? -> \n// Create the camera_intent ACTION_IMAGE_CAPTURE it will open the camera for capture the image \nval cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) \n// Start the activity with camera_intent, and request pic id \nstartActivityForResult(cameraIntent, pic_id) \n}) \n} // This method will help to retrieve the image \noverride fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { \nsuper.onActivityResult(requestCode, resultCode, data) \n// Match the request 'pic id with requestCode \nif (requestCode == pic_id) { \n// BitMap is data structure of image file which store the image in memory \nval photo = data!!.extras!![\"data\"] as Bitmap? \n// Set the image in imageview for display \nclickImageId.setImageBitmap(photo) \n} \n} companion object { \n// Define the pic id \nprivate const val pic_id = 123\n} \n}Output:"}, {"text": "\nOverview of Facebook Audience Network\n\nIn order to earn money from the Android or iOS app or game, there are many ways such as in-App Purchases, Sponsorship, Advertisements, and many more. But there is another popular method to earn money from the Android or iOS app is by integrating a third party advertisement e.g known as Facebook Audience Network (FAN). Facebook Audience Network is designed to help monetize with the user experience in mind. By using high-value formats, quality ads, and innovative publisher tools it helps to grow the business while keeping people engaged.\nWhy Facebook Audience Network?Facebook Audience Network is one of the best alternatives for Google Admob to monetize the Android or IOS App.\nMinimum Payout is $100\nWide Range of Ad Formats\nMaximum Fill Rates\nHigh eCPM(Effective Cost Per Mille)\nQuality Ads\nPersonalized AdsHow FAN Helps to Grow the App Business?People-Based Monetization: FAN matches ads with people\u2019s interests so they\u2019re less rude and more likely to keep the audience engaged. It\u2019s high-value, flexible formats are designed to enable a better ad experience and higher returns for the users.\nQuality Controls to Protect the Brand: Protect the app with brand-safe ads. FAN provides pre and post-campaign clarity, blocklists, keyword blocking, severity level controls, and more to help the users ensure a high-quality ad experience.\nMore Revenue Through Bidding: Bidding renders equal and open disposal where the user can offer every ad opportunity to multiple demand sources at the same time. This enhances competition for the inventory and creates a larger yield all in an ecosystem with greater transparency.Formats of Facebook Audience Network\nThere are mainly five types of flexible, high-performing format available in Facebook Audience NetworkBanner: Traditional formats in a variety of placements.\nInterstitial: Full-screen ads that capture attention and become part of the experience.\nRewarded Video: An immersive, user-initiated video ad that rewards users for watching.\nNative: Ads that you design to fit the app, seamlessly\nPlayables: A try-before-you-buy ad experience permitting users to preview a game before installing.1. Banner Ads: Banner ads are the most common type of ad unit and can be placed throughout the app. A Banner ad is a rectangular image or text ad which occupies a small space in the app layout. A Banner ad is easy to implement and it doesn\u2019t affect the user interface and increases the revenue gradually. Below is a sample gif to demonstrate how the Banner ad looks like.Note: To integrate FAN Banner Ads in Android please refer to How to Integrate Facebook Audience Network (FAN) Banner Ads in Android?2. Interstitial Ads: Interstitial ad is a full-screen ad that covers the whole UI of the app. The eCPM (Effective Cost Per Mille) of Interstitial ads are relatively higher than banner ads and also leads to higher CTR(Click Through Rate) which results in more earning from the app. Below is a sample gif to demonstrate how the Interstitial ad looks like.Note: To integrate FAN Interstitial Ads in Android please refer to How to Integrate Facebook Audience Network (FAN) Interstitial Ads in Android?3. Rewarded Video Ads: A rewarded video ad is a full-screen ad that covers the whole UI of the app. The eCPM (Effective Cost Per Mille) of Rewarded Video ads are relatively higher than banner and Interstitial ads and also leads to higher CTR(Click Through Rate) which results in more earning from the app. The user gets an in-App reward when they watch the Rewarded Video from start to end. Below is a sample video to demonstrate how the Rewarded video ad looks like.Note: To integrate FAN Rewarded Video Ads in Android please refer to How to Integrate Facebook Audience Network (FAN) Rewarded Video Ads in Android?4. Native Ads: Native Ads is customizable formats that fit the look and feel of your app design. A native ad is a custom-designed unit that fits seamlessly with the app. If done well, ads can blend in naturally with the interface. The unique feature of native ads is that they should balance the app\u2019s experience while protecting the integrity of advertisers\u2019 assets and creating a great user experience. Below is a sample image to demonstrate how the Native ad looks like.5. Playable Ads: The playable ad format is an interactive video ad for Facebook and Audience Network for mobile app advertisers to drive immense quality and higher-intent users to install their apps with a try-before-you-buy experience. Below is a sample image to demonstrate how the Playable ad looks like."}, {"text": "\nHow to Save Data to the Firebase Realtime Database in Android?\n\nFirebase is one of the famous backend platforms which is used by so many developers to provide backend support to their applications and websites. It is the product of Google which provides services such as database, storage, user authentication, and many more. In this article, we will create a simple app in which we will be adding our Data to Firebase Realtime Database. Note that we are going toimplement this project using theJavalanguage.\nWhat is Firebase Realtime Database?\nFirebase Realtime Database is a NoSQL cloud database that is used to store and sync the data. The data from the database can be synced at a time across all the clients such as android, web as well as IOS. The data in the database is stored in the JSON format and it updates in real-time with every connected client. \nWhat are the Advantages of using the Firebase Realtime Database?The main advantage of using the Firebase Realtime database is that the data is updated in a real-time manner and you don\u2019t have to make any requests for the data updates or changes. The database uses data synchronization every time when data changes and these changes will reflect the connected user within milliseconds.\nWhile using Firebase Realtime Database your apps remain responsive even if the device loses its connectivity to the database. Once the user has established the connection he will receive the changes made in the data from the database.\nThe data stored in the Firebase database can be easily accessible through the web portal of Firebase. You can manage your database from PC as well as mobile devices. You can manage the rules of the database which gives permissions to read and write operations to the database.What We are Going to Build in This Article?\nIn this article, we are going to build a simple application in which we will be getting the data from the users with the help of some TextFields and store that data in the Firebase Realtime Database. Note that we are using Firebase Realtime Database and the app is written using JAVA language.\nStep by Step Implementation\nStep 1: Create a New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Connect your app to Firebase\nAfter creating a new project navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Realtime Database. Click on that option and you will get to see two options on Connect app to Firebase and Add Firebase Realtime Database to your app. Click on Connect now and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase.After connecting your app to Firebase you will get to see the below screen.After that verify that dependency for Firebase Realtime database has been added to our Gradle file. Now navigate to the app > Gradle Scripts and inside that file check whether the below dependency is added or not. If the below dependency is not added in your build.gradle file. Add the below dependency in the dependencies section.implementation \u2018com.google.firebase:firebase-database:19.6.0\u2019After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about Adding Firebase to Android App.\nStep 3: Working with AndroidManifest.xml file\nFor adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml and inside that file add the below permissions to it.XML \nStep 4: Working with the activity_main.xml file\nGo to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.XML \n\n \n \n \n Step 5: Create a new Java class for storing our data\nFor sending multiple data to the Firebase Realtime database we have to create an Object class and send that whole object class to Firebase. For creating an object class navigate to the app > java > your app\u2019s package name > Right-click on it and Click on New > Java Class > Give a name to your class. In my case, it is EmployeeInfo, and add below code to it.Java public class EmployeeInfo {// string variable for \n// storing employee name.\nprivate String employeeName;// string variable for storing\n// employee contact number\nprivate String employeeContactNumber;// string variable for storing\n// employee address.\nprivate String employeeAddress;// an empty constructor is \n// required when using\n// Firebase Realtime Database.\npublic EmployeeInfo() {}// created getter and setter methods\n// for all our variables.\npublic String getEmployeeName() {\nreturn employeeName;\n}public void setEmployeeName(String employeeName) {\nthis.employeeName = employeeName;\n}public String getEmployeeContactNumber() {\nreturn employeeContactNumber;\n}public void setEmployeeContactNumber(String employeeContactNumber) {\nthis.employeeContactNumber = employeeContactNumber;\n}public String getEmployeeAddress() {\nreturn employeeAddress;\n}public void setEmployeeAddress(String employeeAddress) {\nthis.employeeAddress = employeeAddress;\n}\n}Step 6: Working with the MainActivity.java file\nGo to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.firebase.database.DataSnapshot;\nimport com.google.firebase.database.DatabaseError;\nimport com.google.firebase.database.DatabaseReference;\nimport com.google.firebase.database.FirebaseDatabase;\nimport com.google.firebase.database.ValueEventListener;public class MainActivity extends AppCompatActivity {// creating variables for \n// EditText and buttons.\nprivate EditText employeeNameEdt, employeePhoneEdt, employeeAddressEdt;\nprivate Button sendDatabtn;// creating a variable for our\n// Firebase Database.\nFirebaseDatabase firebaseDatabase;// creating a variable for our Database \n// Reference for Firebase.\nDatabaseReference databaseReference;// creating a variable for \n// our object class\nEmployeeInfo employeeInfo;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// initializing our edittext and button\nemployeeNameEdt = findViewById(R.id.idEdtEmployeeName);\nemployeePhoneEdt = findViewById(R.id.idEdtEmployeePhoneNumber);\nemployeeAddressEdt = findViewById(R.id.idEdtEmployeeAddress);// below line is used to get the \n// instance of our FIrebase database.\nfirebaseDatabase = FirebaseDatabase.getInstance();// below line is used to get reference for our database.\ndatabaseReference = firebaseDatabase.getReference(\"EmployeeInfo\");// initializing our object \n// class variable.\nemployeeInfo = new EmployeeInfo();sendDatabtn = findViewById(R.id.idBtnSendData);// adding on click listener for our button.\nsendDatabtn.setOnClickListener(new View.OnClickListener() {\n@Override\npublic void onClick(View v) {// getting text from our edittext fields.\nString name = employeeNameEdt.getText().toString();\nString phone = employeePhoneEdt.getText().toString();\nString address = employeeAddressEdt.getText().toString();// below line is for checking whether the \n// edittext fields are empty or not.\nif (TextUtils.isEmpty(name) && TextUtils.isEmpty(phone) && TextUtils.isEmpty(address)) {\n// if the text fields are empty \n// then show the below message.\nToast.makeText(MainActivity.this, \"Please add some data.\", Toast.LENGTH_SHORT).show();\n} else {\n// else call the method to add \n// data to our database.\naddDatatoFirebase(name, phone, address);\n}\n}\n});\n}private void addDatatoFirebase(String name, String phone, String address) {\n// below 3 lines of code is used to set\n// data in our object class.\nemployeeInfo.setEmployeeName(name);\nemployeeInfo.setEmployeeContactNumber(phone);\nemployeeInfo.setEmployeeAddress(address);// we are use add value event listener method\n// which is called with database reference.\ndatabaseReference.addValueEventListener(new ValueEventListener() {\n@Override\npublic void onDataChange(@NonNull DataSnapshot snapshot) {\n// inside the method of on Data change we are setting \n// our object class to our database reference.\n// data base reference will sends data to firebase.\ndatabaseReference.setValue(employeeInfo);// after adding this data we are showing toast message.\nToast.makeText(MainActivity.this, \"data added\", Toast.LENGTH_SHORT).show();\n}@Override\npublic void onCancelled(@NonNull DatabaseError error) {\n// if the data is not added or it is cancelled then\n// we are displaying a failure toast message.\nToast.makeText(MainActivity.this, \"Fail to add data \" + error, Toast.LENGTH_SHORT).show();\n}\n});\n}\n}After adding this code go to this link for Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner.After clicking on this screen you will get to see the below screen with your all project inside that select your project.Inside that screen click n Realtime Database in the left window.After clicking on this option you will get to see the screen on the right side. On this page click on the Rules option which is present in the top bar. You will get to see the below screen.Inside this screen click on the Rules tab you will get to see the above screen and change the rules to true as shown in the screenshot. The rules are changed to true because we are not providing authentication inside our app and we have to write data to our database. That\u2019s why we are specifying it to true. After changing your rules click on the publish rules button. Click on that option and your rules will be published. Now come back to the Data tab of your database.\nOutput:\nBelow is the video for our app for adding data to the Firebase Realtime Database.https://media.geeksforgeeks.org/wp-content/uploads/20201225155952/Screenrecorder-2020-12-25-15-48-46-492.mp4\nRun the app and make sure to connect your device to the internet. After that add some data in your text fields and click on the Insert data button. The data will be added to our Firebase Database. Below is the screenshot we will get to see after adding data to Firebase Database from the app."}, {"text": "\nDownload and Install Java Development Kit (JDK) on Windows, Mac, and Linux\n\nSetting up a Suitable Development Environment is necessary before one can begin creating Android Applications. It makes it easier for developers to use the tools required to create any Application and ensures that all Operations or Processes run smoothly. Download and Install JDK in order to create Android Application Source Files using the Java or Kotlin Programming Language. The system will execute the code using a set of Libraries and Compilers. JDK, JRE, and JVM should not be confused with one another, for more Differences between JDK, JRE, and JVM. This article describes the step-by-step process for installing and configuring the JDK on the 3 most popular Computer Operating Systems in order to begin the process of developing Android Applications.\nJava JDK Download\nThe JDK can be installed on the following Platforms:Microsoft Windows\nLinux\nmacOSInstall JDK on Microsoft Windows\nStep 1: Download and Install Java Development Kit (JDK)\nThe very first step is to download the Oracle Java Development Kit (JDK) from the Official Oracle Website. For that, Head over to the Official Website.You need to identify your system specifications to choose the Product/file description. The website will contain the latest version for your corresponding system. For Windows, we\u2019ll be downloading the latest x64 Installer of Java SE Development Kit 18. After the download is complete, proceed to install the JDK by following the bootstrapped steps.Step 2: Configure Environment Variables\nAfter the installation is complete, we have to configure environment variables to notify the system about the directory in which JDK files are located. Proceed to C:\\Program Files\\Java\\jdk-{YOUR_JDK_VERSION}\\bin (replace {-} with your JDK version)To set the Environment Variables, you need to search Environment Variables in the Task Bar and click on \u201cEdit the system environment variables\u201d.Under the Advanced section, Click on \u201cEnvironment Variables\u201d.Under System variables, select the \u201cPath\u201d variable and click on \u201cEdit\u201d. Click on \u201cNew\u201d then paste the Path Address i.e. C:\\Program Files\\Java\\jdk-{YOUR_JDK_VERSION}\\bin. Click on \u201cOK\u201d.Now, in the Environment Variables dialogue, under System variables, click on \u201cNew\u201d and then under Variable name: JAVA_HOME and Variable value: paste address i.e. C:\\Program Files\\Java\\jdk-{YOUR_JDK_VERSION}. Click on OK => OK => OK.Step 3: Check the Java Version\nOpen Command Prompt and enter the following commands\njava -version\njavac -versionInstall JDK on Linux\nStep 1: Download and Install Oracle Java Development Kit (JDK)\nThe very first step is to download the Oracle Java Development Kit (JDK) from the Official Oracle Website. For that, Head over to the Official Website.You need to identify your system specifications to choose the Product/file description. The website will contain the latest version for your corresponding system. For Linux, we\u2019ll be downloading the latest x64 Debian Package of Java SE Development Kit 18. To install the downloaded JDK File using terminal, Open terminal and change your directory to downloads by using the command\n$ cd downloads\nTo list files and packages present in the directory, Type\n$ lsNow we use Debian Package Manager to configure our downloaded file for installation by typing\n$ sudo dpkg -i jdk-{YOUR_JDK_VERSION} (replace {-} with your version)\nEnter your password as we have run an elevated prompt, i.e. the sudo or superuser do command, which is a quick way to grant specific users permission to perform specific system commands at the system\u2019s root (most powerful) level.Now, Type the following commands to proceed with the installation\n$ sudo update-alternatives --install /usr/bin/java java /usr/lib/jvm/jdk-{YOUR_JDK_VERSION}/bin/java 1\n$ sudo update-alternatives --install /usr/bin/javac javac /usr/lib/jvm/jdk-{YOUR_JDK_VERSION}/bin/javac 1\nStep 2: Check the Java Version\nOpen the terminal and enter the following commands\n$ java --version\n$ javac --versionStep 3: Configure JAVA_HOME Environment Variable\nAfter the installation is complete, we have to configure environment variables to notify the system about the directory in which jdk files are located. To find the Location of the JDK Files, run this command\n$ sudo update-alternatives --config java\nand copy the File Location.\nIn order to set the environment variable, you have to edit the environment file using this command\n$ sudo gedit /etc/environment\nProceed to add JAVA_HOME=\u201d /usr/lib/jvm/jdk-{YOUR_JDK_VERSION}\u201d\nProceed to save and close the file.Now we have to refresh the environment file by using this command\n$ SOURCE /etc/environment\nAnd echo the JAVA_HOME Path\n$ echo $JAVA_HOME\nInstall JDK on MacOS\nStep 1: Download and Install Oracle Java Development Kit (JDK)\nThe very first step is to download the Oracle Java Development Kit (JDK) from the Official Oracle Website. For that, Head over to the Official Website.You need to identify your system specifications to choose the Product/file description. The website will contain the latest version for your corresponding system. For Mac, we\u2019ll be downloading the latest x64 DMG Installer of Java SE Development Kit 18. After the download is complete, proceed to install the JDK by following the bootstrapped steps.Step 2: Configure environment variables\nNow to configure, we have to open the terminal and pass the following commands. To find the Location of the JAVA_HOME, run this command\n$ /usr/libexec/java_home -v{YOUR_VERSION}We have to set this output as our JAVA_HOME Environment Variable. You can use any command or code editor to edit the file, here we are using VS Code\n$ code ~/. bash_profileAt the very bottom, we have to export the path we obtained earlier i.e.\n$ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-{YOUR_VERSION}.jdk/Contents/HomeNow we have to refresh the environment file by using this command\n$ source ~/.bash_profile\nAnd echo the JAVA_HOME variable\n$ echo $JAVA_HOMEStep 3: Check the Java Version\nIn the terminal, enter the following commands\n$ java -version\n$ javac -version"}, {"text": "\nHow to pre populate database in Android using SQLite Database\n\nIntroduction :\nOften, there is a need to initiate an Android app with an already existing database. This is called prepopulating a database. In this article, we will see how to pre-populate database in Android using SQLite Database. The database used in this example can be downloaded as Demo Database.\nTo prepopulate a SQLite database in an Android application, you can follow these steps:Create a new SQLite database in your Android application.\nCreate a SQL script that contains the data you want to prepopulate your database with. This script should contain the SQL commands to create tables, insert data, and perform other database operations.\nStore the SQL script in the assets folder of your Android application.\nIn the onCreate() method of your SQLiteOpenHelper subclass, open the database and execute the SQL script to populate the database with data.Here is an example code snippet that demonstrates how to prepopulate a SQLite database in an Android application :Java import android.content.Context;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteOpenHelper;public class MyDatabaseHelper extends SQLiteOpenHelper {private final Context context;\nprivate static final String DATABASE_NAME = \"myDatabase.db\";\nprivate static final int DATABASE_VERSION = 1;public MyDatabaseHelper(Context context) {\nsuper(context, DATABASE_NAME, null, DATABASE_VERSION);\nthis.context = context;\n}@Override\npublic void onCreate(SQLiteDatabase db) {\nString createTableQuery = \"CREATE TABLE myTable (id INTEGER PRIMARY KEY, name TEXT)\";\ndb.execSQL(createTableQuery);\n}@Override\npublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\ndb.execSQL(\"DROP TABLE IF EXISTS myTable\");\nonCreate(db);\n}@Override\npublic void onOpen(SQLiteDatabase db) {\nsuper.onOpen(db);\n}public void insertData(int id, String name) {\nSQLiteDatabase db = getWritableDatabase();\nString insertDataQuery = \"INSERT INTO myTable VALUES (\" + id + \", '\" + name + \"')\";\ndb.execSQL(insertDataQuery);\ndb.close();\n}\n}Approach:Add the support Library in build.gradle file and add Recycler View dependency in the dependencies section.XML dependencies{\nimplementation 'androidx.recyclerview:recyclerview:1.1.0'\n}Make sure you add the database in assets folder. To create assets folder right click on app directory->new->Folder->(select)Assets Folder. Then simply paste your .db file in assets folder.\nIn activity_main.xml, add the following code.XML \n Create a new custom_layout.xml file with the following code.XML \n\n \n Create a DatabaseHelper class and add the following code.Java package org.geeksforgeeks.dictionary;import android.app.Activity;\nimport android.content.Context;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport android.util.Log;import java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.io.OutputStream;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;public class DatabaseHelper\nextends SQLiteOpenHelper {// The Android's default system path\n// of your application database.\nprivate static String DB_PATH = \"\";\nprivate static String DB_NAME = \"database.db\";\nprivate SQLiteDatabase myDataBase;\nprivate final Context myContext;\nprivate SQLiteOpenHelper sqLiteOpenHelper;// Table name in the database.\npublic static final String\nALGO_TOPICS\n= \"algo_topics\";/**\n* Constructor\n* Takes and keeps a reference of \n* the passed context in order \n* to access the application assets and resources. */\npublic DatabaseHelper(Context context)\n{super(context, DB_NAME, null, 1);\nthis.myContext = context;\nDB_PATH = myContext.getDatabasePath(DB_NAME)\n.toString();\n}// Creates an empty database\n// on the system and rewrites it\n// with your own database.\npublic void createDataBase()\nthrows IOException\n{boolean dbExist = checkDataBase();if (dbExist) {\n// do nothing - database already exist\n}\nelse {\n// By calling this method and\n// the empty database will be\n// created into the default system\n// path of your application\n// so we are gonna be able\n// to overwrite that database\n// with our database.\nthis.getWritableDatabase();\ntry {\ncopyDataBase();\n}\ncatch (IOException e) {\nthrow new Error(\n\"Error copying database\");\n}\n}\n}\n// Check if the database already exist\n// to avoid re-copying the file each\n// time you open the application\n// return true if it exists\n// false if it doesn't.\nprivate boolean checkDataBase()\n{\nSQLiteDatabase checkDB = null;\ntry {\nString myPath = DB_PATH;\ncheckDB\n= SQLiteDatabase\n.openDatabase(\nmyPath, null,\nSQLiteDatabase.OPEN_READONLY);\n}\ncatch (SQLiteException e) {// database doesn't exist yet.\nLog.e(\"message\", \"\" + e);\n}\nif (checkDB != null) {\ncheckDB.close();\n}\nreturn checkDB != null;\n}/**\n* Copies your database from your\n* local assets-folder to the just \n* created empty database in the\n* system folder, from where it \n* can be accessed and handled.\n* This is done by transferring bytestream.\n* */\nprivate void copyDataBase()\nthrows IOException\n{\n// Open your local db as the input stream\nInputStream myInput\n= myContext.getAssets()\n.open(DB_NAME);// Path to the just created empty db\nString outFileName = DB_PATH;// Open the empty db as the output stream\nOutputStream myOutput\n= new FileOutputStream(outFileName);// transfer bytes from the\n// inputfile to the outputfile\nbyte[] buffer = new byte[1024];\nint length;\nwhile ((length = myInput.read(buffer)) > 0) {\nmyOutput.write(buffer, 0, length);\n}// Close the streams\nmyOutput.flush();\nmyOutput.close();\nmyInput.close();\n}public void openDataBase()\nthrows SQLException\n{\n// Open the database\nString myPath = DB_PATH;\nmyDataBase = SQLiteDatabase\n.openDatabase(\nmyPath, null,\nSQLiteDatabase.OPEN_READONLY);\n}@Override\npublic synchronized void close()\n{\n// close the database.\nif (myDataBase != null)\nmyDataBase.close();\nsuper.close();\n}@Override\npublic void onCreate(SQLiteDatabase db)\n{\n// It is an abstract method\n// but we define our own method here.\n}@Override\npublic void onUpgrade(SQLiteDatabase db,\nint oldVersion,\nint newVersion)\n{\n// It is an abstract method which is\n// used to perform different task\n// based on the version of database.\n}// This method is used to get the\n// algorithm topics from the database.\npublic List getAlgorithmTopics(\nActivity activity)\n{\nsqLiteOpenHelper\n= new DatabaseHelper(activity);\nSQLiteDatabase db\n= sqLiteOpenHelper\n.getWritableDatabase();List list\n= new ArrayList<>();// query help us to return all data\n// the present in the ALGO_TOPICS table.\nString query = \"SELECT * FROM \" + ALGO_TOPICS;\nCursor cursor = db.rawQuery(query, null);if (cursor.moveToFirst()) {\ndo {\nlist.add(cursor.getString(1));\n} while (cursor.moveToNext());\n}\nreturn list;\n}\n}Create a MyAdapter.java class and add the following code.Java package org.geeksforgeeks.dictionary;import android.app.Activity;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;import androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.List;public class MyAdapter\nextends RecyclerView.Adapter {private List data;\nActivity activity;public MyAdapter(Activity activity,\nList data)\n{\nthis.data = data;\nthis.activity = activity;\n}// This method is used to attach\n// custom layout to the recycler view\n@NonNull\n@Override\npublic ViewHolder onCreateViewHolder(\n@NonNull ViewGroup parent,\nint viewType)\n{\nLayoutInflater LI\n= activity.getLayoutInflater();\nView vw = LI.inflate(\nR.layout.custom_layout, null);\nreturn new ViewHolder(vw);\n}// This method is used to set the action\n// to the widgets of our custom layout.\n@Override\npublic void onBindViewHolder(\n@NonNull ViewHolder holder,\nint position)\n{\nholder.topic_name\n.setText(data.get(position));\n}@Override\npublic int getItemCount()\n{\nreturn data.size();\n}class ViewHolder\nextends RecyclerView.ViewHolder {\nTextView topic_name;\npublic ViewHolder(View itemView)\n{\nsuper(itemView);\nthis.topic_name\n= itemView.findViewById(R.id.textView);\n}\n}\n}Finally, in MainActivity.java add the following code.Java package org.geeksforgeeks.algorithmTopics;import androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.DefaultItemAnimator;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport android.os.Bundle;\nimport java.util.ArrayList;\nimport java.util.List;public class MainActivity\nextends AppCompatActivity {private static RecyclerView.Adapter adapter;\nprivate static RecyclerView recyclerView;\npublic static List data;\nDatabaseHelper db;@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);\nrecyclerView\n= findViewById(R.id.my_recycler_view);db = new DatabaseHelper(this);\nrecyclerView.setLayoutManager(\nnew LinearLayoutManager(this));\ndata = new ArrayList<>();\nfetchData();\n}public void fetchData()\n{\n// Before fetching the data\n// directly from the database.\n// first we have to creates an empty\n// database on the system and\n// rewrites it with your own database.\n// Then we have to open the\n// database to fetch the data from it.\ndb = new DatabaseHelper(this);\ntry {\ndb.createDataBase();\ndb.openDataBase();\n}\ncatch (Exception e) {\ne.printStackTrace();\n}data = db.getAlgorithmTopics(this);\nadapter = new MyAdapter(this, data);\nrecyclerView.setAdapter(adapter);\n}\n}Output: "}, {"text": "\nCreating Multiple Screen Applications in Android\n\nThis article shows how to create an android application to move from one activity to another. Below are the steps for Creating a Simple Android Application to move from one activity to another activity.\nStep By Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.You will have XML and Activity Files, the path of both files is given below.Step 2: Working with the ActivityOne Kotlin/Java/XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n \n Go to the MainActivity File and refer to the following code.\nBelow is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.content.Intent; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; public class Oneactivity extends AppCompatActivity { // define the global variable \nTextView question1; \n// Add button Move to Activity \nButton next_Activity_button; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_oneactivity); // by ID we can use each component which id is assign in xml file \n// use findViewById() to get the Button \nnext_Activity_button = (Button) findViewById(R.id.first_activity_button); \nquestion1 = (TextView) findViewById(R.id.question1_id); // In question1 get the TextView use by findViewById() \n// In TextView set question Answer for message \nquestion1.setText(\"Q1 - How to pass the data between activities in Android?\\n\" + \"\\n\" + \"Ans - Intent\"); // Add_button add clicklistener \nnext_Activity_button.setOnClickListener(v -> { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called SecondActivity with the following code. \nIntent intent = new Intent(Oneactivity.this, SecondActivity.class); \n// start the activity connect to the specified class \nstartActivity(intent); \n}); \n} \n}Kotlin import android.content.Intent \nimport android.os.Bundle \nimport android.widget.Button \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class Oneactivity : AppCompatActivity() { // define the global variable \nprivate lateinit var question1: TextView \n// Add button Move to Activity \nprivate lateinit var next_Activity_button: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_oneactivity) // by ID we can use each component which id is assign in xml file \n// use findViewById() to get the Button \nnext_Activity_button = findViewById(R.id.first_activity_button) \nquestion1 = findViewById(R.id.question1_id) // In question1 get the TextView use by findViewById() \n// In TextView set question Answer for message \nquestion1.text = \"Q1 - How to pass the data between activities in Android? Ans - Intent\".trimIndent() // Add_button add clicklistener \nnext_Activity_button.setOnClickListener { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called SecondActivity with the following code. \nval intent = Intent(this, SecondActivity::class.java) \n// start the activity connect to the specified class \nstartActivity(intent) \n} \n} \n}Now we have to create another activity (SecondActivity) to move from one activity to another.\nCreate second activity and go to the android project > File >new > Activity > Empty ActivityStep 3: Working with the ActivityTwo Kotlin/Java/XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n Go to the MainActivity File and refer to the following code.\nBelow is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.content.Intent; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; public class SecondActivity extends AppCompatActivity { // define the global variable \nTextView question2; \n// Add button Move to next Activity and previous Activity \nButton next_button, previous_button; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_second); // by ID we can use each component which id is assign in xml \n// file use findViewById() to get the both Button and textview \nnext_button = (Button) findViewById(R.id.second_activity_next_button); \nprevious_button = (Button) findViewById(R.id.second_activity_previous_button); \nquestion2 = (TextView) findViewById(R.id.question2_id); // In question1 get the TextView use by findViewById() \n// In TextView set question Answer for message \nquestion2.setText(\"Q 2 - What is ADB in android?\\n\" + \"\\n\" + \"Ans- Android Debug Bridge\"); // Add_button add clicklistener \nnext_button.setOnClickListener(v -> { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called ThirdActivity with the following code. \nIntent intent = new Intent(SecondActivity.this, ThirdActivity.class); \n// start the activity connect to the specified class \nstartActivity(intent); \n}); // Add_button add clicklistener \nprevious_button.setOnClickListener(v -> { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called oneActivity with the following code \nIntent intent = new Intent(SecondActivity.this, Oneactivity.class); \n// start the activity connect to the specified class \nstartActivity(intent); \n}); \n} \n}Kotlin import android.content.Intent \nimport android.os.Bundle \nimport android.widget.Button \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class SecondActivity : AppCompatActivity() { // define the global variable \nprivate lateinit var question2: TextView \n// Add button Move to next Activity and previous Activity \nprivate lateinit var next_button: Button \nprivate lateinit var previous_button: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_second) // by ID we can use each component which id is assign in xml \n// file use findViewById() to get the both Button and textview \nnext_button = findViewById(R.id.second_activity_next_button) \nprevious_button = findViewById(R.id.second_activity_previous_button) \nquestion2 = findViewById(R.id.question2_id) // In question1 get the TextView use by findViewById() \n// In TextView set question Answer for message \nquestion2.text = \"Q2 - What is ADB in android? Ans - Android Debug Bridge\".trimIndent() // Add_button add clicklistener \nnext_button.setOnClickListener { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called ThirdActivity with the following code. \nval intent = Intent(this, ThirdActivity::class.java) \n// start the activity connect to the specified class \nstartActivity(intent) \n} // Add_button add clicklistener \nprevious_button.setOnClickListener { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called oneActivity with the following code \nval intent = Intent(this, Oneactivity::class.java) \n// start the activity connect to the specified class \nstartActivity(intent) \n} \n} \n}Now, we have to create third activity same as the second activity, and the path of this file is also the same as another.\n\u201cNow, you can create many activities like this\u201d. Here we add TextView for messages and one Button for goto previous activity. It will be shown belowStep 4: Working with the ActivityThree Kotlin/Java/XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n \n Go to the MainActivity File and refer to the following code.\nBelow is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.content.Intent; \nimport android.os.Bundle; \nimport android.widget.Button; \nimport android.widget.TextView; \nimport androidx.appcompat.app.AppCompatActivity; public class ThirdActivity extends AppCompatActivity { // define the global variable \nTextView question3; \n// Add button Move previous activity \nButton previous_button; @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_third); // by ID we can use each component which id is assign in xml \n// file use findViewById() to get the Button and textview. \nprevious_button = (Button) findViewById(R.id.third_activity_previous_button); \nquestion3 = (TextView) findViewById(R.id.question3_id); // In question1 get the TextView use by findViewById() \n// In TextView set question Answer for message \nquestion3.setText(\"Q 3 - How to store heavy structured data in android?\\n\" + \"\\n\" + \"Ans- SQlite database\"); \n// Add_button add clicklistener \nprevious_button.setOnClickListener(v -> { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called SecondActivity with the following code: \nIntent intent = new Intent(ThirdActivity.this, SecondActivity.class); \n// start the activity connect to the specified class \nstartActivity(intent); \n}); \n} \n}Kotlin import android.content.Intent \nimport android.os.Bundle \nimport android.widget.Button \nimport android.widget.TextView \nimport androidx.appcompat.app.AppCompatActivity class ThirdActivity : AppCompatActivity() { // define the global variable \nprivate lateinit var question3: TextView \n// Add button Move previous activity \nprivate lateinit var previous_button: Button override fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_third) // by ID we can use each component which id is assign in xml \n// file use findViewById() to get the Button and textview. \nprevious_button = findViewById(R.id.third_activity_previous_button) \nquestion3 = findViewById(R.id.question3_id) // In question1 get the TextView use by findViewById() \n// In TextView set question Answer for message \nquestion3.text = \"Q3 - How to store heavy structured data in android? Ans - SQlite database \".trimIndent() // Add_button add clicklistener \nprevious_button.setOnClickListener { \n// Intents are objects of the android.content.Intent type. Your code can send them to the Android system defining \n// the components you are targeting. Intent to start an activity called SecondActivity with the following code: \nval intent = Intent(this, SecondActivity::class.java) \n// start the activity connect to the specified class \nstartActivity(intent) \n} \n} \n}Output:"}, {"text": "\nHow to Generate Unsigned (Shareable) Apk in Android Studio?\n\nUnsigned Apk, as the name suggests it means it is not signed by any Keystore. A Keystore is basically a binary file that contains a set of private keys. Every App that we install using the Google Play App Store needs to be signed with a Keystore. The signed apk is simply the unsigned apk that has been signed via the JDK jarsigner tool.If you want to generate a signed apk then refer to How to Generate Signed Apk in Android Studio?Why do We Need to Generate an Unsigned Apk?\nWhen developers are developing the android application for end-users, they need to test the application for which they share that apk with their friends or client to get the feedback and the improvement need to be done. It is somewhat lengthy and difficult to generate a signed apk every time to share as that requires a Keystore(Unique). That is why most of the time we prefer to generate unsigned apk as that is even easy to be generated.\nDifference Between Signed and Unsigned ApkS.NoSigned ApkUnsigned Apk1Signed APK it\u2019s signed with your own key which is guarded by you\nUnsigned APK is actually signed by debugging key.2It is a somewhat lengthy process to generate Signed Apk\nIt is Easy to Generate Unsigned Apk3It is Secure.\nIt is not Secure4Generally Available on Play store\nOnly the Developer has unsigned Apk.5It is generated when we are releasing our App.\nIt is generating when we are testing our app.Generating Unsigned (Sharable) Apk in Android Studio\nStep 1: Build your project then go to the Build > Build Bundle(s)/APK(s) > Build APK(s) as shown in the below image.Step 2: Then, You will see that Gradle is building. Wait for 3 to 4 minutes to complete the build.Step 3: After the Gradle Build Running Completed Then In the Right Bottom Side, you will see something like this as shown in the below image.Step 4: Then Click on locate and you will see your Apk File as (app-debug.apk) and Now You can share this Apk file with anyone."}, {"text": "\nCustom ArrayAdapter with ListView in Android\n\nIn the previous article ArrayAdapter in Android with Example, it\u2019s been discussed how the ArrayAdapter works and what are the data sources which can be attached to the ArrayAdapter with ListView. In this article, it\u2019s been discussed how to implement custom ArrayAdapter with the ListView. Have a look at the following image in which a single view in the ArrayAdapter can be customized.Steps to Implement the Custom ArrayAdapter\nStep 1: Create an Empty Activity projectCreate an Empty Activity Android studio project. Refer to Android | How to Create/Start a New Project in Android Studio?\nAnd make sure to select the programming as Java.Step 2: Working with the activity_main.xmlIn the activity_main.xml file, the root view is ListView. Invoke the following code into the activity_main.xml file and mention the appropriate ID for the ListView.XML \n \n Step 3: Creating a custom View for ListViewUnder layout, the folder creates a layout as custom_list_view.xml and invokes the following code.XML \n For every single item in the ListView this layout creates the following view for every single item in the array adapter.Step 4: Create a custom class for custom layoutBy creating this custom class we invoke the getter and setter manually for the custom_list_view layout.\nCreate a custom class called NumbersView under the package folder of the Application.\nAnd invoke the following code.Java public class NumbersView { // the resource ID for the imageView \nprivate int ivNumbersImageId; // TextView 1 \nprivate String mNumberInDigit; // TextView 1 \nprivate String mNumbersInText; // create constructor to set the values for all the parameters of the each single view \npublic NumbersView(int NumbersImageId, String NumbersInDigit, String NumbersInText) { \nivNumbersImageId = NumbersImageId; \nmNumberInDigit = NumbersInDigit; \nmNumbersInText = NumbersInText; \n} // getter method for returning the ID of the imageview \npublic int getNumbersImageId() { \nreturn ivNumbersImageId; \n} // getter method for returning the ID of the TextView 1 \npublic String getNumberInDigit() { \nreturn mNumberInDigit; \n} // getter method for returning the ID of the TextView 2 \npublic String getNumbersInText() { \nreturn mNumbersInText; \n} \n}Step 5: Now create a custom ArrayAdapter class of the type NumbersViewUnder the same package name, create a NumbersViewAdapter.java class of the type NumbersView which extends the ArrayAdapter class.\nAnd invoke the following code inside the NumbersViewAdapter.java file. Comments are added for better understanding.Java import android.content.Context; \nimport android.view.LayoutInflater; \nimport android.view.View; \nimport android.view.ViewGroup; \nimport android.widget.ArrayAdapter; \nimport android.widget.ImageView; \nimport android.widget.TextView; \nimport androidx.annotation.NonNull; \nimport androidx.annotation.Nullable; \nimport java.util.ArrayList; public class NumbersViewAdapter extends ArrayAdapter { // invoke the suitable constructor of the ArrayAdapter class \npublic NumbersViewAdapter(@NonNull Context context, ArrayList arrayList) { // pass the context and arrayList for the super \n// constructor of the ArrayAdapter class \nsuper(context, 0, arrayList); \n} @NonNull\n@Override\npublic View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { // convertView which is recyclable view \nView currentItemView = convertView; // of the recyclable view is null then inflate the custom layout for the same \nif (currentItemView == null) { \ncurrentItemView = LayoutInflater.from(getContext()).inflate(R.layout.custom_list_view, parent, false); \n} // get the position of the view from the ArrayAdapter \nNumbersView currentNumberPosition = getItem(position); // then according to the position of the view assign the desired image for the same \nImageView numbersImage = currentItemView.findViewById(R.id.imageView); \nassert currentNumberPosition != null; \nnumbersImage.setImageResource(currentNumberPosition.getNumbersImageId()); // then according to the position of the view assign the desired TextView 1 for the same \nTextView textView1 = currentItemView.findViewById(R.id.textView1); \ntextView1.setText(currentNumberPosition.getNumberInDigit()); // then according to the position of the view assign the desired TextView 2 for the same \nTextView textView2 = currentItemView.findViewById(R.id.textView2); \ntextView2.setText(currentNumberPosition.getNumbersInText()); // then return the recyclable view \nreturn currentItemView; \n} \n}Step 6: Working with the MainActivity.java fileIn this case, there is a need to create a custom ArrayList of all the items that are Image for ImageView, Text for TextView 1, Text for TextView 2.Java import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport android.widget.ListView; \nimport java.util.ArrayList; public class MainActivity extends AppCompatActivity { @Override\nprotected void onCreate(Bundle savedInstanceState) { \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); // create a arraylist of the type NumbersView \nfinal ArrayList arrayList = new ArrayList(); // add all the values from 1 to 15 to the arrayList \n// the items are of the type NumbersView \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"1\", \"One\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"2\", \"Two\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"3\", \"Three\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"4\", \"Four\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"5\", \"Five\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"6\", \"Six\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"7\", \"Seven\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"8\", \"Eight\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"9\", \"Nine\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"10\", \"Ten\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"11\", \"Eleven\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"12\", \"Twelve\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"13\", \"Thirteen\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"14\", \"Fourteen\")); \narrayList.add(new NumbersView(R.drawable.geeks_logo, \"15\", \"Fifteen\")); // Now create the instance of the NumebrsViewAdapter and pass \n// the context and arrayList created above \nNumbersViewAdapter numbersArrayAdapter = new NumbersViewAdapter(this, arrayList); // create the instance of the ListView to set the numbersViewAdapter \nListView numbersListView = findViewById(R.id.listView); // set the numbersViewAdapter for ListView \nnumbersListView.setAdapter(numbersArrayAdapter); \n} \n}Output: Run on Emulatorhttps://media.geeksforgeeks.org/wp-content/uploads/20201125093947/Untitled-Project.mp4"}, {"text": "\nDifference Between MVC and MVP Architecture Pattern in Android\n\nDeveloping an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in the future. MVC (Model \u2014 View \u2014 Controller) and MVP (Model \u2014 View \u2014 Presenter) are the two most popular android architectures among developers.\nThe Model\u2014View\u2014Controller(MVC) Pattern\nThe MVC pattern suggests splitting the code into 3 components. While creating the class/file of the application, the developer must categorize it into one of the following three layers:\nModel: This component stores the application data. It has no knowledge about the interface. The model is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: It is the UI(User Interface) layer that holds components that are visible on the screen. Moreover, it provides the visualization of the data stored in the Model and offers interaction to the user.\nController: This component establishes the relationship between the View and the Model. It contains the core application logic and gets informed of the user\u2019s behavior and updates the Model as per the need.The Model\u2014View\u2014Presenter(MVP) Pattern\nMVP pattern overcomes the challenges of MVC and provides an easy way to structure the project codes. The reason why MVP is widely accepted is that it provides modularity, testability, and a more clean and maintainable codebase. It is composed of the following three components:\nModel: Layer for storing data. It is responsible for handling the domain logic(real-world business rules) and communication with the database and network layers.\nView: UI(User Interface) layer. It provides the visualization of the data and keep a track of the user\u2019s action in order to notify the Presenter.\nPresenter: Fetch the data from the model and applies the UI logic to decide what to display. It manages the state of the View and takes actions according to the user\u2019s input notification from the View.Key Differences Between MVC and MVP Design PatternMVC(Model View Controller)MVP(Model View PresenterOne of the oldest software architecture\nDeveloped as the second iteration of software architecture which is advance from MVC.UI(View) and data-access mechanism(Model) are tightly coupled.\nThe View is loosely coupled to the Model.Controller and View layer falls in the same activity/fragment\nCommunication between View-Presenter and Presenter-Model happens via an interface.User inputs are handled by Controller which instructs the model for further operations.\nUser inputs are handled by View which instructs the presenter to call appropriate functions.The many-to-one relationship exists between Controller and View as one Controller can select different View based upon required operations.\nThe one-to-one relationship exists between Presenter and View as one Presenter class manages one View at a time.The Controller is the overall in charge as it creates the appropriate View and interacts with the Model according to the user\u2019s request.\nThe View is the overall in charge in this schema as View call methods of Presenter which further directs Model.Limited support to Unit Testing\nUnit Testing is highly supported."}, {"text": "\nHow to add fading TextView animation in Android\n\nTextView is the basic building block of user interface components. It is used to set the text and display it to the user. It is a very basic component and used a lot. \nA Fading TextView is a TextView that changes its content automatically every few seconds. If we want to design a beautiful interface than we can use Fading TextView. \nApproach:Add this to your root build.gradle file (not your module build.gradle file): allprojects { \nrepositories { \njcenter() \n} \n} Add the support Library in your module\u2019s build.gradle file and add dependency in the dependencies section. dependencies { \nimplementation 'com.tomer:fadingtextview:2.5' \n} Now add the following code in the activity_main.xml file.activity_main.xml \n Now add the following code in the MainActivity.java file.MainActivity.java package org.geeksforgeeks.gfgFadingTextView; import androidx.appcompat.app.AppCompatActivity; \nimport android.os.Bundle; \nimport com.tomer.fadingtextview.FadingTextView; public class MainActivity extends AppCompatActivity { FadingTextView fadingTextView; \nString[] text \n= { \"GeeksForGeeks\", \"A\", \n\"Computer\", \"Science\", \"Portal\", \n\"For\", \"Geeks\" }; @Override\nprotected void onCreate(Bundle savedInstanceState) \n{ \nsuper.onCreate(savedInstanceState); \nsetContentView(R.layout.activity_main); fadingTextView \n= findViewById(R.id.fadingTextView); \nfadingTextView.setTexts(text); \n} \n} Output:https://media.geeksforgeeks.org/wp-content/uploads/20200507013947/Record_2020-05-06-19-55-21_a2713a04fe48232cffc9a346995b5281.mp4"}, {"text": "\nAndroid | AdMob Interstitial Ads for Android Studio\n\nInterstitial ads are full-screen ads that cover the whole UI of the app. This article shows you how to integrate Interstitial ads from AdMob into an Android app. Example \u2013 First Create a new Project in Android Studio and add the following codes to import the google Mobile Ads SDK. In the project-level build.gradle file, add the highlighted code to the allprojects section.Java allprojects\n{\nrepositories\n{\ngoogle()\njcenter()\nmaven\n{\nurl \"https://maven.google.com\"\n}\n}\n}In the app-level build.gradle file, add the highlighted code to dependencies section.Java dependencies\n{\nimplementation fileTree (dir : 'libs', include : [ '*.jar' ])\nimplementation 'com.android.support:appcompat-v7:26.1.0'\ncompile 'com.google.android.gms:play-services-ads:15.0.0'Add the following code to Main Activity to initialize Mobile Ads SDK (this only needs to be done once in app lifecycle). You can find the app\u2019s App ID in AdMob console.Java package org.geeksforgeeks.geeksforgeeks;import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport com.google.android.gms.ads.MobileAds;public class MainActivity extends AppCompatActivity \n{\nprotected void onCreate (Bundle savedInstanceState)\n{\nsuper.onCreate (savedInstanceState);\nsetContentView (R.layout.activity_main);// Initialize the Mobile Ads SDK\nMobileAds.initialize (this, getString (R.string.admob_app_id));\n}\n}Add the highlighted code to Main Activity to show Interstitial Ad: MainActivity.class \u2013JAVA package org.geeksforgeeks.geeksforgeeks;import android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.android.gms.ads.AdListener;\nimport com.google.android.gms.ads.AdRequest;\nimport com.google.android.gms.ads.InterstitialAd;\nimport com.google.android.gms.ads.MobileAds;public class MainActivity extends AppCompatActivity {private InterstitialAd interstitial;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// Initialize the Mobile Ads SDK\nMobileAds.initialize(this, getString(R.string.admob_app_id));// create ad request \nAdRequest adIRequest = new AdRequest.Builder().build();// Create an instance of the InterstitialAd object\ninterstitial = new InterstitialAd(MainActivity.this);// Set the Ad Unit ID\ninterstitial.setAdUnitId(getString(R.string.admob_interstitial_id));// Load the Interstitial Ad\ninterstitial.loadAd(adIRequest);// Prepare an Interstitial Ad Listener\ninterstitial.setAdListener(new AdListener() {\n@Override\npublic void onAdLoaded() {\n// Call displayInterstitial() function when the Ad loads\ndisplayInterstitial();\n}\n});\n}public void displayInterstitial() {\n// If Interstitial Ads are loaded then show them, otherwise do nothing.\nif (interstitial.isLoaded()) {\ninterstitial.show();\n}\n}\n}Add the Admob App Id and Interstitial Ad Id to string.xml strings.xml \u2013XML \n\n\nca-app-pub-3940256099942544~3347511713 \n\nca-app-pub-3940256099942544/1033173712 \n\n\n "}, {"text": "\nRecyclerView using ListView in Android With Example\n\nRecyclerView is more flexible and advanced version of ListView and GridView. RecyclerView is used for providing a limited window to a large data set, which means it is used to display a large amount of data that can be scrolled very efficiently by maintaining a limited number of Views. In RecyclerView we supply data and define how each item looks, and the RecyclerView library dynamically creates the content when it is needed. RecyclerView was introduced in Material Design in Android 5.0(API level 21.0).\nHow RecyclerView Works?RecyclerView is a ViewGroup that contains Views corresponding to your data. It itself a View so, it is added to the layout file as any other UI element is added.\nViewHolder Object is used to define each individual element in the list. View holder does not contain anything when it created, RecyclerView binds data to it. ViewHolder is defined by extending RecyclerView.ViewHolder.\nAdapters are used to bind data to the Views. RecyclerView request views, and binds the views to their data, by calling methods in the adapter. The adapter can be defined by extending RecyclerView.Adapter.\nLayoutManager arranges the individual elements in the list. It contains the reference of all views that are filled by the data of the entry.LayoutManager class of RecyclerView provide three types of built-in LayoutManagersLinearLayoutManager: It is used for displaying Horizontal and Vertical List\nGridLayoutManager: It is used for displaying items in the forms of grids\nStaggeredGridLayoutManager: It is used for displaying items in form of staggered gridsExample\nIn this example, we are going to use RecyclerView as ListView. Here, we are going to display the list of courses with their images as a vertical list using RecyclerView.\nStep by Step Implementation\nStep 1: Create A New Project\nTo create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.\nStep 2: Add Dependency\nWe are going to use RecyclerView as ListView. So, we need to add the dependency for it. For adding the dependency Go to Gradle Scripts > build.gradle(Module: app) and add the following dependency. After adding the dependency click on Sync Now.dependencies {\n implementation \u201candroidx.recyclerview:recyclerview:1.1.0\u201d\n}Before moving further let\u2019s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML \n#0F9D58 \n#16E37F \n#03DAC5 \n Step 3: Working with the activity_main.xml file\nIn this step, we will add a RecyclerView to our activity_main.xml file which is used to display data of listItems. Go to the app > res > layout > activity_main.xml and the following code snippet.XML \n\n Step 4: Create a new layout file list_item.xml\nIn this step, we will create a new layout file for the single list item view. Go to app > res > layout > right-click > New > Layout Resource File and name it as list_item. list_item.xml contains an ImageView and a TextView which is used for populating the RecyclerView.XML \n\n\n \n Step 5: Create a new Adapter class\nNow, we will create an Adapter class that acts as a bridge between the UI Component and the Data Source .i.e., courseImg, courseName, and RecyclerView. Go to the app > java > package > right-click and create a new java class and name it as Adapter. Below is the code snippet given for it.Java import android.content.Context;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.ImageView;\nimport android.widget.TextView;import androidx.annotation.NonNull;\nimport androidx.recyclerview.widget.RecyclerView;\nimport java.util.ArrayList;// Extends the Adapter class to RecyclerView.Adapter\n// and implement the unimplemented methods\npublic class Adapter extends RecyclerView.Adapter {\nArrayList courseImg, courseName;\nContext context;// Constructor for initialization\npublic Adapter(Context context, ArrayList courseImg, ArrayList courseName) {\nthis.context = context;\nthis.courseImg = courseImg;\nthis.courseName = courseName;\n}@NonNull\n@Override\npublic Adapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n// Inflating the Layout(Instantiates list_item.xml\n// layout file into View object)\nView view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);// Passing view to ViewHolder\nAdapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);\nreturn viewHolder;\n}// Binding data to the into specified position\n@Override\npublic void onBindViewHolder(@NonNull Adapter.ViewHolder holder, int position) {\n// TypeCast Object to int type\nint res = (int) courseImg.get(position);\nholder.images.setImageResource(res);\nholder.text.setText((String) courseName.get(position));\n}@Override\npublic int getItemCount() {\n// Returns number of items \n// currently available in Adapter\nreturn courseImg.size();\n}// Initializing the Views\npublic class ViewHolder extends RecyclerView.ViewHolder {\nImageView images;\nTextView text;public ViewHolder(View view) {\nsuper(view);\nimages = (ImageView) view.findViewById(R.id.courseImg);\ntext = (TextView) view.findViewById(R.id.courseName);\n}\n}\n}Step 6: Working with the MainActivity file\nIn MainActivity.java class we create two ArrayList for storing courseImg and courseName. These images are placed in the drawable folder(app > res > drawable). You can use any images in place of these. And then we get the reference RecyclerView and set the LayoutManager as LinearLayoutManager and Adapter, to show items in RecyclerView. Below is the code for the MainActivity.java file.Java import android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport androidx.recyclerview.widget.LinearLayoutManager;\nimport androidx.recyclerview.widget.RecyclerView;\nimport androidx.recyclerview.widget.StaggeredGridLayoutManager;\nimport java.util.ArrayList;\nimport java.util.Arrays;public class MainActivity extends AppCompatActivity {RecyclerView recyclerView;// Using ArrayList to store images data\nArrayList courseImg = new ArrayList<>(Arrays.asList(R.drawable.data_structure, R.drawable.c_plus_plus,\nR.drawable.c_hash, R.drawable.java_script, \nR.drawable.java, R.drawable.c,\nR.drawable.html, R.drawable.css));\nArrayList courseName = new ArrayList<>(Arrays.asList(\"Data Structure\", \"C++\", \"C#\", \"JavaScript\", \"Java\",\n\"C-Language\", \"HTML 5\", \"CSS\"));@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// Getting reference of recyclerView\nrecyclerView = (RecyclerView) findViewById(R.id.recyclerView);// Setting the layout as linear \n// layout for vertical orientation\nLinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());\nrecyclerView.setLayoutManager(linearLayoutManager);// Sending reference and data to Adapter\nAdapter adapter = new Adapter(MainActivity.this, courseImg, courseName);// Setting Adapter to RecyclerView\nrecyclerView.setAdapter(adapter);\n}\n}Output: Run On Emulator"}, {"text": "\nSwitch in Kotlin\n\nAndroid Switch is also a two-state user interface element that is used to toggle between ON and OFF as a button. By touching the button we can drag it back and forth to make it either ON or OFF.The Switch element is useful when only two states require for activity either choose ON or OFF. We can add a Switch to our application layout by using the Switch object. By default, the state for the android Switch is OFF state. We can also change the state of Switch to ON by setting the android:checked = \u201ctrue\u201d in our XML layout file.In android, we can create Switch control in two ways either by using Switch in XML layout file or creating it in Kotlin file dynamically.First, we create a new project by following the below steps:Click on File, then New => New Project.\nAfter that include the Kotlin support and click on next.\nSelect the minimum SDK as per convenience and click next button.\nThen select the Empty activity => next => finish.Different attributes of Switch widgetXML Attributes\nDescriptionandroid:id\nUsed to uniquely identify the control.android:gravity\nUsed to specify how to align the text like left, right, center, top, etc.android:checked\nUsed to specify the current state of switch control.android:thumb\nUsed to set drawable to be used as thumb that can be moved back and forth.android:thumbTint\nUsed to set tint to apply to the thumb.android:text\nUsed to set the text of the Switch.android:textOn\nUsed to set the text when toggle button is in ON (Checked) state.android:textOff\nUsed to set the text when toggle button is in Off (unchecked) state.android:textStyle\nUsed to set style of the text. For example, bold, italic, bolditalic etc.android:textColor\nUsed to set color of the text.android:textSize\nUsed to set size of the text.android:background\nUsed to set background color of the toggle button.android:drawableBottom\nUsed to set drawable to the bottom of the text.android:drawableLeft\nUsed to set drawable to left of the text.android:drawableRight\nUsed to set drawable to the right of text.android:padding\nUsed to set the padding from left, right, top and bottom.Adding Switch code in activity_main.xml file\nIn this file, we will use the LinearLayout and two switches inside it. Set the attributes of each switch like switch id, text etc.XML \n \n \n Add application name in strings.xml.XML \nSwitchInKotlin \n Accessing the Switch widget in MainActivity.kt file\nHere, we will access the switches by using their respective id\u2019s and set click Listener and Toast message if a switch is checked(ON) state.First of all, declare a variable to get the switch using it\u2019s id.\nval sw1 = findViewById(R.id.switch1)\nthen, set OnClick listener on the switch and use if condition to check the state of the button.\n \nsw1?.setOnCheckedChangeListener({ _ , isChecked ->\n val message = if (isChecked) \"Switch1:ON\" else \"Switch1:OFF\"\n Toast.makeText(this@MainActivity, message,\n Toast.LENGTH_SHORT).show()\n })\nRepeat the process for another switch in the kotlin file.Kotlin package com.geeksforgeeks.myfirstkotlinapp\nimport android.os.Bundle\nimport android.widget.Switch\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)val sw1 = findViewById(R.id.switch1)\nsw1?.setOnCheckedChangeListener({ _ , isChecked ->\nval message = if (isChecked) \"Switch1:ON\" else \"Switch1:OFF\"\nToast.makeText(this@MainActivity, message,\nToast.LENGTH_SHORT).show()\n})val sw2 = findViewById(R.id.switch2)\nsw2?.setOnCheckedChangeListener({ _ , isChecked ->\nval message = if (isChecked) \"Switch2:ON\" else \"Switch2:OFF\"\nToast.makeText(this@MainActivity, message,\nToast.LENGTH_SHORT).show()\n})\n}\n}AndroidManifest.xml fileXML \n\n\n\n \n \n \n Run as emulator for output:\nHere, two switches are shown in the emulator when we run the above code. We can change the state of the switches independently."}, {"text": "\nFoundation Components of Android Jetpack\n\nAndroid Jetpack is a set of software components, libraries, tools, and guidance to help in developing robust Android applications. Launched by Google in 2018, Jetpack comprises existing android support libraries, android architecture components with an addition of the Android KTX library as a single modular entity. Nowadays, nearly 99% of the apps present on the Google Play Store uses Android Jetpack libraries. The core system components of android apps reside in the Foundation area of Jetpack. Kotlin extension for the language support and Testing libraries are also present in it. Moreover, backward compatibility is provided from the libraries present in this component. This article explains each and every library of the Foundation component in detail. Jetpack consist of a wide collection of libraries that are built in a way to work together and make robust mobile applications. Its software components have been divided into 4 categories:Foundation Components\nArchitecture Components\nBehavior Components\nUI ComponentsFurther, the following are the list of all Foundation components:AppCompat\nAndroid KTX\nTest\nMultidexWays to include Android Jetpack libraries in the application\nAdd google repository in the build.gradle file of the application project.allprojects {\n repositories {\n google()\n mavenCentral()\n }\n}All Jetpack components are available in the Google Maven repository, include them in the build.gradle fileallprojects {\n repositories {\n google()\n mavenCentral()\n }\n}Foundation Components\n1. AppCompat\nThe AppCompat library in Jetpack foundation includes all of the components from the v7 library. This includes AppCompat, Cardview, GridLayout, MediaRouter, Palette, RecyclerView, Renderscript, Preferences, Leanback, Vector Drawable, Design, Custom tabs, etc. Moreover, this library provides implementation support to the material design user interface which makes AppCompat very useful for the developers. Following are some key areas of an android application that are difficult to build but can be designed effortlessly using the AppCompat library:App bar: The topmost element in an application is its app bar/action bar which generally contains the name of the application or current activity name. AppCompat library facilitates the developers to design a more customized App bar. It provides a toolbar for designing and painting the background of the app bar with primary colors or gradient background(multiple colors).\nNavigation drawer: It is the left pane menu that provides an easy navigation guide of the application. This is a very common design pattern nowadays, and so it is needed to add very often. By using the AppCompat library, it is very straightforward to manage the colors and icons of the navigation drawer. In order to create a navigation drawer, developers just required to add a DrawerLayout with the main view and a NavigationView. Further, this library also assists in managing the active state of each menu element with XML resources.\nPermissions: In the newer version of android OS, applications ask permission from users in order to access device hardware such as camera, microphone, etc or to perform certain actions. The further operations performed by the application depend upon the choice selected by the user i.e., whether permission is granted or not. However, this was not the case before the Marshmallow(6.0) version of the Android OS. In older versions, developers do not need to write any code in the SDK which asks permission from the users and check whether it is granted or not. This problem has been solved by the ContextCompat(a component of AppCompat) which checks the permission status of an operation and request from the user if needed irrespective of the android OS version.\nResources: Previously, more lines of code are needed to design the XML resources like drawable resources which are supported by a specific Android OS version. Using ContextCompat(part of AppCompat), the number of lines of code reduce drastically as well as the dependency of drawables on the OS version also removed.\nDialog box: The AppCompat library has an AppCompatDialog component which is similar to the toolbar. It helps in making the material design dialog box in an application.\nShare actions: Sharing of any document/file from one application to another platform is possible because of the AppCompat library. The list of share actions like Gmail, Facebook, message, etc which appears on the screen when a document/file is selected to share is provided by the Activity toolbar of the AppCompat library.2. Android KTX\nThis library is the only one among the foundation components which was introduced for the first time with the release of the Jetpack. Android KTX is a collection of Kotlin extensions that are designed to facilitate developers to remove boilerplate code as well as to write concise code while developing android applications with Kotlin language. Here KTX in the name stands for Kotlin Extensions. Below is an example of a piece of code without using and after using the Android KTX library:\nCode snippet of SQLite without using KTX library:db.beginTransaction()\ntry {\n// insert data\ndb.setTransactionSuccessful()\n}\nfinally {\ndb.endTransaction()\n}Above code after using KTX library:db.transaction {\n // insert data\n}This example clearly depicts how the Android KTX library reduced the lines of code and gracefully organized the SQLite transactions using a simple function along with a trailing lambda. Many of the jetpack libraries are linked with various Android KTX modules. For example, one can use the below extensions while working with the Navigation component of Android Jetpack. android.arch.navigation:navigation-common-ktx\nandroid.arch.navigation:navigation-fragment-ktx\nandroid.arch.navigation:navigation-runtime-ktx\nand android.arch.navigation:navigation-ui-ktx3. Test\nThis part of the foundation component includes the Espresso UI testing framework for the runtime UI test and AndroidJUnitRunner for the purpose of unit testing of Android applications. Espresso is primarily used for the testing of UI elements. Further, AndroidJUnitRunner performs small tests on the logic of each and every method. It assures the fast and accurate testing of a specific piece of logic within the project code.\n4. Multidex\nThe multidex property of Android is one of the most important features while developing mobile applications. Dex is the format of the executable file which runs on the Android virtual machine(known as Dalvik). To make a .dex file according to the Dalvik Executable specification, it must not contain more than 65,536 methods considering all libraries of the project.\nWhile making any real-life mobile application, the count of methods in project libraries can easily cross that number. In this situation, developers take the help of Multidex library which performs the system split of the .dex file of the application into multiple .dex files. Further, the Multidex component also provides support to the collective dex files of an application.\nDetecting the need for Multidex in the application:\nIt is impractical for anyone to keep a record of method count while developing an application. Thus to know if there is a need for Multidex in the project files or not, one should look out for the following errors. If the IDE shows one of these errors while building the application files, then it means there is a need to enable Multidex.\nError Message 1:trouble writing output:\nToo many field references: 131000; max is 65536.\nYou may try using \u2013multi-dex option.Error Message 2:Conversion to Dalvik format failed:\nUnable to execute dex: method ID not in [0, 0xffff]: 65536Enable Multidex:\nThe code to enable Multidex depends upon the minimum SDK version of the android app. For different SDK versions, below is the code snippet of the build.gradle file.\na. For minimum SDK version equal to or above 21:android{\n // \u2026\n defaultConfig {\n // \u2026\n minSdkVersion 21\n targetSdkVersion 30\n multiDexEnabled true\n }\n // \u2026\n}b. For minimum SDK version less than 21:\ni. For AndroidXandroid {\n defaultConfig {\n // \u2026\n minSdkVersion 18\n targetSdkVersion 30\n multiDexEnabled true\n }\n // \u2026\n}\ndependencies {\n // \u2026\n implementation \u2018androidx.multidex:multidex:2.0.0\u2019\n}ii. For old Support Library:android {\n defaultConfig {\n // \u2026\n minSdkVersion 18\n targetSdkVersion 30\n multiDexEnabled true\n }\n // \u2026\n}\ndependencies {\n // \u2026\n implementation \u2018com.android.support:multidex:1.0.3\u2019\n}"}, {"text": "\nCircular Reveal Animation in Android\n\nAnimations in Android play an important role in the user experience. This makes the user focus on the main content, which they want. And also helps in user interactivity. Animations communicate with the user to really get engaged in application usage. So in this article, one of the animations in android which is the most popular one, Circular reveal animation is discussed. Have a look at the following image to get an idea of how the circular animation looks like. Note that we are going toimplement this project using theKotlinlanguage.Steps to Implement the Circular Animation in Android\nStep 1: Create an empty activity projectCreate an empty activity Android Studio Project. Or refer to Android | How to Create/Start a New Project in Android Studio? to know how to create an empty activity Android Studio project. Note that select Kotlin as the programming language.Step 2: Working with the activity_main.xml fileTo implement the application\u2019s main layout in which includes only a single button, which when clicked on it triggers the Circular reveal animation.\nTo implement the UI invoke the following code inside the activity_main.xml file.XML \n \n \n Output UI:Now revealing the same layout from the bottom of the screen\nStep 3: Working with the MainActivity.kt fileFirstly, the code is for the circular reveal animation from the right bottom of the screen.\nInvoke the following code and refer to its output for better understanding, the comments are added for better understanding.Kotlin import android.animation.Animator \nimport android.annotation.SuppressLint \nimport android.content.res.ColorStateList \nimport android.os.Build \nimport android.os.Bundle \nimport android.view.View \nimport android.view.ViewAnimationUtils \nimport androidx.annotation.RequiresApi \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.core.content.res.ResourcesCompat \nimport com.google.android.material.floatingactionbutton.FloatingActionButton \nimport kotlin.math.hypot \nimport kotlin.math.max class MainActivity : AppCompatActivity() { private lateinit var mRevealLayout: View \nprivate lateinit var mFab: FloatingActionButton // boolean variable to check whether the \n// reveal layout is visible or not \nprivate var isRevealed = false@RequiresApi(Build.VERSION_CODES.M) \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) mRevealLayout = findViewById(R.id.revealLayout) \nmFab = findViewById(R.id.fab) // initially the color of the FAB should be green \nmFab.backgroundTintList = ColorStateList.valueOf( \nResourcesCompat.getColor( \nresources, \nR.color.green_500, \nnull\n) \n) // upon clicking the FAB the reveal should be \n// toggled according to the boolean value \nmFab.setOnClickListener { \nrevealLayoutFun() \n} \n} // this function is triggered when \n// the FAB is clicked \n@RequiresApi(Build.VERSION_CODES.M) \n@SuppressLint(\"ResourceAsColor\") \nprivate fun revealLayoutFun() { // based on the boolean value the \n// reveal layout should be toggled \nif (!isRevealed) { // get the right and bottom side \n// lengths of the reveal layout \nval x: Int = mRevealLayout.right \nval y: Int = mRevealLayout.bottom // here the starting radius of the reveal \n// layout is 0 when it is not visible \nval startRadius = 0// make the end radius should match \n// the while parent view \nval endRadius = hypot( \nmRevealLayout.width.toDouble(), \nmRevealLayout.height.toDouble() \n).toInt() // and set the background tint of the FAB to white \n// color so that it can be visible \nmFab.backgroundTintList = ColorStateList.valueOf( \nResourcesCompat.getColor( \nresources, \nR.color.white, \nnull\n) \n) \n// now set the icon as close for the FAB \nmFab.setImageResource(R.drawable.ic_close) // create the instance of the ViewAnimationUtils to \n// initiate the circular reveal animation \nval anim = ViewAnimationUtils.createCircularReveal( \nmRevealLayout, \nx, \ny, \nstartRadius.toFloat(), \nendRadius.toFloat() \n) // make the invisible reveal layout to visible \n// so that upon revealing it can be visible to user \nmRevealLayout.visibility = View.VISIBLE \n// now start the reveal animation \nanim.start() // set the boolean value to true as the reveal \n// layout is visible to the user \nisRevealed = true} else { // get the right and bottom side lengths \n// of the reveal layout \nval x: Int = mRevealLayout.right \nval y: Int = mRevealLayout.bottom // here the starting radius of the reveal layout is its full width \nval startRadius: Int = max(mRevealLayout.width, mRevealLayout.height) // and the end radius should be zero \n// at this point because the layout should be closed \nval endRadius = 0// now set the background tint of the FAB to green \n// so that it can be visible to the user \nmFab.backgroundTintList = ColorStateList.valueOf( \nResourcesCompat.getColor( \nresources, \nR.color.green_500, \nnull\n) \n) // now again set the icon of the FAB to plus \nmFab.setImageResource(R.drawable.ic_add) // create the instance of the ViewAnimationUtils to \n// initiate the circular reveal animation \nval anim = ViewAnimationUtils.createCircularReveal( \nmRevealLayout, \nx, \ny, \nstartRadius.toFloat(), \nendRadius.toFloat() \n) // now as soon as the animation is ending, the reveal \n// layout should also be closed \nanim.addListener(object : Animator.AnimatorListener { \noverride fun onAnimationStart(animator: Animator) {} \noverride fun onAnimationEnd(animator: Animator) { \nmRevealLayout.visibility = View.GONE \n} override fun onAnimationCancel(animator: Animator) {} \noverride fun onAnimationRepeat(animator: Animator) {} \n}) // start the closing animation \nanim.start() // set the boolean variable to false \n// as the reveal layout is invisible \nisRevealed = false\n} \n} \n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20210119152457/Untitled-Project.mp4\nNow revealing the same layout from the center of the screenNote: The layout of the application remains same only the code from the MainActivity.kt file are changed.Invoke the following code inside the MainActivity.kt file to reveal the same layout from the center of the screen.Kotlin import android.animation.Animator \nimport android.annotation.SuppressLint \nimport android.content.res.ColorStateList \nimport android.os.Build \nimport android.os.Bundle \nimport android.view.View \nimport android.view.ViewAnimationUtils \nimport androidx.annotation.RequiresApi \nimport androidx.appcompat.app.AppCompatActivity \nimport androidx.core.content.res.ResourcesCompat \nimport com.google.android.material.floatingactionbutton.FloatingActionButton \nimport kotlin.math.hypot \nimport kotlin.math.max class MainActivity : AppCompatActivity() { private lateinit var mRevealLayout: View \nprivate lateinit var mFab: FloatingActionButton // boolean variable to check whether \n// the reveal layout is visible or not \nprivate var isRevealed = false@RequiresApi(Build.VERSION_CODES.M) \noverride fun onCreate(savedInstanceState: Bundle?) { \nsuper.onCreate(savedInstanceState) \nsetContentView(R.layout.activity_main) mRevealLayout = findViewById(R.id.revealLayout) \nmFab = findViewById(R.id.fab) // initially the color of the FAB should be green \nmFab.backgroundTintList = ColorStateList.valueOf( \nResourcesCompat.getColor( \nresources, \nR.color.green_500, \nnull\n) \n) // upon clicking the FAB the reveal should \n// be toggled according to the boolean value \nmFab.setOnClickListener { \nrevealLayoutFun() \n} \n} // this function is triggered when \n// the FAB is clicked \n@RequiresApi(Build.VERSION_CODES.M) \n@SuppressLint(\"ResourceAsColor\") \nprivate fun revealLayoutFun() { // based on the boolean value the \n// reveal layout should be toggled \nif (!isRevealed) { // get the right and bottom side \n// lengths of the reveal layout \nval x: Int = mRevealLayout.right / 2\nval y: Int = mRevealLayout.bottom / 2// here the starting radius of the reveal \n// layout is 0 when it is not visible \nval startRadius = 0// make the end radius should \n// match the while parent view \nval endRadius = hypot( \nmRevealLayout.width.toDouble(), \nmRevealLayout.height.toDouble() \n).toInt() // and set the background tint of the FAB to white \n// color so that it can be visible \nmFab.backgroundTintList = ColorStateList.valueOf( \nResourcesCompat.getColor( \nresources, \nR.color.white, \nnull\n) \n) \n// now set the icon as close for the FAB \nmFab.setImageResource(R.drawable.ic_close) // create the instance of the ViewAnimationUtils to \n// initiate the circular reveal animation \nval anim = ViewAnimationUtils.createCircularReveal( \nmRevealLayout, \nx, \ny, \nstartRadius.toFloat(), \nendRadius.toFloat() \n) // make the invisible reveal layout to visible \n// so that upon revealing it can be visible to user \nmRevealLayout.visibility = View.VISIBLE \n// now start the reveal animation \nanim.start() // set the boolean value to true as the reveal \n// layout is visible to the user \nisRevealed = true} else { // get the right and bottom side lengths \n// of the reveal layout \nval x: Int = mRevealLayout.right / 2\nval y: Int = mRevealLayout.bottom / 2// here the starting radius of the reveal layout is its full width \nval startRadius: Int = max(mRevealLayout.width, mRevealLayout.height) // and the end radius should be zero at this \n// point because the layout should be closed \nval endRadius = 0// now set the background tint of the FAB to green \n// so that it can be visible to the user \nmFab.backgroundTintList = ColorStateList.valueOf( \nResourcesCompat.getColor( \nresources, \nR.color.green_500, \nnull\n) \n) // now again set the icon of the FAB to plus \nmFab.setImageResource(R.drawable.ic_add) // create the instance of the ViewAnimationUtils \n// to initiate the circular reveal animation \nval anim = ViewAnimationUtils.createCircularReveal( \nmRevealLayout, \nx, \ny, \nstartRadius.toFloat(), \nendRadius.toFloat() \n) // now as soon as the animation is ending, the reveal \n// layout should also be closed \nanim.addListener(object : Animator.AnimatorListener { \noverride fun onAnimationStart(animator: Animator) {} \noverride fun onAnimationEnd(animator: Animator) { \nmRevealLayout.visibility = View.GONE \n} override fun onAnimationCancel(animator: Animator) {} \noverride fun onAnimationRepeat(animator: Animator) {} \n}) // start the closing animation \nanim.start() // set the boolean variable to false \n// as the reveal layout is invisible \nisRevealed = false\n} \n} \n}Output:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210119152924/Untitled-Project.mp4"}, {"text": "\nWhat is the Difference Between \u201cpx\u201d, \u201cdip\u201d, \u201cdp\u201d and \u201csp\u201d in Android?\n\nAn XML-defined dimension value. A dimension is denoted by a number followed by a unit of measurement. For instance, 25px, 5in, 10dp and 10sp. When you use sp/dp, your Android applications will be compatible with a wide range of screen densities and resolutions.PX: is an abbreviation for Pixels, which specifies the actual pixels on the screen.\nSP: is an abbreviation for Scale independent pixels. It is the same as the dp unit, but it is additionally scaled according to the user\u2019s font size selection.\nDP: A virtual pixel unit used to communicate layout dimensions or location in a density-independent manner while creating UI layout. The density-independent pixel corresponds to one physical pixel on a 160 dpi screen, which is the system\u2019s baseline density for a \u201cmedium\u201d density screen. At runtime, the system handles any scaling of the dp units that is required based on the actual density of the screen in use in a transparent manner.The terms DP and DIP refer to Density Independent Pixels, which are based on the physical density of the screen.SP: Similar to dp, but also scaled by the user\u2019s font size selection. When choosing font sizes, it is recommended that you use this unit so that they are adjusted for both screen density and user choice.1. Orientation of the Android Device\nThe orientation of the screen is seen by the user. This is either landscape or portrait, indicating that the screen\u2019s aspect ratio is broad or tall. Be aware that various devices not only function in different orientations by default but that the orientation might change at runtime when the user spins the device.\n2. The density of the screen\nThe number of pixels inside a physical region of a screen; sometimes abbreviated as dpi (dots per inch). A \u201clow\u201d density screen, for example, contains fewer pixels inside a given physical area than a \u201cnormal\u201d or \u201chigh\u201d density screen. Android categorizes all real screen densities into six generic densities for ease of use: low, medium, high, extra-high, extra-extra-high, and extra-extra-extra-high.\n3. Resolution of the Android Device\nA screen\u2019s entire amount of physical pixels. When providing support for multiple screens, programs should not be concerned with resolution; instead, they should be concerned with screen size and density, as described by the generic size and density groups.\nDifference Tablepx (pixels)in (inches)mm (millimeters)pt (points)dp or dip (Density-independent Pixels)Refers to the actual pixels on the screen.\nDepending on the actual size of the screen in inches.\nDetermined by the actual size of the screen.\nBased on the actual size of the screen, 1/72 of an inch, assuming a screen with a resolution of 72dpi\nAn abstract unit based on on-screen physical density. These measurements are measured in relation to a 160 dpi screen.The compiler only accepts px\nThe compiler only accepts in (however this unit is not recommended because it may vary)\nThe compiler takes mm, but not by default (takes sp)\nNot a familiar unit, used in old Android Programming, by Eclipse. Still, the compiler takes it.\nThe Compiler accepts both \u201cdip\u201d and \u201cdp,\u201dThe actual physical present pixels of the screen is measured by its diagonal. Android combines all real screen sizes into four generic sizes for ease of use: small, standard, big, and extra-large.\nThe actual screen estate which is available on the running device is accessible to the Android OS.\nThe usual unit of measurement is millimeters, used like in everyday measurements.\nSimilar to the dp unit, but scaled by the user\u2019s font size selection. When choosing font sizes, it is suggested that you use this unit so that they are adjusted for both screen density and user choice.\nThe dp-to-pixel ratio will alter with screen density, but not always in a straight proportion. However \u201cdp\u201d is more consistent with \u201csp.\u201dCan be used to determine the layouts and elements places on the layout.\nCan be used to scale the elements on the screen concerning the actual screen.\nShould not be used for setting and determining the layouts due to the variations possible.\nCan be used to design the layout just like px but is preferred less as compared to the other measurements.\nThe \u201csp\u201d here is only used for text; it should never be used for layout sizes.px = dp * (dpi / 160)\nN/A (as the measurement is absolute)\nN/A (as the measurement is absolute)\nN/A (as the measurement is absolute)\nDensity = sqrt((wp * wp) + (hp * hp)) / diRepresented in terms of x*y.X is the horizontal axis, Y is the vertical.\nRepresented in absolute digits and integers within as suffix\nRepresented in absolute digits and integers within as mm\nRepresented as pts or pt depending on the version of Android Studio you are using.\nRepresented as simply \u2018dp\u2019 and to use with text use \u2018sp\u2019.NOT density-independent\nDensity Independent\nDensity Independent\nDensity Independent\nDensity IndependentGeekTip: A dimension is a basic resource that is referred to by the value specified in the name property (not the name of the XML file). As a result, dimension resources may be combined with other basic resources in a single XML file, under a single resource > element.Conclusion\nPixels per inch are higher on high-density screens than on low-density ones. As a result, the identical pixel dimensions UI components look larger on low-density screens and smaller on high-density devices. Density-independent pixels, abbreviated as dp (pronounced \u201cdips\u201d), are adaptable units with consistent size on any screen. They offer a versatile approach to fit a design across many platforms. Material UIs employ density-independent pixels to ensure that components appear consistently on displays of varying densities.\n"}, {"text": "\nHow to Delete Data from Firebase Firestore in Android?\n\nIn the previous article, we have seen on How to Add Data, Read Data, and Update data in Firebase Firestore in Android. Now we will see How to Delete this added data inside our Firebase Firestore. So we will move towards the implementation of this deleting data in Android Firebase. \nWhat we are going to build in this article? \nWe will be adding a simple button inside our update screen where we were updating our data and inside that screen, we will be adding a new button for deleting the course. After deleting, that course will be deleted from our database.\nStep by Step ImplementationStep 1: Creating a new button for deleting the data inside the activity_update_course.xml file\nAs we have created a new Update Course Activity in the previous article. So we will simply add a new button to it. Add the following code snippet to the activity_update_course.xml file.XML\n Below is the updated code for the activity_update_course.xml file.XML\n \n \n \n \n \n Step 2: Now we have to initialize this button in the UpdateCourses.java file and add onClickListener to it\nGo to the UpdateCourses.java file and add the following code snippet.Java// adding on click listener for delete button\ndeleteBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // calling method to delete the course.\n deleteCourse(courses);\n }\n });private void deleteCourse(Courses courses) {\n // below line is for getting the collection\n // where we are storing our courses.\n db.collection(\"Courses\").\n // after that we are getting the document\n // which we have to delete.\n document(courses.getId()).\n \n // after passing the document id we are calling\n // delete method to delete this document.\n delete().\n // after deleting call on complete listener\n // method to delete this data.\n addOnCompleteListener(new OnCompleteListener() {\n @Override\n public void onComplete(@NonNull Task task) {\n // inside on complete method we are checking \n // if the task is success or not.\n if (task.isSuccessful()) {\n // this method is called when the task is success\n // after deleting we are starting our MainActivity.\n Toast.makeText(UpdateCourse.this, \"Course has been deleted from Database.\", Toast.LENGTH_SHORT).show();\n Intent i = new Intent(UpdateCourse.this, MainActivity.class);\n startActivity(i);\n } else {\n // if the delete operation is failed \n // we are displaying a toast message.\n Toast.makeText(UpdateCourse.this, \"Fail to delete the course. \", Toast.LENGTH_SHORT).show();\n }\n }\n });\n }Below is the updated code for the UpdateCourses.java file. Javaimport android.content.Intent;\nimport android.os.Bundle;\nimport android.text.TextUtils;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.Toast;import androidx.annotation.NonNull;\nimport androidx.appcompat.app.AppCompatActivity;import com.google.android.gms.tasks.OnCompleteListener;\nimport com.google.android.gms.tasks.OnFailureListener;\nimport com.google.android.gms.tasks.OnSuccessListener;\nimport com.google.android.gms.tasks.Task;\nimport com.google.firebase.firestore.FirebaseFirestore;public class UpdateCourse extends AppCompatActivity { // creating variables for our edit text\n private EditText courseNameEdt, courseDurationEdt, courseDescriptionEdt; // creating a strings for storing our values from Edittext fields.\n private String courseName, courseDuration, courseDescription; // creating a variable for firebasefirestore.\n private FirebaseFirestore db; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_update_course);\n Courses courses = (Courses) getIntent().getSerializableExtra(\"course\"); // getting our instance from Firebase Firestore.\n db = FirebaseFirestore.getInstance(); // initializing our edittext and buttons\n courseNameEdt = findViewById(R.id.idEdtCourseName);\n courseDescriptionEdt = findViewById(R.id.idEdtCourseDescription);\n courseDurationEdt = findViewById(R.id.idEdtCourseDuration); // creating variable for button\n Button updateCOurseBtn = findViewById(R.id.idBtnUpdateCourse);\n Button deleteBtn = findViewById(R.id.idBtnDeleteCourse); courseNameEdt.setText(courses.getCourseName());\n courseDescriptionEdt.setText(courses.getCourseDescription());\n courseDurationEdt.setText(courses.getCourseDuration()); // adding on click listener for delete button\n deleteBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // calling method to delete the course.\n deleteCourse(courses);\n }\n }); updateCOurseBtn.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n courseName = courseNameEdt.getText().toString();\n courseDescription = courseDescriptionEdt.getText().toString();\n courseDuration = courseDurationEdt.getText().toString(); // validating the text fields if empty or not.\n if (TextUtils.isEmpty(courseName)) {\n courseNameEdt.setError(\"Please enter Course Name\");\n } else if (TextUtils.isEmpty(courseDescription)) {\n courseDescriptionEdt.setError(\"Please enter Course Description\");\n } else if (TextUtils.isEmpty(courseDuration)) {\n courseDurationEdt.setError(\"Please enter Course Duration\");\n } else {\n // calling a method to update our course.\n // we are passing our object class, course name,\n // course description and course duration from our edittext field.\n updateCourses(courses, courseName, courseDescription, courseDuration);\n }\n }\n });\n } private void deleteCourse(Courses courses) {\n // below line is for getting the collection\n // where we are storing our courses.\n db.collection(\"Courses\").\n // after that we are getting the document\n // which we have to delete.\n document(courses.getId()). // after passing the document id we are calling\n // delete method to delete this document.\n delete().\n // after deleting call on complete listener\n // method to delete this data.\n addOnCompleteListener(new OnCompleteListener() {\n @Override\n public void onComplete(@NonNull Task task) {\n // inside on complete method we are checking\n // if the task is success or not.\n if (task.isSuccessful()) {\n // this method is called when the task is success\n // after deleting we are starting our MainActivity.\n Toast.makeText(UpdateCourse.this, \"Course has been deleted from Database.\", Toast.LENGTH_SHORT).show();\n Intent i = new Intent(UpdateCourse.this, MainActivity.class);\n startActivity(i);\n } else {\n // if the delete operation is failed\n // we are displaying a toast message.\n Toast.makeText(UpdateCourse.this, \"Fail to delete the course. \", Toast.LENGTH_SHORT).show();\n }\n }\n });\n } private void updateCourses(Courses courses, String courseName, String courseDescription, String courseDuration) {\n // inside this method we are passing our updated values\n // inside our object class and later on we\n // will pass our whole object to firebase Firestore.\n Courses updatedCourse = new Courses(courseName, courseDescription, courseDuration); // after passing data to object class we are\n // sending it to firebase with specific document id.\n // below line is use to get the collection of our Firebase Firestore.\n db.collection(\"Courses\").\n // below line is use toset the id of\n // document where we have to perform\n // update operation.\n document(courses.getId()). // after setting our document id we are\n // passing our whole object class to it.\n set(updatedCourse). // after passing our object class we are\n // calling a method for on success listener.\n addOnSuccessListener(new OnSuccessListener() {\n @Override\n public void onSuccess(Void aVoid) {\n // on successful completion of this process\n // we are displaying the toast message.\n Toast.makeText(UpdateCourse.this, \"Course has been updated..\", Toast.LENGTH_SHORT).show();\n }\n }).addOnFailureListener(new OnFailureListener() {\n // inside on failure method we are\n // displaying a failure message.\n @Override\n public void onFailure(@NonNull Exception e) {\n Toast.makeText(UpdateCourse.this, \"Fail to update the data..\", Toast.LENGTH_SHORT).show();\n }\n });\n }\n}Output:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20210115214934/Screenrecorder-2021-01-15-21-41-08-100.mp4The Final Project File StructureBelow is the file structure for Java files:Below is the file structure for XML files:"}, {"text": "\nDropDownView in Android\n\nDropDownView is another exciting feature used in most Android applications. It is a unique way of representing the menu and other options in animated form. We can get to see the list of options under one heading in DropDownView. In this article, we are going to see how to implement DropDownView in Android. A sample GIF is given below to get an idea about what we are going to do in this article. We are going to implement this project using both Java and Kotlin Programming Language for Android.Applications of DropDownViewA unique way of representing data in the Animated form.\nMake it easy to navigate and find many options under one heading.\nLarge options can be displayed easily.Attributes of DropDownViewAttributesDescriptionlayout_width\nTo give width to the layout.layout_height\nTo give height to the layout.containerBackgroundColor\nTo give Background color to the container.overlayColor\nTo give Overlay Color.Step by Step Implementation\nStep 1: Create a New Project in Android Studio\nTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Add the Required Dependencies\nNavigate to the Gradle Scripts > build.gradle(Module:app) and Add the Below Dependency in the Dependencies section.\nimplementation 'com.github.AnthonyFermin:DropDownView:1.0.1'\nAdd the Support Library in your settings.gradle File. This library Jitpack is a novel package repository. It is made for JVM so that any library which is present in Github and Bitbucket can be directly used in the application.\ndependencyResolutionManagement {\n repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)\n repositories {\n google()\n mavenCentral()\n \n // add the following\n maven { url \"https://jitpack.io\" }\n }\n}\nAfter adding this Dependency, Sync the Project and now we will move towards its implementation.\nStep 3: Working with the XML Files\nNext, go to the activity_main.xml file, which represents the UI of the project. Below is the code for theactivity_main.xml file. Comments are added inside the code to understand the code in more detail.XML \n\n \n Create New Layout Resource Files\nNavigate to the app > res > layout > right-click > New > Layout resource file and name the files as header and footer.\nBelow is the code for the header.xml FileXML \n\n \n Below is the code for the footer.xml FileXML \n\n \n Step 5: Working with the MainActivity File\nGo to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.Java import android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.widget.Button;\nimport androidx.appcompat.app.AppCompatActivity;\nimport com.anthonyfdev.dropdownview.DropDownView;public class MainActivity extends AppCompatActivity {Button button;@Override\nprotected void onCreate(Bundle savedInstanceState) {\nsuper.onCreate(savedInstanceState);\nsetContentView(R.layout.activity_main);// Drop down menu given using id\nDropDownView dropDownView = (DropDownView) findViewById(R.id.drop_down_view);\nView collapsedView = LayoutInflater.from(this).inflate(R.layout.header, null, false);\nView expandedView = LayoutInflater.from(this).inflate(R.layout.footer, null, false);dropDownView.setHeaderView(collapsedView);\ndropDownView.setExpandedView(expandedView);collapsedView.setOnClickListener(v -> {\n// on click the drop down will open or close\nif (dropDownView.isExpanded()) {\ndropDownView.collapseDropDown();\n} else {\ndropDownView.expandDropDown();\n}\n});\n}\n}Kotlin import android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.widget.Button\nimport androidx.appcompat.app.AppCompatActivity\nimport com.anthonyfdev.dropdownview.DropDownViewclass MainActivity : AppCompatActivity() {private lateinit var button: Buttonoverride fun onCreate(savedInstanceState: Bundle?) {\nsuper.onCreate(savedInstanceState)\nsetContentView(R.layout.activity_main)// Drop down menu given using id\nval dropDownView: findViewById(R.id.drop_down_view) \nval collapsedView: View = LayoutInflater.from(this).inflate(R.layout.header, null, false)\nval expandedView: View = LayoutInflater.from(this).inflate(R.layout.footer, null, false)dropDownView.setHeaderView(collapsedView)\ndropDownView.setExpandedView(expandedView)\ncollapsedView.setOnClickListener {\n// on click the drop down will open or close\nif (dropDownView.isExpanded()) {\ndropDownView.collapseDropDown()\n} else {\ndropDownView.expandDropDown()\n}\n}\n}\n}Output:https://media.geeksforgeeks.org/wp-content/uploads/20210124143314/Screenrecorder-2021-01-24-14-29-19-301.mp4"}, {"text": "\nPush Notifications in Android Using OneSignal\n\nWe have seen so many types of notifications that we received in many of the Android apps. These notifications inform our users about the new offers, new features, and many more inside our application. In this article, we will take a look at the implementation of the OneSignal notification platform in the Android app in Android Studio. We will be building a simple application in which we will be sending notifications from the One Signal platform in our Android app.\nStep by Step ImplementationStep 1: Create a New Project in Android StudioTo create a new project in Android Studio please refer toHow to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.\nStep 2: Connect your App to FirebaseAfter creating a new project. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options Connect the app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not.\nStep 3: Adding Dependencies in the build.gradle fileNow we will add the dependency for using One Signal in our Gradle file. Navigate to build.gradle (:app) and add the below line in the plugins section.\nplugins { id 'com.android.application' id 'com.google.gms.google-services' // add below line is plugins id 'com.onesignal.androidsdk.onesignal-gradle-plugin'} Add the below line in the dependencies section of the same file.\nimplementation 'com.onesignal:OneSignal:[4.0.0, 4.99.99]'Now we will add the below dependencies in the dependency section. Navigate to build.gradle (Your app name) and add the below code to it.\nbuildscript { repositories { google() jcenter() // add below line in build script > repositories section. gradlePluginPortal() } dependencies { classpath \"com.android.tools.build:gradle:4.1.1\" classpath 'com.google.gms:google-services:4.3.4' // add below line in dependencies section classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.9, 0.99.99]' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }} After adding the above dependencies section then sync your project and now we will move toward the XML part.\nStep 4: Adding Permissions for the Internet Step 5: Working with the activity_main.xml fileNavigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.XML\n \n \n Step 6: Generating App ID for the ApplicationFor generating our app ID we have to sign up to One Signal similar to that we used to sign in to GeeksforGeeks using a Google account. After signing into One Signal you will get to see the below screen to create a new app.Inside this screen, You have to enter your app name, select the application type as Android and click on the Next option to configure your project. After clicking on the Next option you will get to see two text fields to enter two keys.\nStep 7: Getting the Keys to Enter in One Signal ConsoleAfter adding this code go to this link to open Firebase. After clicking on this link you will get to see the below page and on this page Click on Go to Console option in the top right corner. After clicking on this screen you will get to see the below screen with your all project inside that select your project. After clicking on your project name you have to click on the settings option and select on Project settings option. The settings options are shown below.After clicking on Project settings. Navigate to Cloud messaging tab which is shown below. There we will get to see the server key and sender id. You can get to see this below screen.You have to copy these two keys and paste them into your one signal console.After adding these keys click on the Next option to proceed further. You will get to see the below screen.Inside this screen select the Android option and click on the Next option to proceed further. You will get to see your App ID is displayed on the screen.\nStep 8: Working with the MainActivity fileGo to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.Javaimport android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\nimport com.onesignal.OneSignal;public class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n // OneSignal Initialization\n OneSignal.initWithContext(this);\n // on below line we are setting app id for our one signal\n OneSignal.setAppId(\"Enter your app id here\");\n }\n}Kotlinimport android.os.Bundle\nimport androidx.appcompat.app.AppCompatActivity\nimport com.onesignal.OneSignalclass MainActivity : AppCompatActivity() {\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) // OneSignal Initialization\n OneSignal.initWithContext(this)\n // on below line we are setting app id for our one signal\n OneSignal.setAppId(\"Enter your app id here\")\n }\n}Now run your app and we will send our first notification in our Android app. For sending notifications in One Signal click on your app name in the top left corner of One Signal Console and then click on your app name you will get to see the Dashboard screen.Click on the New Push option to send a new notification. After clicking on the New Push option you will get to see the below screen.Inside this screen, select Send to Subscribed users option, add the title option add your Notification title in the title field, and Notification Message in the message section, and scroll down to proceed further.After scrolling down click on the review and send option to send your notification. After that, your notification will be sent to your app. You can get to see the output of the app on the below screen.\nOutput:https://media.geeksforgeeks.org/wp-content/uploads/20210129225052/Screenrecorder-2021-01-29-20-20-35-587.mp4\n"}, {"text": "\nContent Providers in Android with Example\n\nIn Android, Content Providers are a very important component that serves the purpose of a relational database to store the data of applications. The role of the content provider in the android system is like a central repository in which data of the applications are stored, and it facilitates other applications to securely access and modifies that data based on the user requirements. Android system allows the content provider to store the application data in several ways. Users can manage to store the application data like images, audio, videos, and personal contact information by storing them in SQLite Database, in files, or even on a network. In order to share the data, content providers have certain permissions that are used to grant or restrict the rights to other applications to interfere with the data.Content URI\nContent URI(Uniform Resource Identifier) is the key concept of Content providers. To access the data from a content provider, URI is used as a query string.Structure of a Content URI: content://authority/optionalPath/optionalIDDetails of different parts of Content URI:content:// \u2013 Mandatory part of the URI as it represents that the given URI is a Content URI.\nauthority \u2013 Signifies the name of the content provider like contacts, browser, etc. This part must be unique for every content provider.\noptionalPath \u2013 Specifies the type of data provided by the content provider. It is essential as this part helps content providers to support different types of data that are not related to each other like audio and video files.\noptionalID \u2013 It is a numeric value that is used when there is a need to access a particular record.If an ID is mentioned in a URI then it is an id-based URI otherwise a directory-based URI.\nOperations in Content Provider\nFour fundamental operations are possible in Content Provider namely Create, Read, Update, and Delete. These operations are often termed as CRUD operations.Create: Operation to create data in a content provider.\nRead: Used to fetch data from a content provider.\nUpdate: To modify existing data.\nDelete: To remove existing data from the storage.Working of the Content Provider\nUI components of android applications like Activity and Fragments use an object CursorLoader to send query requests to ContentResolver. The ContentResolver object sends requests (like create, read, update, and delete) to the ContentProvider as a client. After receiving a request, ContentProvider process it and returns the desired result. Below is a diagram to represent these processes in pictorial form.Creating a Content Provider\nFollowing are the steps which are essential to follow in order to create a Content Provider:Create a class in the same directory where the that MainActivity file resides and this class must extend the ContentProvider base class.\nTo access the content, define a content provider URI address.\nCreate a database to store the application data.\nImplement the six abstract methods of ContentProvider class.\nRegister the content provider in AndroidManifest.xml file using tag.Following are the six abstract methods and their description which are essential to override as the part of ContenProvider class:Abstract MethodDescriptionquery()A method that accepts arguments and fetches the data from the\ndesired table. Data is retired as a cursor object.insert()To insert a new row in the database of the content provider.\nIt returns the content URI of the inserted row.update()This method is used to update the fields of an existing row.\nIt returns the number of rows updated.delete()This method is used to delete the existing rows.\nIt returns the number of rows deleted.getType()This method returns the Multipurpose Internet Mail Extension(MIME)\ntype of data to the given Content URI.onCreate()As the content provider is created, the android system calls\nthis method immediately to initialise the provider.Example\nThe prime purpose of a content provider is to serve as a central repository of data where users can store and can fetch the data. The access of this repository is given to other applications also but in a safe manner in order to serve the different requirements of the user. The following are the steps involved in implementing a content provider. In this content provider, the user can store the name of persons and can fetch the stored data. Moreover, another application can also access the stored data and can display the data.Note: Following steps are performed on Android Studio version 4.0Creating a Content Provider:\nStep 1: Create a new projectClick on File, then New => New Project.\nSelect language as Java/Kotlin.\nChoose empty activity as a template\nSelect the minimum SDK as per your need.Step 2: Modify the strings.xml file\nAll the strings used in the activity are stored here.XML \nContent_Provider_In_Android \nEnter User Name \nContent Provider In Android \nInsert Data \nLoad Data \n Step 3: Creating the Content Provider classClick on File, then New => Other => ContentProvider.\nName the ContentProvider\nDefine authority (it can be anything for example \u201ccom.demo.user.provider\u201d)\nSelect Exported and Enabled option\nChoose the language as Java/KotlinThis class extends the ContentProvider base class and override the six abstract methods. Below is the complete code to define a content provider.Java package com.example.contentprovidersinandroid;import android.content.ContentProvider;\nimport android.content.ContentUris;\nimport android.content.ContentValues;\nimport android.content.Context;\nimport android.content.UriMatcher;\nimport android.database.Cursor;\nimport android.database.sqlite.SQLiteDatabase;\nimport android.database.sqlite.SQLiteException;\nimport android.database.sqlite.SQLiteOpenHelper;\nimport android.database.sqlite.SQLiteQueryBuilder;\nimport android.net.Uri;\nimport java.util.HashMap;public class MyContentProvider extends ContentProvider {\npublic MyContentProvider() {\n}// defining authority so that other application can access it\nstatic final String PROVIDER_NAME = \"com.demo.user.provider\";// defining content URI\nstatic final String URL = \"content://\" + PROVIDER_NAME + \"/users\";// parsing the content URI\nstatic final Uri CONTENT_URI = Uri.parse(URL);static final String id = \"id\";\nstatic final String name = \"name\";\nstatic final int uriCode = 1;\nstatic final UriMatcher uriMatcher;\nprivate static HashMap values;static {// to match the content URI\n// every time user access table under content provider\nuriMatcher = new UriMatcher(UriMatcher.NO_MATCH);// to access whole table\nuriMatcher.addURI(PROVIDER_NAME, \"users\", uriCode);// to access a particular row\n// of the table\nuriMatcher.addURI(PROVIDER_NAME, \"users/*\", uriCode);\n}\n@Override\npublic String getType(Uri uri) {\nswitch (uriMatcher.match(uri)) {\ncase uriCode:\nreturn \"vnd.android.cursor.dir/users\";\ndefault:\nthrow new IllegalArgumentException(\"Unsupported URI: \" + uri);\n}\n}\n// creating the database\n@Override\npublic boolean onCreate() {\nContext context = getContext();\nDatabaseHelper dbHelper = new DatabaseHelper(context);\ndb = dbHelper.getWritableDatabase();\nif (db != null) {\nreturn true;\n}\nreturn false;\n}\n@Override\npublic Cursor query(Uri uri, String[] projection, String selection,\nString[] selectionArgs, String sortOrder) {\nSQLiteQueryBuilder qb = new SQLiteQueryBuilder();\nqb.setTables(TABLE_NAME);\nswitch (uriMatcher.match(uri)) {\ncase uriCode:\nqb.setProjectionMap(values);\nbreak;\ndefault:\nthrow new IllegalArgumentException(\"Unknown URI \" + uri);\n}\nif (sortOrder == null || sortOrder == \"\") {\nsortOrder = id;\n}\nCursor c = qb.query(db, projection, selection, selectionArgs, null,\nnull, sortOrder);\nc.setNotificationUri(getContext().getContentResolver(), uri);\nreturn c;\n}// adding data to the database\n@Override\npublic Uri insert(Uri uri, ContentValues values) {\nlong rowID = db.insert(TABLE_NAME, \"\", values);\nif (rowID > 0) {\nUri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);\ngetContext().getContentResolver().notifyChange(_uri, null);\nreturn _uri;\n}\nthrow new SQLiteException(\"Failed to add a record into \" + uri);\n}@Override\npublic int update(Uri uri, ContentValues values, String selection,\nString[] selectionArgs) {\nint count = 0;\nswitch (uriMatcher.match(uri)) {\ncase uriCode:\ncount = db.update(TABLE_NAME, values, selection, selectionArgs);\nbreak;\ndefault:\nthrow new IllegalArgumentException(\"Unknown URI \" + uri);\n}\ngetContext().getContentResolver().notifyChange(uri, null);\nreturn count;\n}@Override\npublic int delete(Uri uri, String selection, String[] selectionArgs) {\nint count = 0;\nswitch (uriMatcher.match(uri)) {\ncase uriCode:\ncount = db.delete(TABLE_NAME, selection, selectionArgs);\nbreak;\ndefault:\nthrow new IllegalArgumentException(\"Unknown URI \" + uri);\n}\ngetContext().getContentResolver().notifyChange(uri, null);\nreturn count;\n}// creating object of database\n// to perform query\nprivate SQLiteDatabase db;// declaring name of the database\nstatic final String DATABASE_NAME = \"UserDB\";// declaring table name of the database\nstatic final String TABLE_NAME = \"Users\";// declaring version of the database\nstatic final int DATABASE_VERSION = 1;// sql query to create the table\nstatic final String CREATE_DB_TABLE = \" CREATE TABLE \" + TABLE_NAME\n+ \" (id INTEGER PRIMARY KEY AUTOINCREMENT, \"\n+ \" name TEXT NOT NULL);\";// creating a database\nprivate static class DatabaseHelper extends SQLiteOpenHelper {// defining a constructor\nDatabaseHelper(Context context) {\nsuper(context, DATABASE_NAME, null, DATABASE_VERSION);\n}// creating a table in the database\n@Override\npublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_DB_TABLE);\n}@Override\npublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// sql query to drop a table\n// having similar name\ndb.execSQL(\"DROP TABLE IF EXISTS \" + TABLE_NAME);\nonCreate(db);\n}\n}\n}Kotlin package com.example.contentprovidersinandroidimport android.content.*\nimport android.database.Cursor\nimport android.database.sqlite.SQLiteDatabase\nimport android.database.sqlite.SQLiteException\nimport android.database.sqlite.SQLiteOpenHelper\nimport android.database.sqlite.SQLiteQueryBuilder\nimport android.net.Uriclass MyContentProvider : ContentProvider() {\ncompanion object {\n// defining authority so that other application can access it\nconst val PROVIDER_NAME = \"com.demo.user.provider\"// defining content URI\nconst val URL = \"content://$PROVIDER_NAME/users\"// parsing the content URI\nval CONTENT_URI = Uri.parse(URL)\nconst val id = \"id\"\nconst val name = \"name\"\nconst val uriCode = 1\nvar uriMatcher: UriMatcher? = null\nprivate val values: HashMap? = null// declaring name of the database\nconst val DATABASE_NAME = \"UserDB\"// declaring table name of the database\nconst val TABLE_NAME = \"Users\"// declaring version of the database\nconst val DATABASE_VERSION = 1// sql query to create the table\nconst val CREATE_DB_TABLE =\n(\" CREATE TABLE \" + TABLE_NAME\n+ \" (id INTEGER PRIMARY KEY AUTOINCREMENT, \"\n+ \" name TEXT NOT NULL);\")init {// to match the content URI\n// every time user access table under content provider\nuriMatcher = UriMatcher(UriMatcher.NO_MATCH)// to access whole table\nuriMatcher!!.addURI(\nPROVIDER_NAME,\n\"users\",\nuriCode\n)// to access a particular row\n// of the table\nuriMatcher!!.addURI(\nPROVIDER_NAME,\n\"users/*\",\nuriCode\n)\n}\n}override fun getType(uri: Uri): String? {\nreturn when (uriMatcher!!.match(uri)) {\nuriCode -> \"vnd.android.cursor.dir/users\"\nelse -> throw IllegalArgumentException(\"Unsupported URI: $uri\")\n}\n}// creating the database\noverride fun onCreate(): Boolean {\nval context = context\nval dbHelper =\nDatabaseHelper(context)\ndb = dbHelper.writableDatabase\nreturn if (db != null) {\ntrue\n} else false\n}override fun query(\nuri: Uri, projection: Array?, selection: String?,\nselectionArgs: Array?, sortOrder: String?\n): Cursor? {\nvar sortOrder = sortOrder\nval qb = SQLiteQueryBuilder()\nqb.tables = TABLE_NAME\nwhen (uriMatcher!!.match(uri)) {\nuriCode -> qb.projectionMap = values\nelse -> throw IllegalArgumentException(\"Unknown URI $uri\")\n}\nif (sortOrder == null || sortOrder === \"\") {\nsortOrder = id\n}\nval c = qb.query(\ndb, projection, selection, selectionArgs, null,\nnull, sortOrder\n)\nc.setNotificationUri(context!!.contentResolver, uri)\nreturn c\n}// adding data to the database\noverride fun insert(uri: Uri, values: ContentValues?): Uri? {\nval rowID = db!!.insert(TABLE_NAME, \"\", values)\nif (rowID > 0) {\nval _uri =\nContentUris.withAppendedId(CONTENT_URI, rowID)\ncontext!!.contentResolver.notifyChange(_uri, null)\nreturn _uri\n}\nthrow SQLiteException(\"Failed to add a record into $uri\")\n}override fun update(\nuri: Uri, values: ContentValues?, selection: String?,\nselectionArgs: Array?\n): Int {\nvar count = 0\ncount = when (uriMatcher!!.match(uri)) {\nuriCode -> db!!.update(TABLE_NAME, values, selection, selectionArgs)\nelse -> throw IllegalArgumentException(\"Unknown URI $uri\")\n}\ncontext!!.contentResolver.notifyChange(uri, null)\nreturn count\n}override fun delete(\nuri: Uri,\nselection: String?,\nselectionArgs: Array