0% found this document useful (0 votes)
4 views

UNIT 3 MOB

The document provides an overview of various Android UI components including Toast, DatePicker, TimePicker, ImageView, VideoView, and Alert Dialog. It includes code snippets demonstrating how to implement these components and their methods for user interaction. Key functionalities such as displaying messages, selecting dates and times, playing media, and showing dialog boxes are highlighted.

Uploaded by

poojitham0012
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)
4 views

UNIT 3 MOB

The document provides an overview of various Android UI components including Toast, DatePicker, TimePicker, ImageView, VideoView, and Alert Dialog. It includes code snippets demonstrating how to implement these components and their methods for user interaction. Key functionalities such as displaying messages, selecting dates and times, playing media, and showing dialog boxes are highlighted.

Uploaded by

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

Unit 3

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Toast
A toast provides simple feedback about an operation in a small popup.
Toasts automatically disappear after a timeout.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


• public static final int LENGTH_LONG - displays for a long time
• public static final int LENGTH_SHORT - displays for a short time
• public static Toast makeText(Context context, CharSequence text, int
duration) - makes the toast message consist of text and time duration
• public void show() - displays a toast message
• public void setMargin(float horizontalMargin, float verticalMargin) -
changes the horizontal and vertical differences
• public void setGravity (int gravity, int xOffset, int yOffset) - to set the
position of a Toast message 1.TOP 2.BOTTOM 3.LEFT 4.RIGHT
5.CENTER 6.CENTER_HORIZONTAL 7.CENTER_VERTICAL

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


int duration = Toast.LENGTH_SHORT;

Toast toast = Toast.makeText(MainActivity.this, “Hello”, duration);


toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 0, 0);
toast.show();

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


DatePicker

<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"
/>

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


import android.widget.DatePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatePicker datePicker = findViewById(R.id.datePicker);
Calendar today = Calendar.getInstance();

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


datePicker.init(
Hold the initial values that will be
today.get(Calendar.YEAR), displayed in the DatePicker.
today.get(Calendar.MONTH), Typically, set to the current date
values
today.get(Calendar.DAY_OF_MONTH),
new DatePicker.OnDateChangedListener() { The year, month and day
@Override selected by the user

public void onDateChanged(DatePicker view, int year, int month, int day) {
String msg = "You Selected: " + day + "/" + (month + 1) + "/" + year;
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
}
}
);
}
}

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


DatePickerDialog
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="@+id/in_date" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SELECT DATE"
android:id="@+id/btn_date"/>

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


import android.app.DatePickerDialog;
import android.widget.DatePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button btnDatePicker;
EditText txtDate;
private int mYear, mMonth, mDay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDatePicker=(Button)findViewById(R.id.btn_date);
txtDate=(EditText)findViewById(R.id.in_date);
btnDatePicker.setOnClickListener(this);
}

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


@Override
public void onClick(View v) {
Hold the initial values that will be
final Calendar c = Calendar.getInstance(); displayed in the DatePickerDialog.
mYear = c.get(Calendar.YEAR); Typically, set to the current date
mMonth = c.get(Calendar.MONTH); values
mDay = c.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() { The year, month and day
selected by the user
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
txtDate.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
}
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
TimePicker
TimePicker provides two display modes:

Clock Mode: Displays an analog clock-style interface for time selection.


Spinner Mode: Presents hour and minute values in a scrollable spinner
format.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="clock" />

<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner" />

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Methods of TimePicker:
TimePicker simpleTimePicker=findViewById(R.id.simpleTimePicker);
simpleTimePicker.setHour(5);
simpleTimePicker.setMinute(35);
int hours =simpleTimePicker.getHour();
int minutes = simpleTimePicker.getMinute();
simpleTimePicker.setIs24HourView(true);
Boolean mode=simpleTimePicker.is24HourView();

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


import android.widget.TimePicker;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
TimePicker tp = findViewById(R.id.timePicker);
tp.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
textView.setText("Time is :: " + hourOfDay + " : " + minute);
}
});
}
}
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
<EditText
android:id="@+id/time"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:hint="Select Time..." /> import android.app.TimePickerDialog;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TimePickerDialog EditText time;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.time);
time.setOnClickListener(new View.OnClickListener() {

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


@Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
time.setText(selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);
mTimePicker.show();
}
});
}
}

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


