0% found this document useful (0 votes)
19 views32 pages

Mad Unit-Iii

Unit III focuses on advanced user interface components and data persistence in Android applications. It covers various UI elements such as Basic Views, Picker Views, ListView, and ImageView, as well as methods for saving user preferences and persisting data using files and databases. The unit emphasizes creating intuitive interfaces and efficient data management techniques for enhancing user interaction.

Uploaded by

yaswinmbu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views32 pages

Mad Unit-Iii

Unit III focuses on advanced user interface components and data persistence in Android applications. It covers various UI elements such as Basic Views, Picker Views, ListView, and ImageView, as well as methods for saving user preferences and persisting data using files and databases. The unit emphasizes creating intuitive interfaces and efficient data management techniques for enhancing user interaction.

Uploaded by

yaswinmbu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

UNIT - III: ADVANCED USER INTERFACE AND DATA PERSISTENCE

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

Advanced User Interface and Data Persistence focuses on enhancing

user interaction and efficiently managing data storage in Android applications.

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

content within apps. Additionally, it discusses saving user settings using

SharedPreferences, and persisting data to files or databases for long-term

storage, ensuring apps retain data across sessions. The focus is on creating

intuitive interfaces and reliable data management techniques.

BASIC VIEWS IN ANDRIOID

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

information, we will have to use the TextView alongside.

SAMPLE CODE:

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp"/>

EditText View in Android

EditText is a TextView which is Editable. It has almost similar properties as a

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

automatically displays the keyboard.

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

and radio boxes comes in handy.

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

if multiple selection is allowed then check box should be used.

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

clicked by the user to perform an action. It has the same properties as a

TextView, with a few Buttons specific properties.

SAMPLE CODE:

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"/>

IMAGE VIEW

ImageView and ImageButton in Android

ImageView and ImageButton are used in Android application to place an image

in the view. ImageButton is used to use an image as a button in your android

application.

IMAGEVIEW IN ANDROID

ImageView is used to show any picture on the user interface.

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

attached with them upon clicking.

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

android: maxHeight Used to specify a maximum height for this view.

android: maxWidth Used to specify a maximum width for this view.

android:src Sets a drawable as the content for this ImageView.

Controls how the image should be resized or moved to


android: scaleType
match the size of the ImageView.

5
A few more, commonly used attributes with ImageView

android:background: This property gives a background color to your

ImageView. Following is some of the commonly used attributes:When your

image is not able to entirely fill the ImageView, then background color is used

to fill the area not covered by the image.

android:padding: To provide padding or extra space inside the ImageView for

the image.

All scaleType in ImageView


Here we have specified all the possible values for the attribute scaleType which

can be used in your app for ImageView:

• CENTER: Places the image in center, but does not scale it.

• CENTER_CROP: Scales the image uniformly.

• 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

will be inside it.

• FIT_CENTER: Scale the image from the center.

• FIT_END: Scale the image from the end of the container, i.e from the

right hand side.

• FIT_START: Scale the image from the start of the container, i.e from the

left hand side.

• FIT_XY: This will fill the complete container with the image. This

generally distorts the image by stretching/sqeezing it in disproportionate

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;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initializing Views

EditText editText = findViewById(R.id.editText);

Button button = findViewById(R.id.button);

ImageView imageView = findViewById(R.id.imageView);

CheckBox checkBox = findViewById(R.id.checkBox);

RadioGroup radioGroup = findViewById(R.id.radioGroup);

Switch switchToggle = findViewById(R.id.switchToggle);

TextView textView = findViewById(R.id.textView);

7
// Button Click Event

