Mad Unit-Iii
Mad Unit-Iii
Basic views, Picker views, List view, Image view, Menus with views, Web view,
Saving and loading user preferences, persisting data to files, Creating and using
databases.
INTRODUCTION
It covers Basic Views like TextView, Button, and EditText as the building
blocks of UI, and introduces more interactive elements like Picker Views
(DatePicker, TimePicker) and ListView for displaying dynamic data. The unit
explores using ImageView for media, and WebView for embedding web
storage, ensuring apps retain data across sessions. The focus is on creating
Basic views in Android refer to the core UI components that allow you to
interact with the user. These views are the building blocks for creating Android
app interfaces. Let's look at some common basic views with examples:
1
TextView in Android
TextView is the most widely used view used to show pre-defined text on
display screen. This is a view which is not only used alone, but is also used
along with other Views as well, like when you are creating a form, where you
have EditText view, CheckBox view etc, then to mention the labels and other
SAMPLE CODE:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp"/>
TextView. EditText is used when you want to have a text field in your
application where user can enter any text. It can be either single line or multi-
line. Touching a text field place makes the field active, places a cursor and
SAMPLE CODE:
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name"/>
2
RadioButton View and CheckBox View in Android
When you are creating a form to accept user inputs in your android application,
and you have to list down a few options for the user to choose from, check boxes
So, the functional difference between, radio box and check box are that we use
radio box when out of multiple options only one can be chosen by the user, and
SAMPLE CODE:
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Agree to terms"/>
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"/>
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"/>
</RadioGroup>
3
Button View in Android
Button, as understood by its name, is a component which can be pressed or
SAMPLE CODE:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"/>
IMAGE VIEW
application.
IMAGEVIEW IN ANDROID
Therefore, any image that we want to display in the app should be placed under
the drawable folder. This folder can be found under app → res → drawable. To
insert an image, simply copy the image and then right click on drawable →
Paste.
4
SAMPLE CODE:
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/img_nature"/>
ImageButton in Android
ImageButton has the same property as ImageView. Only one feature is extra,
which is, images set through ImageButton are clickable, and actions can be
SAMPLE CODE:
<ImageButton
android:id="@+id/imgButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter"
android:src="@drawable/img_nature"/>
Attribute Description
5
A few more, commonly used attributes with ImageView
image is not able to entirely fill the ImageView, then background color is used
the image.
• CENTER: Places the image in center, but does not scale it.
• CENTER_INSIDE: This will place the image inside the container and the
edges of the image will not overlap with that of the container, the image
• FIT_END: Scale the image from the end of the container, i.e from the
• FIT_START: Scale the image from the start of the container, i.e from the
• FIT_XY: This will fill the complete container with the image. This
ratios.
• MATRIX: Used to scale the image using the image matrix when drawing.
6
Example Code:
MainActivity.java
package com.example.basicviews;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing Views
7
// Button Click Event
button.setOnClickListener(v -> {
if (selectedId != -1) {
gender = selectedRadioButton.getText().toString();
});
of AndroidX and is commonly used as the base class for activities in Android
applications.
• Toast in Android is a short popup message that appears on the screen for a
8
Eg: Toast.makeText(MainActivity.this, "Hello, Toast!",Toast.LENGTH_SHORT).show();
LISTVIEW IN ANDROID
ListView is used when you have to show items in a vertically scrolling
list. Best example of it is our device's Contact List. With ListView, user can
easily browse the information, while scrolling up and down. You can set
divider between every item and set its height and coloredg as per your UI
design.
feasible to manually create list items for the complete data, hence Android
provides us with special Adapter classes which can be used to supply data from
datasets to ListView. Following are some of the main attributes that are most
commonly used:
Below we have shown how you can add a ListView to your android app using
SAMPLE CODE:
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/black"
android:dividerHeight="1dp"/>
9
Adapter and Adapter View
Adapter and Adapter View are so popular, that every time you see any app
with a List of items or Grid of items, you can say for sure that it is using Adapter
Generally, when we create any List or Grid of data, we think we can use a loop
to iterate over the data and then set the data to create the list or grid.
But what if the data is a set of 1 million products. Then using a loop will not
only consume a lot of time, making the app slow, also it might end up eating
All these problems are solved by using Adapter and Adapter View.
Adapter View, is a View object, and can be used just like we use any other
interface widget. The only catch here is, that it needs an Adapter to provide
What is an Adapter?
An adapter acts like a bridge between a data source and the user interface. It
reads data from various data sources, coverts it into View objects and provide
The data source or dataset can be an Array object, a List object etc.
10
You can create your own Adapter class by extending the BaseAdapter class,
which is the parent class for all other adapter class. Android SDK also provides
An Adapter View can be used to display large sets of data efficiently in form
Interface, while keeping the memory and CPU usage very low and without any
noticeable lag. Different Adapters follow different strategies for this, but the
1. It only renders those View objects which are currently on-screen or are
about to some on-screen. Hence no matter how big your data set is, the
2. It also reuses the already created layout to populate data items as the user
Suppose you have a dataset, like a String array with the following contents.
11
Now, what does an Adapter do is that it takes the data from this array and
creates a View from this data and then, it gives this View to an AdapterView.
The AdapterView then displays the data in the way you want.
ArrayAdapter:
Syntax:
(android.R.layout.simple_list_item_1).
Note: Adapter is only responsible for taking the data from a data source and
converting it into View and then passing it to the AdapterView. Thus, it is used
Therefore, you can take the data from a database or an ArrayList or any other
data source and then, you can display that data in any arrangement.
Source Code:
package com.example.listview;
import android.os.Bundle;
import android.view.View;
12
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Reference to ListView
// Setting Adapter
android.R.layout.simple_list_item_1 items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.LENGTH_SHORT).show();
});
13
PICKER VIEW IN ANDROID
Android provides controls for the user to pick a time or pick a date as ready-
to-use dialogs. Each picker provides controls for selecting each part of the time
(hour, minute, AM/PM) or date (month, day, year). Using these pickers helps
ensure that your users can pick a time or date that is valid, formatted correctly,
1. DatePicker
The DatePicker allows the user to select a date (year, month, day). It can be used
SAMPLE CODE:
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>
2. TimePicker
The TimePicker allows users to select time (hours and minutes). Like the
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"
android:is24HourView="true" />
14
SAMPLE CODE:
package com.example.datepicker;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDate = findViewById(R.id.btnDate);
txtDate = findViewById(R.id.txtDate);
btnTime = findViewById(R.id.btnTime);
txtTime = findViewById(R.id.txtTime);
btnDate.setOnClickListener(v -> {
15
(view, year1, month1, dayOfMonth) -> txtDate.setText("Selected Date: " +
dayOfMonth + "/"
datePickerDialog.show();
});
btnTime.setOnClickListener(v -> {
timePickerDialog.show();
});
set to the current date and time based on the device’s default time zone and
locale.
ANDROID WEBVIEW
Android WebView is used to load and display the web pages in android.
16
STEP 1: create new project with empty views activity
Click New project->Choose "Empty Views Activity" from the project template
permission
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.webview.project">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.StudyTonight">
<activity android:name=".MainActivity">
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>
17
STEP 3: adding webview to android activity
Now go to app -> res -> layout -> activity_main.xml and add Webview
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">
android:id="@+id/oklWebView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
Next, we create the object of WebView class inside MainActivity class, then
inside the onCreate method, we initialize the WebView. After initializing the
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
18
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize WebView
webView = findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
// Load a website
@Override
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
• webView.loadUrl("https://www.google.com");
Loads Google's website into the WebView.
19
ANDROID DIFFERENT TYPES OF MENUS
In android, we have a three fundamental type of Menus available to define a
• Options Menu
• Context Menu
• Popup Menu
activity and it is useful to implement actions that have a global impact on the
Bottom_nav_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
Context_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
</menu>
20
Android Popup Menu
In android, Popup Menu displays a list of items in a vertical list that’s anchored
to the view that invoked the menu and it’s useful for providing an overflow of
Popup_menu.xml :
<menu xmlns:android="http://schemas.android.com/apk/res/android">
For all menu types, Android provides a standard XML format to define menu
menu and all its items in an XML menu resource and load menu resource as
In android, to define menu, we need to create a new folder menu inside of our
project resource directory (res/menu/) and add a new XML file to build the
Element Description
<menu> It’s a root element to define a Menu in XML file and it will hold
21
Element Description
Once we are done with creation of menu, we need to load the menu resource
from our activity using MenuInflater.inflate().
MenuInflater.inflate() in Android
In Android, MenuInflater.inflate() is used to convert an XML menu resource (.xml)
into a runtime menu (such as options menu, context menu, or popup menu) that the
Syntax
@Override
inflater.inflate(R.menu.my_menu, menu);
return true;
package] directory.
22
Android supports the following ways of storing data in the local file system:
SHARED PREFERENCES
Shared Preferences is a type of data storage used in Android to store private
data in key-value pairs. It only allows you to store and retrieve primitive data
types - boolean, float, int, long, and strings. The data you want to save gets
directory: data/data/<package-name>/shared-prefs/yourFilename.xml
primitive data types. To get a SharedPreferences object for our application, you
Use this method if you need multiple preferences files to store your key-
value pairs. To uniquely identify your file, you must give a unique name of the
2) getPreferences(int mode)
Use this method if you need only one preferences file to store key-value pairs.
Since this will be the only single preferences file for your Activity, you don't
23
need a name for the file. The mode defines the way in which you want to store
➢ MODE_PRIVATE
application.
➢ Context.MODE_MULTI_PROCESS
SharedPreferences file.
➢ Context.MODE_APPEND
This mode will append the new preferences added with the already
existing preferences.
Note: Following modes were earlier used, but now they have been deprecated.
➢ MODE_WORLD_READABLE
➢ MODE_WORLD_WRITEABLE
putString(key,value) etc.
When you want to store the data, for example, using putString() method,
24
• Key: You need to define a unique key that you will be needed when you
Sample code:
SharedPreferences s; s=getSharedPreferences("myFile",Context.MODE_PRIVATE);
SharedPreferences.Editor e = s.edit();
e.putString("key1","I LOVE");
e.putString("key2","ANDROID");
e.commit();
Note: If you have used getSharedPreferences() method, then you need to provide the
When you want to retrieve your data, for example, using getString() method, there
• Key: You need to specify the same key that you have mentioned while
saving the data so that you get the unique value (i.e. your data).
match with any of the keys saved, then this particular default value gets
displayed.
Sample code:
SharedPreferences ss=getSharedPreferences("myFile",Context.MODE_PRIVATE);
25
Persisting data to files :
Android provides Internal Storage and External Storage to store files.
Use internal storage to save files that should be private to the app.
Saving a File
Context.MODE_PRIVATE)) {
fos.write(fileContents.getBytes());
} catch (IOException e) {
e.printStackTrace();
Reading a File
String line;
stringBuilder.append(line).append("\n");
} catch (IOException e) {
e.printStackTrace();
26
}
Deleting a File
if (file.exists()) {
file.delete();
} catch (IOException e) {
e.printStackTrace();
27
String line;
stringBuilder.append(line).append("\n");
} catch (IOException e) {
e.printStackTrace();
SQL database engine. Unlike most other SQL databases, SQLite does not have
a separate server process. SQLite reads and writes directly to ordinary disk files.
The below are three components of SQLite that you need to understand because
systems.
everything in motion to create your database but holds off until you are
28
ready to use that database. And the way SQLiteOpenHelper knows that
you are ready to use your database is when you access that database
3. Cursor — The reason you store your data in a database is so you can
access them later. That access is called a query and a successful query will
return a list of the items you queried for. If that list is so long, your
Android device may choke if you want to access all of the items in the
returned result. This is where the Cursor comes in, the list of the items
that you query for are wrapped in a Cursor and the Cursor hands them
Sample code:
package com.example.notescrud
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
companion object {
private const val DATABASE_NAME = "notesapp.db"
private const val DATABASE_VERSION = 1
private const val TABLE_NAME = "allnotes"
private const val COLUMN_ID = "id"
private const val COLUMN_TITLE = "title"
private const val COLUMN_DESCRIPTION = "description"
}
29
val createTableQuery =
"CREATE TABLE $TABLE_NAME($COLUMN_ID INTEGER PRIMARY
KEY, $COLUMN_TITLE TEXT, $COLUMN_DESCRIPTION TEXT)"
db?.execSQL(createTableQuery)
}
try {
if (cursor.moveToFirst()) {
do {
val id = cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID))
val title =
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TITLE))
val description =
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_DESCRIPTION))
val note = NotesData(id, title, description)
noteList.add(note)
30
} while (cursor.moveToNext())
}
} finally {
cursor.close()
db.close()
}
return noteList
}
}
Companion object:
➢ This contains static values for the database, table name, and column
managing upgrades).
Column names for storing the ID, title, and description of each note.
onCreate(db: SQLiteDatabase?):
➢ This method is called when the database is created for the first time.
➢ Primary Key: The id is the primary key, ensuring each note has a unique
identifier.
31
onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int):
➢ This method is called when the database needs to be upgraded, usually
when there is a change in the database schema, like adding new columns
➢ It drops the existing table using DROP TABLE IF EXISTS and calls
insertNote():
➢ This method inserts a new note into the database.
➢ Steps:
appropriate columns.
getAllNotes():
➢ Steps:
o Loops through the result set (cursor) to extract the id, title, and
noteList.
32