ImageView
In Android, ImageView class is used to display an image file in application.

<ImageView
android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion" />

ImageView i = findViewById(R.id.img);
i.setImageResource(R.drawable.lion);

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


<ImageView
android:id="@+id/img"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="center"
android:src="@drawable/lion" />
CENTER – Center the image but doesn’t scale the image
CENTER_CROP – Scale the image uniformly
CENTER_INSIDE – Center the image inside the container, rather than making the edge match exactly
FIT_CENTER – Scale the image from center
FIT_END – Scale the image from the end of the container.
FIT_START – Scale the image from start of the container
FIT_XY – Fill the image from x and y coordinates of the container
MATRIX – Scale using the image matrix when drawing

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
<RelativeLayout>
<TextView
android:id="@+id/headingText"
android:text="MEDIA PLAYER"/>
<LinearLayout>
<Button
android:id="@+id/stopButton"
android:text="STOP" />
<Button
android:id="@+id/playButton"
android:text="PLAY" />
<Button
android:id="@+id/pauseButton"
android:text="PAUSE" />
</LinearLayout>
</RelativeLayout>

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.music);

Button bPlay = findViewById(R.id.playButton);


Button bPause = findViewById(R.id.pauseButton);
Button bStop = findViewById(R.id.stopButton);
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
bPlay.setOnClickListener(new View.OnClickListener() { bPause.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
mediaPlayer.start(); mediaPlayer.pause();
} }
}); });
bStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaPlayer.stop();
mediaPlayer.prepare();
}
});
}
}
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
VideoView
<VideoView
android:id="@+id/simpleVideo"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Methods Used in VideoView:
setVideoUri(Uri uri): to set the absolute path of the video file which is
going to be played

VideoView simpleVideo = findViewById(R.id.simpleVideo);


simpleVideo.setVideoURI(Uri.parse("Paste Your Video URL Here"));

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


setMediaController(MediaController controller): to set the controller
for the controls of video playback

MediaController mediaController = new MediaController(this);


VideoView simpleVideo = findViewById(R.id.simpleVideo);
simpleVideo.setMediaController(mediaController);

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


VideoView simpleVideo = findViewById(R.id.simpleVideo);
simpleVideo.start();
simpleVideo.pause();
simpleVideo.stopPlayback();
int duration =simpleVideo.getDuration();
int pos = simpleVideo.getCurrentPosition();
Boolean isPlaying = simpleVideo.isPlaying();

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Methods Of MediaController:
MediaController con = new MediaController(this);
con.setAnchorView(simpleVideo); // set anchor view for video view
con.show(); // show the controller on the screen
con.show(500); // set the time to show the controller on the screen
con.hide(); // hide the control from the screen
Boolean isShowing = con.isShowing(); // checks whether the controls
are currently visible or not

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.media.MediaPlayer;
import android.net.Uri;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
VideoView vid;
MediaController con;
@Override
protected void onCreate(Bundle s) {
super.onCreate(s);
setContentView(R.layout.activity_main);
vid= findViewById(R.id.simpleVideo);
if (con == null) {
con = new MediaController(MainActivity.this);
con.setAnchorView(vid);
}
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
vid.setMediaController(con);
vid.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.fishvideo));
vid.start();
vid.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
Toast.makeText(this, "Thank You...!!!", Toast.LENGTH_LONG).show();
}
});
vid.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
return false;
}
});
}
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Alert Dialog Box
An Android Alert Dialog is a UI element that displays a warning or
notification message and asks the user to respond with options such as
Yes or No.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
AlertDialog.Builder is used to create an interface for Alert Dialog.
AlertDialog.Builder a = new AlertDialog.Builder(this);

Alert Dialog code has the following methods :


