Unit 3 Exploring User Interface Screen Elements
Unit 3 Exploring User Interface Screen Elements
3.1 Introducing Android Views, Layouts, TextView, Buttons, Check Boxes, Radio Groups, Indicators, SeekBar,
Context Menus, User Events, Styles and Themes, Dates and Times, Retrieving Data.
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.
The Android SDK has a Java package name android.view. This package contains a number of interfaces and
classes related to drawing on the screen. However, when we refer to the View object, we actually refer to onl y
one of the classes within this package: the android.view.View class.
View is the basic building block of UI (User Interface) in android. View refers to the android.view.View class,
which is the super class for all the GUI components like TextView, ImageView, Button etc. View class extends
Object class and Implements Drawable.Callback, KeyEvent.Callback and AccessibilityEventSource.
The question that might be bothering you would be, what can be the size of this rectangle?
The answer is either we can set it manually, by specifying the exact size (with proper units) or by using some
predefined values. These predefined values are match_parent and wrap_content. match_parent means it will
occupy the complete space available on the display of the device. Whereas, wrap_content means it will occupy
only that much space as required for its content to display.
ViewGroup
View Group is a subclass of the ViewClass and can be considered as a superclass of Layouts. It provides an
invisible co0ntainer to hold the views or layouts. ViewGroup instances and views work together as a container
for Layouts. To understand in simpler words it can be understood as a special view that can hold other views
that are often known as a child view.
A layout defines the structure for a user interface in your app, such as in an activity. All elements in the layout
are built using a hierarchy of View and ViewGroup objects. A View usually draws something the user can see
and interact with. Whereas a ViewGroup is an invisible container that defines the layout structure for View and
other ViewGroup objects.
One special type of control found within the android.widget package is called a layout. A layout control is still a
View object, but it doesn’t actually draw anything specific on the screen. Instead, it is a parent container for
organizing other controls (children). Layout controls determine how and where on the screen child controls are
drawn. Each type of layout control draws its children using particular rules. For instance, the LinearLayout
control draws its child controls in a single horizontal row or a single vertical column. Similarly, a TableLayout
control displays each child control in tabular format(in cells within specific rows and columns).
In “Designing User Interfaces with Layouts,” we organize various controls within layouts and other containers.
These special View controls, which are derived from the android.view.ViewGroup class, are useful only after
you understand the various display controls these containers can hold. By necessity, we use some of the layout
View objects within this chapter to illustrate how to use the controls previously mentioned.
Types of Layouts
Linear Layout
Relative Layout
Constraint Layout
Table Layout
Frame Layout
List View
Grid View
Absolute Layout
WebView
ScrollView
Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements
one by one either in a particular direction either horizontally or vertically based on the orientation
property.
Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of
child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the
top of the parent).
Layout params
This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may contain any
type of widgets such as buttons, labels, textboxes, and so on. Following is a simple example of XML file having
LinearLayout −
Once your layout has created, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below −
The following are the attributes for customizing a Layout while defining it:
Another thing that might now come to your mind must be, “what are the available types of view in Android that
we can use?”
For that, we’ll see all these types one by one as follows:
TextView
EditText
Button
Image Button
Date Picker
RadioButton
CheckBox buttons
Image View
A TextView displays text to the user and optionally allows them to edit it. A TextView is a complete text editor,
however the basic class is configured to not allow editing.
TextView Attributes
android:cursorVisible Makes the cursor visible (the default) or invisible. Default is false.
android:editable If set to true, specifies that this TextView has an input method.
android:fontFamily Font family (named by string) for the text.
android:gravity Specifies how to align the text by the view's x- and/or y-axis when the text is smaller
than the view.
android:hint Hint text to display when the text is empty.
android:inputType The type of data being placed in a text field. Phone, Date, Time, Number, Password
etc.
android:password Whether the characters of the field are displayed as password dots instead of
themselves. Possible value either "true" or "false".
android:phoneNumber If set, specifies that this TextView has a phone number input method. Possible value
either "true" or "false".
android:text Text to display.
android:textAllCaps Present the text in ALL CAPS. Possible value either "true" or "false".
android:textSize Size of the text. Recommended dimension type for text is "sp" for scaled-pixels
(example: 15sp).
Example
MainActivity.java
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text_id"
android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:textSize="50dp"/>
</RelativeLayout>
2).EditText
A EditText is an overlay over TextView that configures itself to be editable. It is the predefined subclass of
TextView that includes rich editing capabilities.
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.
Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility This controls the initial visibility of the view.
Example
activity_main.xml file –
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="18dp"
android:text="@string/example_edittext" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="@string/show_the_text" />
<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text" />
</RelativeLayout>
MainActivity.java file-
package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
3).Button:-
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.
Button Attributes
Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display
Button Example
Activity_main.xml
MainActivity.java
package com.example.exampleofbutton;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn_next(View view) {
Toast.makeText(this,"Next Button Clicked", Toast.LENGTH_SHORT).show();
}
Activity_main.xml
<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textviewname"
android:layout_marginTop="-249dp"
android:ems="10"
android:hint="Enter Your Name"
android:inputType="textPersonName"
android:padding="20dp"
android:textColor="#F44336" />
<Button
android:id="@+id/btnclickhere"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextName"
android:layout_marginTop="29dp"
android:padding="20dp"
android:text="ClickMe" />
<TextView
android:id="@+id/textviewname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="TextView" />
</RelativeLayout>
MainActivity.java
package com.example.exampleoftextview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
}
});
}
}
4). CheckBox:- Android CheckBox is a type of two state button either checked or unchecked.There can be
a lot of usage of checkboxes. For example, it can be used to know the hobby of the user, activate/deactivate
the specific action etc.Android CheckBox class is the subclass of CompoundButton class.
Method:-There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:
CheckBox Attributes
Example
MainActivity.java
package com.example.checkboxexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
CheckBox ch,ch1,ch2,ch3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch=(CheckBox)findViewById(R.id.checkBox);
ch1=(CheckBox)findViewById(R.id.checkBox3);
ch2=(CheckBox)findViewById(R.id.checkBox4);
ch3=(CheckBox)findViewById(R.id.checkBox5);
}
// This function is invoked when the button is pressed.
public void Check(View view) {
/* Finding CheckBox by its unique ID */
String msg="";
// Concatenation of the checked options in if
// isChecked() is used to check whether
// the CheckBox is in true state or not.
if(ch.isChecked())
msg = msg + " Painting ";
if(ch1.isChecked())
msg = msg + " Dancing ";
if(ch2.isChecked())
msg = msg + " Reading ";
if(ch3.isChecked())
msg = msg + " Surfing ";
// Toast is created to display the
// message using show() method.
Toast.makeText(this, msg+"Are Selected", Toast.LENGTH_LONG).show();
}
}
RadioButton is a two states button which is either checked or unchecked. If a single radio button is
unchecked, we can click it to make checked radio button. Once a radio button is checked, it cannot be
marked as unchecked by user.
RadioButton is generally used with RadioGroup. RadioGroup contains several radio buttons, marking one
radio button as checked makes all other radio buttons as unchecked.
Example
Activity_main.xml
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:textSize="22dp"
android:text="Single Radio Buttons"/>
<!-- Default RadioButtons -->
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="fill_parent"
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="20dp"
android:background="#B8B894" />
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:textSize="22dp"
android:text="Radio button inside RadioGroup" />
<!-- Customized RadioButtons -->
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioGroup">
<RadioButton
android:id="@+id/radioMale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Male"
android:layout_marginTop="10dp"
android:checked="false"
android:textSize="20dp" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Female"
android:layout_marginTop="20dp"
android:checked="false"
android:textSize="20dp" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected"
android:id="@+id/button"
MainActivity.java
package com.example.radiobuttondemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
Indicators
The Android SDK provides a number of controls that can be used to visually show some form of
information to the user. These indicator controls include progress bars, clocks, and other similar controls.
ProgressBars
Android ProgressBar is a graphical view indicator that shows some progress. Android progress bar displays
android:max : We can set the maximum value of the ProgressBar using this attribute. By default
the progress bar maximum value is 100
android:indeterminate : A boolean value is set depending on whether the time is determinate or
not. Setting this attribute to false would show the actual progress. Else if it’s set to true a cyclic
animation is displayed to show that progress is happening
android:minHeight : It’s used to set the height of the ProgressBar
android:minWidth : It’s used to set the width of the ProgressBar
android:progress : It’s used to set the number by which the progress bar value will be
incremented
style : By default the progress bar will be displayed as a spinning wheel. If we want it to be
displayed as a horizontal bar, we need to set the attribute as :
style=”?android:attr/progressBarStyleHorizontal”
Method
2). incrementProgressBy(int diff):-This method increments the progress bar by the difference of value
passed as a parameter.
4). setMax(int max):-This method sets the maximum value of the progress dialog.
5). setProgress(int value):-This method is used to update the progress dialog with some specific value.
6). show(Context context, CharSequence title, CharSequence message):-This is a static method, used to
display progress dialog.
Example
Activity_main.xml
Mainactivity.java
package com.example.textviewdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate progress bar and start button
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// visible the progress bar
simpleProgressBar.setVisibility(View.VISIBLE);
}
});
}
}
Android SeekBar is a type of ProgressBar. On touching the thumb on seekbar and dragging it to the right
or left, the current value of the progress changes. SeekBar is used for forwarding or backwarding the songs,
Video etc. In the setOnSeekBarChangeListener interface is used which provides three methods.
onProgressChanged: In this method progress is changed and then according to this change the
progress value can used in our logic.
onStartTrackingTouch: In this method when the user has started dragging, then this method will
be called automatically.
onStopTrackingTouch: In this method, when the user stops dragging, then this method will
called automatically.
Example
Activity_main.xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="180dp"
android:layout_marginBottom="460dp"
android:text="Example of Seekbar" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="372dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#0F0"/><!-- set green color in the background of seek bar-->
</RelativeLayout>
MainActivity.java
package com.example.seekbarexample;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Context menus:-
In Android, the context menu is like a floating menu and arises when the user has long
pressed or clicks on an item and is beneficial for implementing functions that define the specific content or
reference frame effect. The Android context menu is similar to the right-click menu in Windows or Linux.
In the Android system, the context menu provides actions that change a specific element or context frame in
the user interface and one can provide a context menu for any view. The context menu will not support any
object shortcuts and object icons. Note that we are going to implement this project using the Java language.
Example
Step 1: Create a New Project
Step 2: Working with the activity_main.xml file Open res -> Layout -> activity_main.xml and write the
following code. In this file add only a TextView to display a simple text.
Activity_main.xml
Step 3: Working with the Mainactivity.java file Open the app -> Java -> Package -> Mainactivity.java file.
In this step, add the code to show the ContextMenu. Whenever the app will start make a long click on a text
and display the number of options to select them for specific purposes.
MainActivity.java
package com.example.contextmenuexample;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Link those objects with their respective id's
// that we have given in .XML file
textView = (TextView) findViewById(R.id.textView);
relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);
// here you have to register a view for context menu
// you can register any view like listview, image view,
// textview, button etc
registerForContextMenu(textView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// you can set menu header with title icon etc
menu.setHeaderTitle("Choose a color");
// add menu items
menu.add(0, v.getId(), 0, "Yellow");
menu.add(0, v.getId(), 0, "Gray");
menu.add(0, v.getId(), 0, "Cyan");
}
// menu item select listener
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Yellow") {
relativeLayout.setBackgroundColor(Color.YELLOW);
} else if (item.getTitle() == "Gray") {
relativeLayout.setBackgroundColor(Color.GRAY);
} else if (item.getTitle() == "Cyan") {
relativeLayout.setBackgroundColor(Color.CYAN);
}
return true;
User Event
Events are a useful way to collect data about a user's interaction with interactive components of
Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as
a first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action
as per requirements.
Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by touching
the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by calling the View
class's InTouchMode() method.
Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This
indicates that it’s ready to accept input from the user.
● isFocusable() − it returns true or false
● isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be
focusable when using a hardware key but not when the device is in touch mode)
android:foucsUp="@=id/button_l"
onTouchEvent()
case TOUCH_UP:
Toast.makeText(this,"you have clicked up touch button",Toast.LENTH_LONG).show();
break;
case TOUCH_MOVE:
Toast.makeText(this,"you have clicked move touch button"Toast.LENTH_LONG).show();
break;
}
return super.onTouchEvent(event) ;
}
Activity_main.xml
MainActivity.java
package com.tutlane.inputeventsexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
A style resource defines the format and looks for a UI. A style can be applied to an individual View
(from within a layout file) or to an entire Activity or application (from within the manifest file).
Defining Styles
A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML
file resides under the res/values/ directory of your project and will have as the root node which is
mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension.
You can define multiple styles per file using tag as shown below –
Using Styles Once your style is defined, you can use it in your XML Layout file using style attribute as
follows –
<TextView
android:id="@+id/text_id"
style="@style/CustomFontStyle"
android:text="@string/hello_world" />
</LinearLayout>
Android Themes
Theme is a style that is applied to an entire activity or app, instead of an individual View like as mentioned
above. When we applied a style as a theme, the views in activity or app apply to the all style attributes that
supports. For example. If we apply TextviewStyle as a theme for an activity, then the text of all
the views in activity appears in the same style.
<color name="custom_theme_color">#b0b0ff</color>
<style name="CustomTheme" parent="Theme.AppCompat.Light">
<item name="android:windowBackground">@color/custom_theme_color</item>
<item name="android:colorBackground">@color/custom_theme_color</item>
</style>
To set a theme for a particular activity, open AndroidManifest.xml file and write the code like as shown
below
<activity android:theme="@android:style/CustomTheme">
In case, if we want to set the theme for all the activities in android application, open AndroidManifest.xml
file and write the code like as shown below.
<application android:theme="@android:style/CustomTheme">
In android, we can customize the application basic theme colors based on our requirements.
We can customize the application basic theme colors based on our requirements. Now we will see how to
use these styles and themes in android applications with examples.
Following is the example of defining a custom style for controls in LinearLayout to apply different styles
for controls in the android application.
Create a new android application using android studio and give names as StylesThemesExample. In case
if you are not aware of creating an app in android studio check this article Android Hello World App.
Now we need to define our styles in styles.xml file, for that open styles.xml file from \res\values folder
and write the code like as shown below.
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="TextviewStyle" parent="@android:style/Widget.TextView">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
If you observe above code, we defined a two styles (TextViewStyle, ButtonStyle) and we can apply these
styles for required controls in android application.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
If you observe above code we are referring our styles to required controls using style attribute.
Date 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’s 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.
Using Android Studio create an empty activity project. Refer to Android | How to Create/Start a
New Project in Android Studio?
The 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.
To implement the UI invoke the following code inside the activity_main.xml file.
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:text="Date and Time value in Long type :"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="64dp"
android:text="Date and Time formatted :"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dateTimeLongValue" />
<TextView
android:id="@+id/format2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format1" />
<TextView
android:id="@+id/format3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format2" />
<TextView
android:id="@+id/format4"
android:layout_width="wrap_content"
<TextView
android:id="@+id/format5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format4" />
<TextView
android:id="@+id/format6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format5" />
<TextView
android:id="@+id/format7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format6" />
</androidx.constraintlayout.widget.ConstraintLayout>
Understanding the way of formatting the date and time in Android using SimpleDateFormat
Firstly, 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.
The below table includes the characters to be used to generate the most used common pattern of
date and time.
ActivityMain.java
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;
// format type 2
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format2.setText(dateTime);
// format type 3
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aaa z");
// format type 4
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format4.setText(dateTime);
// format type 5
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format5.setText(dateTime);
// format type 6
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("E.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format6.setText(dateTime);
// format type 7
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("EEEE.LLLL.yyyy KK:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format7.setText(dateTime);
}
}
Retrieving Data
SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with
built in SQLite database implementation. SQLite supports all the relational database features. In order to
access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c
Database – Package
The main package is android.database.sqlite that contains the classes to manage your own databases
Database – Creation
In order to create a database you just need to call this method openOrCreateDatabase with your database
name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your
own object.
Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);
Database - Insertion
We can create tables or insert data into tables using the execSQL method defined in SQLiteDatabase class.
Database - Fetching
We can retrieve anything from the database using an object of the Cursor class. We will call a method of
this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move
For managing all the operations related to the database , a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database.
public DBHelper(){
super(context,DATABASE_NAME,null,1);