[
{
"instruction": "\nAnimation in Android with ExampleAnimation is the process of adding a motion effect to any view, image, or text. With the help of an animation, you can add motion or can change the shape of a specific view. Animation in Android is generally used to give your UI a rich look and feel. The animations are basically of three types as follows:\nProperty AnimationView AnimationDrawable Animation1. Property AnimationProperty Animation is one of the robust frameworks which allows animation almost everything. This is one of the powerful and flexible animations which was introduced in Android 3.0. Property animation can be used to add any animation in the CheckBox, RadioButtons, and widgets other than any view.2. View AnimationView Animation can be used to add animation to a specific view to perform tweened animation on views. Tweened animation calculates animation information such as size, rotation, start point, and endpoint. These animations are slower and less flexible. An example of View animation can be used if we want to expand a specific layout in that place we can use View Animation. The example of View Animation can be seen in Expandable RecyclerView.3. Drawable AnimationDrawable Animation is used if you want to animate one image over another. The simple way to understand is to animate drawable is to load the series of drawable one after another to create an animation. A simple example of drawable animation can be seen in many apps Splash screen on apps logo animation.Important Methods of AnimationMethods\nDescription\nstartAnimation()This method will start the animation.clearAnimation()This method will clear the animation running on a specific view.Example of Implementation Android Animation Now we will see the Simple Example to add animations to ImageView. Note that we are going toimplement this project using theJavalanguage.\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 Java as the programming language.\nStep 2: Working with the strings.xml fileStrings.xml can be found from the app > res > values > strings.xml. \nBelow is the snippet for the strings.xml file.\nstrings.xml\n GFG App \n BLINK \n ROTATE \n FADE \n MOVE \n SLIDE \n ZOOM \n STOP ANIMATION \n Course Rating \n Course Name \n Step 3: Working with the activity_main.xml fileCreate ImageView in the activity_main.xml along with buttons that will add animation to the view. Navigate to the app > res > layout > activity_main.xml. \nBelow is the code for the activity_main.xml file.activity_main.xml\n \n \n \n \n \n \n \n \n \n \n \n \n Step 4: Create 6 different types of animation for ImageViewTo create new animations we have to create a new directory for storing all our animations. Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your directory as \u201canim\u201d. Inside this directory, we will create our animations. For creating a new anim right click on the anim directory >> Animation Resource file and give the name to your file. Below is the code snippet for 6 different animations.\n1. Blink Animation\nblink_animation.xml\n\n \n 2. Fade Animation\nfade_animation.xml\n\n \n \n 3. Move Animation\nmove_animation.xml\n \n 4. Rotate Animation\nrotate_animation.xml\n\n 5. Slide Animation\nslide_animation.xml\n\n \n 6. Zoom Animation\nzoom_animation.xml\n\n \n \n Step 5: Working with the MainActivity.java fileAdd animation to the ImageView by clicking a specific Button. Navigate to the app > java > your apps package name >> MainActivity.java.\nBelow is the implementation of MainActivity file:\nMainActivity.javaimport 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 { // Declare ImageView and Buttons\n ImageView imageView;\n Button blinkBTN, rotateBTN, fadeBTN, moveBTN, slideBTN, zoomBTN, stopBTN; @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main); // Initialize ImageView and Buttons using their IDs\n imageView = findViewById(R.id.imageview);\n blinkBTN = findViewById(R.id.BTNblink);\n rotateBTN = findViewById(R.id.BTNrotate);\n fadeBTN = findViewById(R.id.BTNfade);\n moveBTN = findViewById(R.id.BTNmove);\n slideBTN = findViewById(R.id.BTNslide);\n zoomBTN = findViewById(R.id.BTNzoom);\n stopBTN = findViewById(R.id.BTNstop); // Set up click listener for blink button to start blink animation\n blinkBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Load blink animation and start it on the ImageView\n Animation animation = AnimationUtils.loadAnimation(getApplicationContext()\n , R.anim.blink_animation);\n imageView.startAnimation(animation);\n }\n }); // Set up click listener for rotate button to start rotate animation\n rotateBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Load rotate animation and start it on the ImageView\n Animation animation = AnimationUtils.loadAnimation(getApplicationContext()\n , R.anim.rotate_animation);\n imageView.startAnimation(animation);\n }\n }); // Set up click listener for fade button to start fade animation\n fadeBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Load fade animation and start it on the ImageView\n Animation animation = AnimationUtils.loadAnimation(getApplicationContext()\n , R.anim.fade_animation);\n imageView.startAnimation(animation);\n }\n }); // Set up click listener for move button to start move animation\n moveBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Load move animation and start it on the ImageView\n Animation animation = AnimationUtils.loadAnimation(getApplicationContext()\n , R.anim.move_animation);\n imageView.startAnimation(animation);\n }\n }); // Set up click listener for slide button to start slide animation\n slideBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Load slide animation and start it on the ImageView\n Animation animation = AnimationUtils.loadAnimation(getApplicationContext()\n , R.anim.slide_animation);\n imageView.startAnimation(animation);\n }\n }); // Set up click listener for zoom button to start zoom animation\n zoomBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Load zoom animation and start it on the ImageView\n Animation animation = AnimationUtils.loadAnimation(getApplicationContext()\n , R.anim.zoom_animation);\n imageView.startAnimation(animation);\n }\n }); // Set up click listener for stop button to clear any ongoing animation\n stopBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n // Clear the animation on the ImageView\n imageView.clearAnimation();\n }\n });\n }\n}MainActivity.ktpackage com.gfg.animation_androidimport android.os.Bundle\nimport android.view.View\nimport android.widget.Button\nimport android.widget.ImageView\nimport android.view.animation.AnimationUtils\nimport androidx.appcompat.app.AppCompatActivityclass MainActivity : AppCompatActivity() { // Declare variables for ImageView and Buttons\n private lateinit var imageView: ImageView\n private lateinit var blinkBTN: Button\n private lateinit var rotateBTN: Button\n private lateinit var fadeBTN: Button\n private lateinit var moveBTN: Button\n private lateinit var slideBTN: Button\n private lateinit var zoomBTN: Button\n private lateinit var stopBTN: Button override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main) // Initialize the ImageView and Buttons using their IDs\n imageView = findViewById(R.id.imageview)\n blinkBTN = findViewById(R.id.BTNblink)\n rotateBTN = findViewById(R.id.BTNrotate)\n fadeBTN = findViewById(R.id.BTNfade)\n moveBTN = findViewById(R.id.BTNmove)\n slideBTN = findViewById(R.id.BTNslide)\n zoomBTN = findViewById(R.id.BTNzoom)\n stopBTN = findViewById(R.id.BTNstop) // Set up click listeners for each button to start corresponding animations\n createAnimation(blinkBTN, R.anim.blink_animation)\n createAnimation(rotateBTN, R.anim.rotate_animation)\n createAnimation(fadeBTN, R.anim.fade_animation)\n createAnimation(moveBTN, R.anim.move_animation)\n createAnimation(slideBTN, R.anim.slide_animation)\n createAnimation(zoomBTN, R.anim.zoom_animation) // Set up click listener for stop button to clear any ongoing animation\n stopBTN.setOnClickListener {\n imageView.clearAnimation()\n }\n } // Function to set up an animation for a given view and animation resource ID\n private fun createAnimation(view: View, animationResId: Int) {\n view.setOnClickListener {\n // Load the animation from the specified resource ID\n val animation = AnimationUtils.loadAnimation(this, animationResId)\n // Start the animation on the ImageView\n imageView.startAnimation(animation)\n }\n }\n}Note: Drawables and strings can be found in the drawable folder and strings.xml file. Drawables can be found from the app > res > drawable.\nOutput:\nhttps://media.geeksforgeeks.org/wp-content/uploads/20201126131135/Screenrecorder-2020-11-26-12-51-05-314.mp4Note :To access the full android application using Pie chat check this repository:Animation in Android ApplicationClick Here to Learn How to Create Android Application",
"input": "",
"output": "id, 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."
},
{
"instruction": "id, 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.",
"input": "",
"output": "nto an Android ApplicationA 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"
},
{
"instruction": "nto an Android ApplicationA 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",
"input": "",
"output": "Google 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. "
},
{
"instruction": "Google 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. ",
"input": "",
"output": "droidSlider 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"
},
{
"instruction": "droidSlider 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",
"input": "",
"output": "tall Plugins in Android Studio?Android 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."
},
{
"instruction": "tall Plugins in Android Studio?Android 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.",
"input": "",
"output": "ndroid 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:"
},
{
"instruction": "ndroid 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:",
"input": "",
"output": "in Android?In 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"
},
{
"instruction": "in Android?In 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",
"input": "",
"output": "PlayerView Library in Android?If 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"
},
{
"instruction": "PlayerView Library in Android?If 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",
"input": "",
"output": "h App using Android StudioIn 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."
},
{
"instruction": "h App using Android StudioIn 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.",
"input": "",
"output": "Fundamentals for BeginnersAndroid 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"
},
{
"instruction": "Fundamentals for BeginnersAndroid 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",
"input": "",
"output": "Android 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:"
},
{
"instruction": "Android 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:",
"input": "",
"output": "droid App DevelopmentWith 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"
},
{
"instruction": "droid App DevelopmentWith 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",
"input": "",
"output": "with ExampleThe 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"
},
{
"instruction": "with ExampleThe 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",
"input": "",
"output": "roidThe 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"
},
{
"instruction": "roidThe 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",
"input": "",
"output": "itText in Android?EditText 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"
},
{
"instruction": "itText in Android?EditText 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",
"input": "",
"output": "sing Jetpack ComposeProgressBar 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"
},
{
"instruction": "sing Jetpack ComposeProgressBar 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",
"input": "",
"output": "routinesPrerequisite: 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."
},
{
"instruction": "routinesPrerequisite: 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.",
"input": "",
"output": "droid using Jetpack ComposeCircular 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:"
},
{
"instruction": "droid using Jetpack ComposeCircular 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:",
"input": "",
"output": "Android 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."
},
{
"instruction": "Android 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.",
"input": "",
"output": "h Dagger 2 in AndroidIf 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"
},
{
"instruction": "h Dagger 2 in AndroidIf 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",
"input": "",
"output": "oid App on Google Play Store?Nowadays 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."
},
{
"instruction": "oid App on Google Play Store?Nowadays 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.",
"input": "",
"output": " with ExampleA 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"
},
{
"instruction": " with ExampleA 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",
"input": "",
"output": "oid Device is in Dock State?A 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."
},
{
"instruction": "oid Device is in Dock State?A 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.",
"input": "",
"output": "ader Library in Android Apps?COIL 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:"
},
{
"instruction": "ader Library in Android Apps?COIL 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:",
"input": "",
"output": " AndroidWe 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"
},
{
"instruction": " AndroidWe 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",
"input": "",
"output": "id?Android 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}"
},
{
"instruction": "id?Android 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}",
"input": "",
"output": "lculator app using Android Studio?Pre-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"
},
{
"instruction": "lculator app using Android Studio?Pre-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",
"input": "",
"output": "g Jetpack ComposeEditText 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:"
},
{
"instruction": "g Jetpack ComposeEditText 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:",
"input": "",
"output": "endar View appThis 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:"
},
{
"instruction": "endar View appThis 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:",
"input": "",
"output": " KotlinIn 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"
},
{
"instruction": " KotlinIn 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",
"input": "",
"output": " That Every Android Developer Should KnowAndroid 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."
},
{
"instruction": " That Every Android Developer Should KnowAndroid 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.",
"input": "",
"output": "ashlight/TorchLight Android App?All 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"
},
{
"instruction": "ashlight/TorchLight Android App?All 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",
"input": "",
"output": "g Firebase in AndroidFirebase 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} "
},
{
"instruction": "g Firebase in AndroidFirebase 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} ",
"input": "",
"output": "id with ExampleAn 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."
},
{
"instruction": "id with ExampleAn 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.",
"input": "",
"output": "roidState 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"
},
{
"instruction": "roidState 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",
"input": "",
"output": "tro Slider in Android using Firebase Firestore?We 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"
},
{
"instruction": "tro Slider in Android using Firebase Firestore?We 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",
"input": "",
"output": " Google Maps in Android?We 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"
},
{
"instruction": " Google Maps in Android?We 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",
"input": "",
"output": " in an Android ApplicationToggleButton 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"
},
{
"instruction": " in an Android ApplicationToggleButton 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",
"input": "",
"output": "using Volley LibraryJSON 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"
},
{
"instruction": "using Volley LibraryJSON 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",
"input": "",
"output": "droid 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:"
},
{
"instruction": "droid 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:",
"input": "",
"output": "er in Android with ExampleHere, 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"
},
{
"instruction": "er in Android with ExampleHere, 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",
"input": "",
"output": "se with Operations in Android with ExamplesFirebase 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:"
},
{
"instruction": "se with Operations in Android with ExamplesFirebase 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:",
"input": "",
"output": "F Viewer in Android with Firebase?If 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"
},
{
"instruction": "F Viewer in Android with Firebase?If 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",
"input": "",
"output": "ect in Android Studio Canary Version with Jetpack Compose?Jetpack 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."
},
{
"instruction": "ect in Android Studio Canary Version with Jetpack Compose?Jetpack 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.",
"input": "",
"output": "n Android with ExampleAndroid 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"
},
{
"instruction": "n Android with ExampleAndroid 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",
"input": "",
"output": "m Like Custom RecyclerView in Android?We 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"
},
{
"instruction": "m Like Custom RecyclerView in Android?We 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",
"input": "",
"output": "Like Custom RecyclerView in Android?We 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"
},
{
"instruction": "Like Custom RecyclerView in Android?We 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",
"input": "",
"output": "nd MVVM Architecture Pattern in AndroidDeveloping 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."
},
{
"instruction": "nd MVVM Architecture Pattern in AndroidDeveloping 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.",
"input": "",
"output": "d Grid in Android With ExampleGridView: 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"
},
{
"instruction": "d Grid in Android With ExampleGridView: 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",
"input": "",
"output": "JSON (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"
},
{
"instruction": "JSON (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",
"input": "",
"output": "KotlinIn 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"
},
{
"instruction": "KotlinIn 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",
"input": "",
"output": "in Android Using Kotlin?In 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."
},
{
"instruction": "in Android Using Kotlin?In 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.",
"input": "",
"output": "s in Android with ExampleViewPager 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"
},
{
"instruction": "s in Android with ExampleViewPager 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",
"input": "",
"output": "n 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"
},
{
"instruction": "n 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",
"input": "",
"output": " AndroidSnackbar 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"
},
{
"instruction": " AndroidSnackbar 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",
"input": "",
"output": "\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."
},
{
"instruction": "\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.",
"input": "",
"output": " Tracker Android AppThe 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:"
},
{
"instruction": " Tracker Android AppThe 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:",
"input": "",
"output": "oidAndroid 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"
},
{
"instruction": "oidAndroid 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",
"input": "",
"output": "oid with ExampleNestedScrollView 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"
},
{
"instruction": "oid with ExampleNestedScrollView 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",
"input": "",
"output": "m the Firebase Realtime Database in Android?Firebase 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"
},
{
"instruction": "m the Firebase Realtime Database in Android?Firebase 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",
"input": "",
"output": "m Out in AndroidZoom 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"
},
{
"instruction": "m Out in AndroidZoom 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",
"input": "",
"output": "oidConstraintLayout 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"
},
{
"instruction": "oidConstraintLayout 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",
"input": "",
"output": "gn EditText in Android with ExamplePrerequisite: 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"
},
{
"instruction": "gn EditText in Android with ExamplePrerequisite: 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",
"input": "",
"output": " with ExampleNotification 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"
},
{
"instruction": " with ExampleNotification 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",
"input": "",
"output": "Material Design Date Picker in AndroidAs 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"
},
{
"instruction": "Material Design Date Picker in AndroidAs 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",
"input": "",
"output": "ker in AndroidMaterial 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."
},
{
"instruction": "ker in AndroidMaterial 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.",
"input": "",
"output": "ePicker in Android using SnapTimePickerAndroid 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."
},
{
"instruction": "ePicker in Android using SnapTimePickerAndroid 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.",
"input": "",
"output": "tes App in Android?Notes 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"
},
{
"instruction": "tes App in Android?Notes 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",
"input": "",
"output": "ndroid with ExamplesScreen 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 "
},
{
"instruction": "ndroid with ExamplesScreen 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 ",
"input": "",
"output": "k Audience Network (FAN) Interstitial Ads in Android?In 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"
},
{
"instruction": "k Audience Network (FAN) Interstitial Ads in Android?In 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",
"input": "",
"output": "n Android?APK 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"
},
{
"instruction": "n Android?APK 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",
"input": "",
"output": "gmented Reality Android App?Augmented 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."
},
{
"instruction": "gmented Reality Android App?Augmented 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.",
"input": "",
"output": "droidWe 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"
},
{
"instruction": "droidWe 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",
"input": "",
"output": "Audio Player in Android with Firebase Realtime Database?Many 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"
},
{
"instruction": "Audio Player in Android with Firebase Realtime Database?Many 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",
"input": "",
"output": "ification Containing a Picture in AndroidNotification 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"
},
{
"instruction": "ification Containing a Picture in AndroidNotification 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",
"input": "",
"output": "lertDialog in Android using Firebase Firestore?Dynamic 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"
},
{
"instruction": "lertDialog in Android using Firebase Firestore?Dynamic 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",
"input": "",
"output": "AndroidNowadays 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."
},
{
"instruction": "AndroidNowadays 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.",
"input": "",
"output": "using Jetpack ComposeRadioButtons 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"
},
{
"instruction": "using Jetpack ComposeRadioButtons 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",
"input": "",
"output": " JavaThe 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"
},
{
"instruction": " JavaThe 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",
"input": "",
"output": "es in AndroidActivity 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."
},
{
"instruction": "es in AndroidActivity 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.",
"input": "",
"output": "oidSnackBars 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"
},
{
"instruction": "oidSnackBars 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",
"input": "",
"output": "id using Java with ExamplesWidget 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."
},
{
"instruction": "id using Java with ExamplesWidget 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.",
"input": "",
"output": "th Rounded Corner in Android?TextView 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:"
},
{
"instruction": "th Rounded Corner in Android?TextView 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:",
"input": "",
"output": "ialog Box in Android?Alert 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:"
},
{
"instruction": "ialog Box in Android?Alert 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:",
"input": "",
"output": "n Emulator and Add it\u2019s Plugin to Android Studio?Genymotion 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."
},
{
"instruction": "n Emulator and Add it\u2019s Plugin to Android Studio?Genymotion 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.",
"input": "",
"output": "yclerView in Android with ExampleThe 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"
},
{
"instruction": "yclerView in Android with ExampleThe 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",
"input": "",
"output": "stView in Android using Firebase Firestore?ListView 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"
},
{
"instruction": "stView in Android using Firebase Firestore?ListView 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",
"input": "",
"output": " ApplicationThere 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"
},
{
"instruction": " ApplicationThere 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",
"input": "",
"output": "FAB) in Android with ExampleThe 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."
},
{
"instruction": "FAB) in Android with ExampleThe 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.",
"input": "",
"output": "roid 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"
},
{
"instruction": "roid 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",
"input": "",
"output": " in AndroidDate 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:"
},
{
"instruction": " in AndroidDate 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:",
"input": "",
"output": "ndroid Development SkillsAndroid 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"
},
{
"instruction": "ndroid Development SkillsAndroid 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",
"input": "",
"output": " Use it in Android with Examples?Pre-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:"
},
{
"instruction": " Use it in Android with Examples?Pre-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:",
"input": "",
"output": "with ExamplesParticleView 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"
},
{
"instruction": "with ExamplesParticleView 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",
"input": "",
"output": "in Android with ExampleMaterial 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."
},
{
"instruction": "in Android with ExampleMaterial 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.",
"input": "",
"output": "lertDialog in Android?Sometimes 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"
},
{
"instruction": "lertDialog in Android?Sometimes 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",
"input": "",
"output": " JSON Array in Android using Volley Library?In 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"
},
{
"instruction": " JSON Array in Android using Volley Library?In 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",
"input": "",
"output": " to Kotlin Code in Android Studio?In 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."
},
{
"instruction": " to Kotlin Code in Android Studio?In 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.",
"input": "",
"output": "oader Library in Android Apps?Glide, 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);"
},
{
"instruction": "oader Library in Android Apps?Glide, 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);",
"input": "",
"output": "al Design EditText in AndroidIn 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"
},
{
"instruction": "al Design EditText in AndroidIn 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",
"input": "",
"output": "for Using Google Maps in Android?For 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"
},
{
"instruction": "for Using Google Maps in Android?For 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",
"input": "",
"output": "Firebase 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."
},
{
"instruction": "Firebase 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.",
"input": "",
"output": " Oreo (8+)Android 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: "
},
{
"instruction": " Oreo (8+)Android 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: ",
"input": "",
"output": "educe APK Size in Android?App 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."
},
{
"instruction": "educe APK Size in Android?App 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.",
"input": "",
"output": "onfiguration Changed in Android using Bundles?In 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"
},
{
"instruction": "onfiguration Changed in Android using Bundles?In 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",
"input": "",
"output": " with ExamplesShimmerLayout 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"
},
{
"instruction": " with ExamplesShimmerLayout 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",
"input": "",
"output": "\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."
},
{
"instruction": "\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.",
"input": "",
"output": "udio PluginsAndroid 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"
},
{
"instruction": "udio PluginsAndroid 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",
"input": "",
"output": "ng Jetpack ComposeImages, 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:"
},
{
"instruction": "ng Jetpack ComposeImages, 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:",
"input": "",
"output": "ard and R8 in AndroidProguard 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"
},
{
"instruction": "ard and R8 in AndroidProguard 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",
"input": "",
"output": "id using Java with ExamplesWidget 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:"
},
{
"instruction": "id using Java with ExamplesWidget 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:",
"input": "",
"output": " SharedPreferences in Android?SharedPreferences 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"
},
{
"instruction": " SharedPreferences in Android?SharedPreferences 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",
"input": "",
"output": "A 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."
},
{
"instruction": "A 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.",
"input": "",
"output": " Buttons in Android with different shapes and colorsA 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:"
},
{
"instruction": " Buttons in Android with different shapes and colorsA 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:",
"input": "",
"output": " ExampleServices 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"
},
{
"instruction": " ExampleServices 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",
"input": "",
"output": "dIn 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"
},
{
"instruction": "dIn 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",
"input": "",
"output": "idX and Android Support LibrariesSupport 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."
},
{
"instruction": "idX and Android Support LibrariesSupport 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.",
"input": "",
"output": "derThe 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]."
},
{
"instruction": "derThe 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].",
"input": "",
"output": " JetpackAndroid 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}"
},
{
"instruction": " JetpackAndroid 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}",
"input": "",
"output": "dWave 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"
},
{
"instruction": "dWave 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",
"input": "",
"output": " AndroidPreference 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."
},
{
"instruction": " AndroidPreference 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.",
"input": "",
"output": "leItemSelection in AndroidIn 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"
},
{
"instruction": "leItemSelection in AndroidIn 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",
"input": "",
"output": "n CoroutinesPrerequisite: 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."
},
{
"instruction": "n CoroutinesPrerequisite: 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.",
"input": "",
"output": "e in AndroidJetpack 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().."
},
{
"instruction": "e in AndroidJetpack 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()..",
"input": "",
"output": "ingBarRatingBar 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:"
},
{
"instruction": "ingBarRatingBar 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:",
"input": "",
"output": "Android 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"
},
{
"instruction": "Android 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",
"input": "",
"output": "e Between two Locations in Android?We 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"
},
{
"instruction": "e Between two Locations in Android?We 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",
"input": "",
"output": "ypes of Bars Available in Android?Android 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."
},
{
"instruction": "ypes of Bars Available in Android?Android 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.",
"input": "",
"output": "droid with ExampleStaggeredGridLayout 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