• setTitle(): method for displaying the Alert Dialog box Title
• a.setTitle("Confirm Exit..!!!");
• setMessage(): method for displaying the message
• a.setMessage("Are you sure,You want to exit");
• setIcon(): method is used to set the icon on the Alert dialog box.
• a.setIcon(R.drawable.question);
• setCancelable() – If set to false it does not allow to cancel the dialog box
by clicking on area outside the dialog else it allows.
• a.setCancelable(false);

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


• setPositiveButton() – adds positive button
a.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
• setNegativeButton() - adds negative button
a.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"No", Toast.LENGTH_SHORT).show();
}
});

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


import android.content.DialogInterface;
import androidx.appcompat.app.AlertDialog;
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle s) {
super.onCreate(s);
setContentView(R.layout.activity_main);
}

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


@Override
public void onBackPressed() {
AlertDialog.Builder builder = new
AlertDialog.Builder(MainActivity.this);
builder.setMessage("Do you want to exit ?");
builder.setTitle("Alert !");
builder.setCancelable(false);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Styles and themes
A style is a collection of attributes that specifies the appearance for a
single View. A style can specify attributes such as font color, font size,
background color, and much more.

A theme is a collection of attributes that's applied to an entire app,


activity, or view hierarchy—not just an individual view.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


res/values/styles.xml

<resources>
<style name="GreenText" parent="TextAppearance.AppCompat">
<item name="android:textColor">#00FF00</item>
</style>
</resources>

<TextView
style="@style/GreenText"
... />

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


<manifest ... >
<application android:theme="@style/Theme.AppCompat" ... >
</application>
</manifest>

<manifest ... >


<application ... >
<activity android:theme="@style/Theme.AppCompat.Light" ... >
</activity>
</application>
</manifest>
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
<style name="AppTheme" parent="Theme.AppCompat.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimayDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@color/colorAccent</item>
</style>

<resources>
<color name="colorPrimary">#00cccc</color>
<color name="colorPrimaryDark">#006666</color>
<color name="colorIt">#188596</color>
<color name="colorAccent">#BBF1F1</color>
<color name="colorAccent1">#1397B1</color>
</resources>
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
<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">0dp</item>
<item name="android:layout_marginTop">10dp</item> <resources>
<item name="android:textColor">#86AD33</item> <color name="colorPrimary">#00cccc</color>
<item name="android:textStyle">bold</item>
<color name="colorPrimaryDark">#006666</color>
<item name="android:textSize">20dp</item>
<color name="colorIt">#188596</color>
</style>
<color name="colorAccent">#BBF1F1</color>
<style name="ButtonStyle" parent="@android:style/Widget.Button">
<item name="android:layout_width">wrap_content</item> <color name="colorAccent1">#1397B1</color>
<item name="android:layout_height">wrap_content</item> </resources>
<item name="android:layout_marginLeft">20dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">@color/colorIt</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">30dp</item>
</style>

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginLeft="10dp" android:orientation="vertical">
<TextView
android:id="@+id/TextView1"
android:layout_width="300dp" android:layout_height="50dp"
android:layout_marginLeft="45dp" android:layout_marginTop="100dp"
android:gravity="center" android:text="Welcome"
android:textSize="25dp" android:textColor="@color/colorAccent1" />
<TextView
android:id="@+id/btnShow" android:gravity="center"
android:layout_marginLeft="35dp" android:layout_marginTop="200dp"
style="@style/ButtonStyle" android:text="Android Style" />
</LinearLayout>
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apply Theme Programmatically
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle s) {
setTheme(R.style.AppTheme_Dark);
super.onCreate(s);
setContentView(R.layout.activity_main);
}
}

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Tabs

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
SQLite

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Content Providers
The android.content package contains classes for accessing and
publishing data.
Two classes in the package help enforce this requirement:
the ContentResolver and
the ContentProvider.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


In order to get data from a content provider, you use a mechanism
called ContentResolver.
It provides methods to query, update, insert and delete data from a
content provider.
A request to a content resolver contains an URI to one of the SQL-like
methods.
These methods return a Cursor instance.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