button.setOnClickListener(v -> {

String name = editText.getText().toString();

boolean isSubscribed = checkBox.isChecked();

String gender = "";

int selectedId = radioGroup.getCheckedRadioButtonId();

if (selectedId != -1) {

RadioButton selectedRadioButton = findViewById(selectedId);

gender = selectedRadioButton.getText().toString();

boolean isNotificationEnabled = switchToggle.isChecked();

// Display the collected information in a Toast message

String message = "Name: " + name + "\n" +

"Subscribed: " + isSubscribed + "\n" +

"Gender: " + gender + "\n" +

"Notifications: " + isNotificationEnabled + "\n" ;

Toast.makeText(MainActivity.this, message, Toast.LENGTH_LONG).show();

});

• AppCompatActivity is a subclass of Activity in Android that provides

compatibility support for modern Android features on older devices. It is part

of AndroidX and is commonly used as the base class for activities in Android

applications.

• findViewById(R.id.viewID) is a method in Android used to get references to

UI components defined in an XML layout file. It allows your Java/Kotlin code

to interact with views such as Button, TextView, EditText, etc.

• Toast in Android is a short popup message that appears on the screen for a

brief time. It is used to show quick feedback to users without blocking

interaction. Toast.makeText(context, message, duration).show();

8
Eg: Toast.makeText(MainActivity.this, "Hello, Toast!",Toast.LENGTH_SHORT).show();

Displays "Hello, Toast!" for 2 seconds.

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.

Inside a ListView, we can show list of Text items by using TextView, or

pictures using ImageView, or any other view or a combination of views.

As ListView is generally used to display a large set of data, hence it is not

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

the layout XML.

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

and Adapter View.

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 the runtime memory.

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

content to it as it is incapable of displaying data on its own.

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

it to the linked Adapter view to create UI components.

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

some ready-to-use adapter classes, such as ArrayAdapter, SimpleAdapter etc.

What is an Adapter View?

An Adapter View can be used to display large sets of data efficiently in form

of List or Grid or Gallery or Drop Down etc, provided to it by an Adapter.

An Adapter View is capable of displaying millions of items on the User

Interface, while keeping the memory and CPU usage very low and without any

noticeable lag. Different Adapters follow different strategies for this, but the

default Adapter provided in Android SDK follow the following tricks:

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

Adapter View will always load only 5 or 6 or maybe 7 items at once,

depending upon the display size. Hence saving memory.

2. It also reuses the already created layout to populate data items as the user

scrolls, hence saving the CPU usage.

Suppose you have a dataset, like a String array with the following contents.

String days[] = {"Monday", "Tuesday", "Wednesday",


"Thursday", "Friday", "Saturday", "Sunday"};

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:

ArrayAdapter is a built-in adapter that connects a simple list of data (like an

ArrayList) to an AdapterView (ListView, Spinner, etc.). It automatically maps each

item in the list to a default layout (TextView).

Syntax:

ArrayAdapter<T> adapter = new ArrayAdapter<>(context, layout, data);

• context → Current activity (e.g., this).

• layout → Predefined layout for list items

(android.R.layout.simple_list_item_1).

• data → The list of items.

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

to manage the data. AdapterView is responsible for displaying the data.

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;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Reference to ListView

ListView listView = findViewById(R.id.listView);

// Sample data for ListView

String[] items = {"Apple", "Banana", "Orange", "Grapes", "Pineapple"};

// Setting Adapter

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,

android.R.layout.simple_list_item_1 items);

listView.setAdapter(adapter);

// Handle Item Clicks

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

String selectedItem = (String) parent.getItemAtPosition(position);

