1-View What is Android View? A View is a simple building block of a user interface. It is a small rectangular box that can be TextView, EditText, or even a button. It occupies the area on the screen in a rectangular area and is responsible for drawing and event handling. View is a superclass of all the graphical user interface components. Why and How to use the View in Android? Now you might be thinking what is the use of a View. So, the use of a view is to draw content on the screen of the user’s Android device. A view can be easily implemented in an Application using the java code. Its creation is more easy in the XML layout file of the project. Like, the project for hello world that we had made initially View is the fundamental building block of the User Interface, and It is a small rectangular box that answer to user inputs. Likewise, View is the base class for all User interface widgets. If we want to give an example about the View class, they can be listed as follows. TextView EditText Button Image Button Date Picker RadioButton CheckBox buttons Image View Okey Then, What is the ViewGroup? ViewGroup is a invisible container that include all Views in it. It is base class for layouts that holds all Views and determine(ViewGroup.LayoutParams) their properties. If we want to give an example about the ViewGroup class, they can be listed as follows. Base class as ViewGroup LinearLayout RelativeLayout FrameLayout TableLayout CoordinatorLayout ConstraintLayout Layout Attributes[common Attributes] Each layout has a set of attributes which define the visual properties of that layout. There are few common attributes among all the layouts and their are other attributes which are specific to that layout. Following are common attributes and will be applied to all the layouts: Sr.No Attribute & Description 1 android:id This is the ID which uniquely identifies the view. 2 android:layout_width This is the width of the layout. 3 android:layout_height This is the height of the layout 4 android:layout_marginTop This is the extra space on the top side of the layout. 5 android:layout_marginBottom This is the extra space on the bottom side of the layout. 6 android:layout_marginLeft This is the extra space on the left side of the layout. 7 android:layout_marginRight This is the extra space on the right side of the layout. 8 android:layout_gravity This specifies how child Views are positioned. 9 android:layout_weight This specifies how much of the extra space in the layout should be allocated to the View. 10 android:layout_x This specifies the x-coordinate of the layout. 11 android:layout_y This specifies the y-coordinate of the layout. 12 android:layout_width This is the width of the layout. 13 android:paddingLeft This is the left padding filled for the layout. 14 android:paddingRight This is the right padding filled for the layout. 15 android:paddingTop This is the top padding filled for the layout. 16 android:paddingBottom This is the bottom padding filled for the layout. Gravity attribute plays important role in positioning the view object and it can take one or more (separated by '|') of the following constant values. Constant Value Description top 0x30 Push object to the top of its container, not changing its size. bottom 0x50 Push object to the bottom of its container, not changing its size. left 0x03 Push object to the left of its container, not changing its size. right 0x05 Push object to the right of its container, not changing its size. center_vertical 0x10 Place object in the vertical center of its container, not changing its size. fill_vertical 0x70 Grow the vertical size of the object if needed so it completely fills its container. center_horizontal 0x01 Place object in the horizontal center of its container, not changing its size. fill_horizontal 0x07 Grow the horizontal size of the object if needed so it completely fills its container. center 0x11 Place the object in the center of its container in both the vertical and horizontal axis, not changing its size. fill 0x77 Grow the horizontal and vertical size of the object if needed so it completely fills its container. 0x80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its container's bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges. clip_horizontal 0x08 Additional option that can be set to have the left and/or right edges of the child clipped to its container's bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges. start 0x00800003 Push object to the beginning of its container, not changing its size. end 0x00800005 Push object to the end of its container, not changing its size. clip_vertical 1. Linear Layout We use this layout to place the elements in a linear manner. A Linear manner means one element per line. This layout creates various kinds of forms on Android. In this, arrangement of the elements is in a top to bottom manner. This can have two orientations: a. Vertical Orientation – It is shown above where the widgets such as TextViews, and all in a vertical manner. b. Horizontal Orientation – It is shown above where the widgets such as TextViews, and all in a horizontal manner. Relative Layout The relative layout is used to arrange the child views in a proper order which means arranging the child objects relative to each other. Generally, if we create an application using a linear layout that consists of 5 buttons. Even if we specify weight and gravity properties they will not be relatively arranged. To arrange them in a proper order we need to use the relative layout. To arrange them we need some advanced properties. Basically, we use layout_width, layout_height, layout_text properties while creating an application using the linear layout. But we need some more advanced properties which are supported by relative layout. There are so many properties that are supported by relative layout. some of the most used properties are listed below layout_alignParentTop layout_alignParentBottom layout_alignParentRight layout_alignParentLeft layout_centerHorozontal layout_centerVertical layout_above layout_below Table Layout Android TableLayout going to be arranged groups of views into rows and columns. You will use the <TableRow> element to build a row in the table. Each row has zero or more cells; each cell can hold one View object. TableLayout containers do not display border lines for their rows, columns, or cells. TableLayout Attributes Sr.No. Attribute & Description 1 android:id This is the ID which uniquely identifies the layout. 2 android:collapseColumns This specifies the zero-based index of the columns to collapse. The column indices must be separated by a comma: 1, 2, 5. 3 android:shrinkColumns The zero-based index of the columns to shrink. The column indices must be separated by a comma: 1, 2, 5. 4 android:stretchColumns The zero-based index of the columns to stretch. The column indices must be separated by a comma: 1, 2, 5. FrameLayout Android 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’s views and control their positions only by using gravity attributes in FrameLayout. XML attributes: android:foregroundGravity Defines the gravity to apply to the foreground drawable. The gravity defaults to fill. Must be one or more (separated by '|') of the following constant values. Constant Value Description bottom 50 Push object to the bottom of its container, not changing its size. center 11 Place the object in the center of its container in both the vertical and horizontal axis, not changing its center_horizontal 1 Place object in the horizontal center of its container, not changing its size. center_vertical Place object in the vertical center of its container, not changing its size. 10 clip_horizontal 8 Additional option that can be set to have the left and/or right edges of the child clipped to its contain be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the l clip both edges. clip_vertical 80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its conta will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will cl will clip both edges. fill 77 Grow the horizontal and vertical size of the object if needed so it completely fills its container. fill_horizontal 7 Grow the horizontal size of the object if needed so it completely fills its container. fill_vertical 70 Grow the vertical size of the object if needed so it completely fills its container. left 3 Push object to the left of its container, not changing its size. right 5 Push object to the right of its container, not changing its size. top 30 Push object to the top of its container, not changing its size. Defines the gravity to apply to the foreground drawable. The gravity defaults to fill. Must be one or more (separated by '|') of the following constant values. Constant Value Description bottom 50 Push object to the bottom of its container, not changing its size. center 11 Place the object in the center of its container in both the vertical and horizontal axis, not changing center_horizontal 1 Place object in the horizontal center of its container, not changing its size. center_vertical 10 Place object in the vertical center of its container, not changing its size. clip_horizontal 8 Additional option that can be set to have the left and/or right edges of the child clipped to its conta will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip t will clip both edges. clip_vertical 80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its co will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will cl neither will clip both edges. fill 77 Grow the horizontal and vertical size of the object if needed so it completely fills its container. fill_horizontal 7 Grow the horizontal size of the object if needed so it completely fills its container. fill_vertical 70 Grow the vertical size of the object if needed so it completely fills its container. left 3 Push object to the left of its container, not changing its size. right 5 Push object to the right of its container, not changing its size. top 30 Push object to the top of its container, not changing its size. ConstraintLayout ConstraintLayout is similar to that of other View Groups which we have seen in Android such as RelativeLayout, LinearLayout, and many more. Important Attributes of ConstraintLayout :Attributes Description android:id This is used to give a unique id to the layout. app:layout_constraintBottom_toBottomOf This is used to constrain the view with respect to the bottom position. app:layout_constraintLeft_toLeftOf This attribute is used to constrain the view with respect to the left position. app:layout_constraintRight_toRightOf This attribute is used to constrain the view with respect to the right position. app:layout_constraintTop_toTopOf This attribute is used to constrain the view with respect to the top position. Advantages of using ConstraintLayout in Android ConstraintLayout 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 used in our app. Disadvantages of using ConstraintLayout When 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. How ConstraintLayout differs from Linear Layout? With the help of ConstraintLayout, we can position our UI components in any sort of order whether it may be horizontal or vertical. But in the case of Linear Layout, we can only arrange our UI components either in a horizontal or in a vertical manner. Linear Layout provides usability with which we can equally divide all the UI components in a horizontal or vertical manner using weight sum but in Constraint Layout, we have to arrange this UI component manually. In 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, but in the case of Constraint layout if the UI component is not Constrained then the UI will not look the same as that of in design editor. How ConstraintLayout differs from RelativeLayout? In Constraint Layout, we have to add constraints to the view on all four sides whereas in Relative Layout we can simply align our UI component relative to its ID using the ids of UI components. In 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, but in the case of Constraint layout if the UI component is not Constrained then the UI will not look same as that of in design editor. How Constraint Layout differs from Grid Layout? In Grid Layout the UI components are only arranged in Grid Manner and we cannot arrange the UI components according to requirement, whereas in Constraint Layout we can align UI components according to the requirement. In 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, but in the case of Constraint layout if the UI component is not Constrained then the UI will not look same as that of in design editor. Android AlertDialog Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can be used to interrupt and ask the user about his/her choice to continue or discontinue. Android AlertDialog is composed of three regions: title, content area and action buttons. Android AlertDialog is the subclass of Dialog class. Methods of AlertDialog class Method Description public AlertDialog.Builder setTitle(CharSequence) This method is used to set the title of AlertDialog. public setMessage(CharSequence) This method is used to set the message for AlertDialog. AlertDialog.Builder public AlertDialog.Builder setIcon(int) This method is used to set the icon over AlertDialog. Android AlertDialog Example activity_main.xml You can have multiple components, here we are having only a textview. File: activity_main.xml 1. <?xml version="1.0" encoding="utf-8"?> 2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.co m/apk/res/android" 3. xmlns:app="http://schemas.android.com/apk/res-auto" 4. xmlns:tools="http://schemas.android.com/tools" 5. android:layout_width="match_parent" 6. android:layout_height="match_parent" 7. tools:context="example.javatpoint.com.alertdialog.MainActivity"> 8. 9. <Button 10. android:layout_width="wrap_content" 11. android:layout_height="wrap_content" 12. android:id="@+id/button" 13. android:text="Close app" 14. app:layout_constraintBottom_toBottomOf="parent" 15. app:layout_constraintLeft_toLeftOf="parent" 16. app:layout_constraintRight_toRightOf="parent" 17. app:layout_constraintTop_toTopOf="parent" /> 18. 19. </android.support.constraint.ConstraintLayout> strings.xml Optionally, you can store the dialog message and title in the strings.xml file. File: strings.xml 1. <resources> 2. <string name="app_name">AlertDialog</string> 3. <string name="dialog_message">Welcome to Alert Dialog</string> 4. <string name="dialog_title">Javatpoint Alert Dialog</string> 5. </resources> Activity class Let's write the code to create and show the AlertDialog. File: MainActivity.java 1. package example.javatpoint.com.alertdialog; 2. 3. import android.content.DialogInterface; 4. import android.support.v7.app.AppCompatActivity; 5. import android.os.Bundle; 6. import android.view.View; 7. import android.widget.Button; 8. import android.app.AlertDialog; 9. import android.widget.Toast; 10. 11. public class MainActivity extends AppCompatActivity { 12. Button closeButton; 13. AlertDialog.Builder builder; 14. @Override 15. protected void onCreate(Bundle savedInstanceState) { 16. super.onCreate(savedInstanceState); 17. setContentView(R.layout.activity_main); 18. 19. closeButton = (Button) findViewById(R.id.button); 20. builder = new AlertDialog.Builder(this); 21. closeButton.setOnClickListener(new View.OnClickListener() { 22. @Override 23. public void onClick(View v) { 24. 25. //Uncomment the below code to Set the message and title from the strings.xml file 26. builder.setMessage(R.string.dialog_message) .setTitle(R.string.dialog_title); 27. 28. //Setting message manually and performing action on button click 29. builder.setMessage("Do you want to close this application ?") 30. .setCancelable(false) 31. .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 32. public void onClick(DialogInterface dialog, int id) { 33. finish(); Toast.makeText(getApplicationContext(),"you choose yes action for alertbox", 34. Toast.LENGTH_SHORT).show(); 35. } 36. }) 37. .setNegativeButton("No", new DialogInterface.OnClickListener() { 38. public void onClick(DialogInterface dialog, int id) { 39. // Action for 'NO' Button 40. dialog.cancel(); Toast.makeText(getApplicationContext(),"you choose no action for alertbox", 41. Toast.LENGTH_SHORT).show(); 42. } 43. }); 44. //Creating dialog box 45. AlertDialog alert = builder.create(); 46. //Setting the title manually 47. alert.setTitle("AlertDialogExample"); 48. alert.show(); 49. } 50. 51. 52. } }); } Drawing and Working with Animation 1.Frame By Frame Animation It’s been said that Animation is the state of being alive. Something that gives you an illusion. In mobile application development too this has got its own significance. In Android Frame Animation, you will be swapping frames repeatedly, so that it appears continuous to the human eye and we feel that it is animated. Frame is referred to an image. So to implement frame by frame animation in android, one needs to have set of images, which describes a motion. In Android Frame Animation, you will be swapping frames repeatedly, so that it appears continuous to the human eye and we feel that it is animated. Frame is referred to an image. So to implement frame by frame animation in android, one needs to have set of images, which describes a motion. AnimationDrawable public class AnimationDrawable extends DrawableContainer implements Runnable, Animatable java.lang.Object ↳ android.graphics.drawable.Drawable ↳ android.graphics.drawable.DrawableContainer ↳ android.graphics.drawable.AnimationDrawable XML attributes android:drawable Reference to a drawable resource to use for the frame. android:duration Amount of time (in milliseconds) to display this frame. android:oneshot If true, the animation will only run a single time and then stop. android:variablePadding If true, allows the drawable's padding to change based on the current state that is s android:visible Provides initial visibility state of the drawable; the default value is false. Note: Gives suitable example :- example of duckies 2. Tween Animation Definition of Animation:- Animation is the process of creating motion and shape change Tween Animation takes some parameters such as start value , end value, size , time duration , rotation angle e.t.c and perform the required animation on that object. It can be applied to any type of object. So in order to use this, android has provided us a class called Animation. In order to perform animation in android, we are going to call a static function loadAnimation() of the class AnimationUtils. We are going to receive the result in an instance of Animation Object. Its syntax is as follows − Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.myanimation); Note the second parameter. It is the name of the our animation xml file. You have to create a new folder called anim under res directory and make an xml file under anim folder. This animation class has many useful functions which are listed below − Sr.No Method & Description 1 start() This method starts the animation. 2 setDuration(long duration) This method sets the duration of an animation. 3 getDuration() This method gets the duration which is set by above method 4 end() This method ends the animation. 5 cancel() This method cancels the animation. In order to apply this animation to an object , we will just call the startAnimation() method of the object. Its syntax is − ImageView image1 = (ImageView)findViewById(R.id.imageView1); image.startAnimation(animation); Unit 4 :- Database Connectivity Using and Content Provider SQLite Storage System to Store Data in Android (5marks with one example) We employ some form of storage in Android to retain the data permanently (until destroyed) for future reference. Android Storage System is the name given to these storage systems. Internal storage, external storage, shared preferences, database, and shared storage are some of the storage options offered by Android. However, many users are unsure when to use which storage. So, in this blog, we’ll discover when to use which storage unit. Let’s begin with the internal storage system. We create several variables for storing various data that are used in an Android application when developing it. For example, we can utilize a variable to save data from a remote database and then use that variable throughout the application. These variables, however, are in-app storage, which means they will be visible to you while the app is operating. When the application is ended, all of the data in the variable is wiped, and you are left with nothing. Those variables will be created again when you start the application, and new values can be saved in those variables. 1. Storage on the Inside When you install an app on your phone, the Android operating system will give you some form of secret internal storage where the app can store its private data. No other application has access to this information. When you uninstall an application, all of the data associated with it is also removed. To save a file to the internal storage, you must first obtain it from the internal directory. You can do this by calling the getFilesDir() or getCacheDir() methods. The getFilesDir() method returns the absolute path to the directory where files are created on the filesystem. getCacheDir() returns the absolute path to the filesystem’s application-specific cache directory. When Should Internal Storage Be Used? The internal storage can be used when you need some confidential data for your application. Another thing to keep in mind is that if your app is storing data that may be utilized by other apps, you should avoid using internal storage since when you remove the app, all of your data will be gone, and other apps will never have access to that data. For instance, if your app is downloading a pdf or storing an image or video that might be used by other apps, you shouldn’t use internal storage. 2. External Hard Drives Most Android devices have relatively low internal storage. As a result, we keep our data on an external storage device. These storage units are accessible to everyone, which means they can be accessed by all of your device’s applications. You can also access the storage by connecting your mobile device to a computer. You must obtain the READ EXTERNAL STORAGE permission from the user in order to gain access to the external storage. As a result, any application with this permission has access to your app’s data. When is it appropriate to use external storage? You can use external storage if the data that your application stores can be used by other applications. Additionally, if the file stored by your application is huge, such as a video, you can save it to external storage. You can use external storage to keep the data even after uninstalling the application. 3. Using the Shared Preferences You can use the shared preferences if you only have a little amount of data to keep and don’t want to use the internal storage. Shared Preferences are used to store data in a key-value format, which means you’ll have one key and the associated data or value will be stored depending on that key. The data saved in the shared preferences will remain with the application until you delete it from your phone. All shared preferences will be deleted from the device if you uninstall the application. When Should Shared Preferences Be Used? You can utilize the shared preference in your application when the data you want to store is relatively little. It’s not a good idea to save more than 100 kilobytes of data in shared preferences. In addition, if you wish to keep tiny and private data, you can use Android’s shared preferences. 4. Using Android Database Databases are collections of data that are organized and saved for future use. Using a Database Management System, you can store any type of data in your database. All you have to do is establish the database and use one query to perform all of the operations, such as insertion, deletion, and searching. The query will be passed to the database, which will return the desired output. In Android, an SQLite database is an example of a database. When should you utilize a database? A database is useful when you need to keep track of structured data. A database can hold any type of information. So, if your data is large and you want to retrieve it quickly, you can use a database and store it in a structured style. Data storage in Android (2,3 marks) Data storage is a critical aspect of Android application development. Android provides developers with several options for storing data, including: Shared Preferences are a simple key-value storage mechanism that allows developers to store small amounts of data, such as user preferences, settings, or other configuration data. Internal Storage: Internal storage is a private file system that is only accessible to the application that created it. Internal storage can be used to store application-specific data, such as cached images, downloaded files, Shared Preferences: or user data. External Storage: External storage is a public file system that can be accessed by any application. External storage can be used to store large files, such as media files or documents, that need to be shared between applications or persisted across app updates. SQLite Database: SQLite is a powerful relational database management system that is integrated into the Android platform. SQLite can be used to store large amounts of structured data, such as user data or application settings. Content Providers: Content Providers are a powerful data storage mechanism that allows applications to share data with other applications. Content Providers can be used to store and retrieve data in a centralized location, such as a SQLite database. Cloud Storage: Cloud storage services, such as Google Drive or Amazon S3, can be used to store and synchronize data across devices and platforms. The choice of data storage mechanism depends on the type and amount of data to be stored, as well as the specific needs of the application. By choosing the appropriate data storage mechanism, developers can ensure that their applications are efficient, secure, and scalable Example of Internal Storage:- FileExample