There are two basic steps to interact with a content provider via
content resolver:
1. Request permission from the provider by adding a permission in
the manifest file.
2. Construct a query with an appropriate content URI and send the
query to the provider via content resolver object.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Methods of Content Provider

onCreate() When the receiver is formed, this function in Android initializes the
Provider.
query() In Android, it receives a query request from the user and responds with a
cursor.
insert() We use this method to insert data into our content provider.
update() This function updates existing data in a row and returns the updated row
data.
delete() Removes existing data from the content provider.
getType() This function returns the Multipurpose Internet Mail Extension data type
to the supplied Content URI.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Built-in Content Providers in Android
ContactsContract: This built-in content provider is used to provide access to the
device's contact data such as a phone number or an email address.

MediaStore: This built-in content provider is used to provide access to the device's
media files such as videos, photos, and also audio recordings.

Calendar: It provides access to the device's calendar data.

UserDictionary: Provides access to the user dictionary data (stores custom words
that can be used by the keyboard app for suggestions).

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Popular Third-party Content Providers
Firebase Realtime Database: It's a cloud-based NoSQL database that provides real-time data
synchronization across multiple devices.

SQLite: It's a database engine for Android that provides a lightweight and efficient way to store and
retrieve data.

Google Drive: Google Drive is a cloud-based file storage and sharing service that provides access to
files from anywhere and on any device.

Twitter API: Twitter API provides access to Twitter data, such as tweets, mentions, and direct
messages.

Other examples of popular third-party content providers are Dropbox, Microsoft OneDrive, and
Amazon S3.
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Accessing Data with Content Provider
It involves
determining the Content URI,
obtaining a ContentResolver instance, and then
using the appropriate CRUD operations to manipulate the data.

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
The universal resource identifiers (URIs) that identify the data in content providers
are known as Content URIs.
Every content provider method takes a URI as an argument.
Syntax: content://<authority>/<path>/<optional_id>
content:// – is the scheme that helps in identifying the URI as a content URI.
authority – It is the content provider's unique name, such as photos or contacts. It's
a string that can identify the complete content source.
path – It is frequently used to identify some or all of the Provider's data. The path is
usually used to distinguish between specific tables.
optional id - id is used to retrieve a specific record in a file. We only utilize this when
we need to retrieve a particular document rather than the entire file. It is a
numerical identification used to access a specific data table row.
content://com.android.provider/songs/12
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Create an object of ContentResolver to provide access to content providers in
Android
ContentResolver cr = context.getContentResolver();
Query the Content Provider using query() method
This would require the following parameters:
Content URI
projection (the columns to be returned)
selection (criteria for selecting the data)
selectionArgs (arguments for the selection criteria)
sortOrder (sorting order for the returned data)
Cancellation signal (in order to cancel the operation, if needed)

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


<uses-permission android:name="android.permission.READ_CONTACTS"/>

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in


Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in
START MainActivity

DEFINE constant PERMISSIONS_REQUEST_READ_CONTACTS = 100


DECLARE listViewContacts

ON Activity Creation:
SET layout to activity_main
FIND ListView by ID and assign to listViewContacts
FIND Button by ID

ON Button Click:
CALL checkContactsPermission()

FUNCTION checkContactsPermission():
IF permission to READ_CONTACTS is NOT granted:
REQUEST permission from user
ELSE:
CALL loadContacts()

FUNCTION loadContacts():
CREATE empty list called contacts

QUERY device for contact list using Phone.CONTENT_URI

IF result cursor is not null:


FOR EACH entry in cursor:
EXTRACT contact name
EXTRACT contact phone number
ADD "name - number" to contacts list

SET contacts list into ListView using an ArrayAdapter

FUNCTION onRequestPermissionsResult(requestCode, permissions, grantResults):


IF requestCode matches AND permission is granted:
CALL loadContacts()

END MainActivity

Apoorva S., Asst. Prof., Dept of CS www.iadc.ac.in

You might also like