Toast.makeText(MainActivity.this, "Clicked: " + selectedItem,

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,

and adjusted to the user's locale.

1. DatePicker

The DatePicker allows the user to select a date (year, month, day). It can be used

either as a widget in a layout or within a DatePickerDialog.

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

DatePicker, it can be a widget or a dialog.

<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;

public class MainActivity extends AppCompatActivity {

private Button btnDate;

private TextView txtDate;

private Button btnTime;

private TextView txtTime;

@Override

protected void onCreate(Bundle savedInstanceState) {

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 -> {

final Calendar c = Calendar.getInstance();

int year = c.get(Calendar.YEAR);

int month = c.get(Calendar.MONTH);

int day = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new DatePickerDialog(MainActivity.this,

15
(view, year1, month1, dayOfMonth) -> txtDate.setText("Selected Date: " +

dayOfMonth + "/"

+ (month1 + 1) + "/" + year1), year, month, day);

datePickerDialog.show();

});

btnTime.setOnClickListener(v -> {

final Calendar c = Calendar.getInstance();

int hour = c.get(Calendar.HOUR_OF_DAY);

int minute = c.get(Calendar.MINUTE);

TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this,

(view, hourOfDay, minute1) -> txtTime.setText("Selected Time: " + hourOfDay +

":" + minute1), hour, minute, true);

timePickerDialog.show();

});

• Calendar.getInstance() is a method in Android that returns a Calendar object

set to the current date and time based on the device’s default time zone and

locale.

• TimePickerDialog and DatePickerDialog are Android pop-up dialogs that

allow users to select a time or date interactively.

ANDROID WEBVIEW
Android WebView is used to load and display the web pages in android.

A WebView is useful when we need to increase control over the UI and

advanced configuration options in our app.

STEPS FOR CREATING WEB VIEW IN OUR ANDROID APPLICATION

16
STEP 1: create new project with empty views activity

Click New project->Choose "Empty Views Activity" from the project template

window and click on Next.

STEP 2: adding the internet permission

Now go to app -> mainfests-> AndroidManifest.xml and add internet

permission

<?xml version="1.0" encoding="utf-8"?>

<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>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</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

<RelativeLayout 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">

<!-- webview -->


<WebView

android:id="@+id/oklWebView"

android:layout_width="match_parent"

android:layout_height="match_parent"

/>

</RelativeLayout>

STEP 4: MODIFY THE ActivityMain.java FILE

Next, we create the object of WebView class inside MainActivity class, then

inside the onCreate method, we initialize the WebView. After initializing the

webview, we simply load the URL


package com.example.webviewapp;

import android.os.Bundle;

import android.webkit.WebSettings;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private WebView webView;

18
@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize WebView

webView = findViewById(R.id.webview);

// Configure WebView settings

WebSettings webSettings = webView.getSettings();

webSettings.setJavaScriptEnabled(true); // Enable JavaScript

webSettings.setDomStorageEnabled(true); // Enable DOM storage

// Open links inside WebView instead of external browser

webView.setWebViewClient(new WebViewClient());

// Load a website

webView.loadUrl("https://www.google.com"); // Change this to your desired URL

// Handle back button press to navigate within WebView

@Override

public void onBackPressed() {

if (webView.canGoBack()) {

webView.goBack();

} else {

super.onBackPressed();

• getSettings() retrieves settings for the WebView.

• setJavaScriptEnabled(true); allows JavaScript execution in WebView.

• setDomStorageEnabled(true); enables support for local storage (important for

modern web apps).

• 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

set of options and actions in our android applications.

The following are the commonly used Menus in android applications.

• Options Menu

• Context Menu

• Popup Menu

Android Options Menu

In android, Options Menu is a primary collection of menu items for an

activity and it is useful to implement actions that have a global impact on the

app, such as Settings, Search, etc.

Bottom_nav_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/home" android:title="Home" android:icon="@drawable/ic_home"/>

<item android:id="@+id/search" android:title="Search" android:icon="@drawable/ic_search"/>

<item android:id="@+id/profile" android:title="Profile"android:icon="@drawable/ic_profile"/>

</menu>

Android Context Menu


In android, Context Menu is a floating menu that appears when the user

performs a long click on an element and it is useful to implement actions that

affect the selected content or context frame.

Context_menu.xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/delete" android:title="Delete"/>

<item android:id="@+id/share" android:title="Share"/>

</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

actions that related to specific content.

Popup_menu.xml :
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/item1" android:title="Item 1"/>

<item android:id="@+id/item2" android:title="Item 2"/> </menu>

For all menu types, Android provides a standard XML format to define menu

items. Instead of building a menu in our activity's code, we should define a

menu and all its items in an XML menu resource and load menu resource as

a Menu object in our activity or fragment.

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

menu with the following elements.

Element Description

<menu> It’s a root element to define a Menu in XML file and it will hold

one or more and elements.

<item> It is used to create a menu item and it represents a single item

on the menu. This element may contain a nested <menu>

element in order to create a submenu.

21
Element Description

<group> It’s an optional and invisible for <item> elements. It is used to

categorize the menu items so they share properties such as

active state and visibility.

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

user can interact with.

Syntax

@Override

public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();

inflater.inflate(R.menu.my_menu, menu);

return true;

• getMenuInflater() → Gets a MenuInflater instance.

• inflate(R.menu.my_menu, menu) → Loads menu items from XML

(my_menu.xml) and adds them to the menu.

File based persistence:


Android allows to persists application data via the file system. For each

application the Android system creates a data/data/[application

package] directory.

22
Android supports the following ways of storing data in the local file system:

• Preferences - Android allows you to save and retrieve persistent key-

value pairs of primitive data type.

• Files - You can create and update files

• SQLite database - instances of SQLite databases are also stored on 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

stored in an XML file which can be found in the following

directory: data/data/<package-name>/shared-prefs/yourFilename.xml

How to access SharedPreferences object?

We need a SharedPreferences object to store and retrieve the key-value pairs of

primitive data types. To get a SharedPreferences object for our application, you

can use one of the following two methods:

1) getSharedPreferences(String filename, int mode)

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

file, which you can specify with the first parameter.

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

your key-value pair data. Following are some type of modes:

➢ MODE_PRIVATE

This mode allows the SharedPreferences file to be accessed only by your

application.

➢ Context.MODE_MULTI_PROCESS

This mode allows multiple processes to modify the same

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

This mode allowed other application to read the preferences.

➢ MODE_WORLD_WRITEABLE

This mode allowed other application to write the preferences.

SAVING THE DATA


1. Create a suitable type of SharedPreferences object.

2. Call edit() method to get a SharedPreferences.Editor instance.

3. Add key-value pair with methods such as putBoolean(key,value) ,

putString(key,value) etc.

4. Commit the new values with commit() method.

When you want to store the data, for example, using putString() method,

there are two kind of parameters used:

24
• Key: You need to define a unique key that you will be needed when you

want to retrieve the value related with that key.

• Value: This is your data that you want to store.

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();

RETRIEVING THE DATA


1. Create the SharedPreferences object of the same type that you have used while

saving the data.

Note: If you have used getSharedPreferences() method, then you need to provide the

filename from which you want to retrieve your data.

2. Use SharedPreferences methods such as getBoolean(key,

default_value), getString(key, default value) etc. to get the value.

When you want to retrieve your data, for example, using getString() method, there

are two kind of parameters used:

• 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).

• Default: If in the SharedPreferences file, the key you specified doesn’t

match with any of the keys saved, then this particular default value gets

displayed.

Sample code:

SharedPreferences ss=getSharedPreferences("myFile",Context.MODE_PRIVATE);

String message1 = ss.getString("key1","Key doesn’t match");

String message2 = ss.getString("key2","Key doesn’t match");

25
Persisting data to files :
Android provides Internal Storage and External Storage to store files.

A. Internal Storage (Private to the App)

Use internal storage to save files that should be private to the app.

Saving a File

String filename = "myfile.txt";

String fileContents = "Hello, World!";

try (FileOutputStream fos = openFileOutput(filename,

Context.MODE_PRIVATE)) {

fos.write(fileContents.getBytes());

} catch (IOException e) {

e.printStackTrace();

Reading a File

String filename = "myfile.txt";

StringBuilder stringBuilder = new StringBuilder();

try (FileInputStream fis = openFileInput(filename);

InputStreamReader isr = new InputStreamReader(fis);

BufferedReader br = new BufferedReader(isr)) {

String line;

while ((line = br.readLine()) != null) {

stringBuilder.append(line).append("\n");

} catch (IOException e) {

e.printStackTrace();

26
}

String fileData = stringBuilder.toString();

Deleting a File

String filename = "myfile.txt";

File file = new File(getFilesDir(), filename);

if (file.exists()) {

file.delete();

B. External Storage (Accessible Outside the App)

Note: External storage requires WRITE_EXTERNAL_STORAGE permission

in Android 10 and below.

Writing to External Storage

File externalFile = new File(getExternalFilesDir(null), "externalFile.txt");

try (FileOutputStream fos = new FileOutputStream(externalFile)) {

fos.write("This is external storage data".getBytes());

} catch (IOException e) {

e.printStackTrace();

Reading from External Storage

File externalFile = new File(getExternalFilesDir(null), "externalFile.txt");

StringBuilder stringBuilder = new StringBuilder();

try (FileInputStream fis = new FileInputStream(externalFile);

InputStreamReader isr = new InputStreamReader(fis);

BufferedReader br = new BufferedReader(isr)) {

27
String line;

while ((line = br.readLine()) != null) {

stringBuilder.append(line).append("\n");

} catch (IOException e) {

e.printStackTrace();

String fileData = stringBuilder.toString();

CREATING AND USING DATABASES USING SQLite


Introduction to SQLite-Definition

SQLite is an in-process library that implements a self-contained, serverless,

zero-configuration, transactional SQL database engine. SQLite is an embedded

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

they are central to working with SQLite in Android.

1. SQLiteOpenHelper — this is the most important class that you will

work with in Android SQLite. You will use SQLiteOpenHelper to create

and upgrade your SQLite Database. In other words, SQLiteOpenHelper

removes the effort required to install and configure database in other

systems.

2. SQLiteDatabase — this is the actual database where your data is stored.

When you created your database with SQLiteOpenHelper class, it sets

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

either with getReadableDatabase() or getWritableDatabase() for read and

write operations respectively.

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

over to you in batches of any number.

Sample code:

package com.example.notescrud

import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper

class NotesDataBaseHelper(context: Context) :


SQLiteOpenHelper(context, DATABASE_NAME, null,
DATABASE_VERSION) {

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"
}

override fun onCreate(db: SQLiteDatabase?) {

29
val createTableQuery =
"CREATE TABLE $TABLE_NAME($COLUMN_ID INTEGER PRIMARY
KEY, $COLUMN_TITLE TEXT, $COLUMN_DESCRIPTION TEXT)"
db?.execSQL(createTableQuery)
}

override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {


val dropTableQuery = "DROP TABLE IF EXISTS $TABLE_NAME"
db?.execSQL(dropTableQuery)
onCreate(db)
}

fun insertNote(note: NotesData) {


val db = writableDatabase
val values = ContentValues().apply {
put(COLUMN_TITLE, note.title)
put(COLUMN_DESCRIPTION, note.description)
}

db.insert(TABLE_NAME, null, values)


db.close()
}

fun getAllNotes(): List<NotesData> {


val noteList = mutableListOf<NotesData>()
val db = readableDatabase
val query = "SELECT * FROM $TABLE_NAME"
val cursor = db.rawQuery(query, null)

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

names, which are constants used across the class.

➢ DATABASE_NAME: The name of the database file (e.g., notesapp.db).

➢ DATABASE_VERSION: The version number of the database (used for

managing upgrades).

➢ TABLE_NAME: The name of the table where notes are stored.

• COLUMN_ID, COLUMN_TITLE, COLUMN_DESCRIPTION:

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.

➢ The SQL command "CREATE TABLE $TABLE_NAME..." creates a table

named allnotes with three columns:

o id (an integer that serves as the primary key).

o title (a text field for the note's title).

o description (a text field for the note's description).

➢ 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

or changing data types.

➢ It drops the existing table using DROP TABLE IF EXISTS and calls

onCreate() again to recreate the table with the new schema.

insertNote():
➢ This method inserts a new note into the database.

➢ Parameters: Takes a NotesData object as input, which contains the note's

title and description.

➢ Steps:

o Opens the database in write mode (writableDatabase).

o Uses a ContentValues object to map the title and description to the

appropriate columns.

o Inserts the note into the allnotes table using db.insert().

o Closes the database connection after the insertion.

getAllNotes():

➢ This method retrieves all notes from the database.

➢ Steps:

o Opens the database in read mode (readableDatabase).

o Executes a SQL query "SELECT * FROM $TABLE_NAME" to

retrieve all records from the allnotes table.

o Loops through the result set (cursor) to extract the id, title, and

description of each note.

o Creates NotesData objects for each note and adds them to a

noteList.

32

You might also like