Вы находитесь на странице: 1из 63

Content Provider

Dr. Leon Jololian


Definition
A Content Provider implements a mechanism that
allows users to access data from other
applications.
The information is usually stored in databases or
flat files.
It supports the four basic CRUD operations:
Create, Read, Update and Delete.
Android implements some standard content
providers to access contacts, media files,
preference, etc.

Dr. Leon Jololian 2


Contents URI
Data is accessed from a content provider by
specifying a URI: Scheme://Authority/Path/Id
Scheme: always content
Authority: reversed domain name followed by a
qualifier corresponding to a provider
Path: to the data (optional)
Id: optional, numeric. To access single record

Dr. Leon Jololian 3


ContentResolver and ContentProvider
An application accesses the data from a content
provider using a ContentResolver client object.
This ContentResolver object has methods that call
identically-named methods in the provider object,
an instance of one of the concrete subclasses of
ContentProvider.
The ContentResolver methods provide the basic
"CRUD" functions of persistent storage.

Dr. Leon Jololian 4


The ContentResolver object in the client
application's process and the ContentProvider
object in the application that owns the
provider automatically handle inter-process
communication.
ContentProvider also acts as an abstraction
layer between its repository of data and the
external appearance of data as tables.
To access a provider, the application usually
has to request specific permissions in its
manifest file.

Dr. Leon Jololian 5


Implementing a Content Provider
It involves the following steps:
A class that extends ContentProvider
A contract class
The UriMatcher definition
The onCreate() method
The getType() method
The CRUD methods
The Android Manifest

Dr. Leon Jololian 6


Method Usage

onCreate() Prepares the content provider

getType(Uri) Returns the MIME type for this URI

delete(Uri uri, String selection, String[]


Deletes records
selectionArgs)

insert(Uri uri, ContentValues values) Adds records

query(Uri uri, String[] projection, String


selection, String[] selectionArgs, String Return records based on selection criteria
sortOrder)

update(Uri uri, ContentValues values,


Modifies data
String selection, String[] selectionArgs)
7
8
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter name" />

Dr. Leon Jololian 9


<EditText
android:id="@+id/birthday"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/name"
android:layout_below="@+id/name"
android:ems="10"
android:hint="Enter birthday" />
<Button
android:id="@+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/birthday"
android:layout_below="@+id/birthday"
android:layout_marginTop="30dp"
android:onClick="addBirthday"
android:text="Add Birthday" />
10
<Button
android:id="@+id/btnShow"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnAdd"
android:layout_below="@+id/btnAdd"
android:layout_marginTop="20dp"
android:onClick="showAllBirthdays"
android:text="Show Birthdays" />
<Button
android:id="@+id/btnDelete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btnShow"
android:layout_alignLeft="@+id/btnShow"
android:layout_marginTop="20dp"
android:onClick="deleteAllBirthdays"
android:text="Delete All Birthdays" />
</RelativeLayout>
11
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void deleteAllBirthdays (View view) {
String URL = "content://com.bestapp.BirthdayProvider/friends";
Uri friends = Uri.parse(URL);
int count = getContentResolver().delete(friends, null, null);
Toast.makeText(getBaseContext(), " All records deleted: "
+ count, Toast.LENGTH_LONG).show();
}

Dr. Leon Jololian 12


public void showAllBirthdays(View view) {
String URL="content://com.bestapp.BirthdayProvider/friends";
Uri friends = Uri.parse(URL);
Cursor c = getContentResolver().query(
friends, null, null, null, "name");
String result = "Results:";
if (!c.moveToFirst()) {
Toast.makeText(this, result + "No content!",
Toast.LENGTH_LONG).show();
} else {
do{
result = result + "\n" + c.getString(c.getColumnIndex(
BirthdayProvider.NAME)) + " with id " + c.getString(
c.getColumnIndex(BirthdayProvider.ID)) +
" has birthday: " + c.getString(c.getColumnIndex(
BirthdayProvider.BIRTHDAY));
} while (c.moveToNext());
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
} 13
public void addBirthday(View view) {
ContentValues values = new ContentValues();
values.put(BirthdayProvider.NAME,
((EditText)findViewById(R.id.name)).getText().toString());
values.put(BirthdayProvider.BIRTHDAY,
((EditText)findViewById(R.id.birthday)).getText().toString());
Uri uri = getContentResolver().insert(
BirthdayProvider.CONTENT_URI, values);
Toast.makeText(getBaseContext(), uri.toString() +
"inserted!", Toast.LENGTH_LONG).show();
}
}

Dr. Leon Jololian 14


public class BirthdayProvider extends ContentProvider {
static final String PROVIDER_NAME=
"com.bestapp.BirthdayProvider";
static final String URL =
"content://"+PROVIDER_NAME+"/friends";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String ID = "id";
static final String NAME = "name";
static final String BIRTHDAY = "birthday";
static final int FRIENDS = 1;
static final int FRIENDS_ID = 2;
DBHelper dbHelper;
// projection map for a query
private static HashMap<String, String> BirthMap;

Dr. Leon Jololian 15


// maps content URI "patterns" to the integer values set above
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(PROVIDER_NAME, "friends", FRIENDS);
uriMatcher.addURI(PROVIDER_NAME, "friends/#", FRIENDS_ID);
}
// database declarations
private SQLiteDatabase database;
static final String DATABASE_NAME = "BirthdayReminder";
static final String TABLE_NAME = "birthTable";
static final int DATABASE_VERSION = 1;
static final String CREATE_TABLE =
" CREATE TABLE " + TABLE_NAME +
" (id INTEGER PRIMARY KEY AUTOINCREMENT, " +
16
" name TEXT NOT NULL, " + " birthday TEXT NOT NULL);" ;
private static class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{ db.execSQL(CREATE_TABLE); }
@Override
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer){
Log.w(DBHelper.class.getName(),
"Upgrading database from version " + oldVer + " to "
+ newVer + ". Old data will be destroyed");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
17
}
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
database = dbHelper.getWritableDatabase();
if(database == null)
return false;
else
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String
selection, String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder queryBuilder =
new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);

18
switch (uriMatcher.match(uri)) {
case FRIENDS:
queryBuilder.setProjectionMap(BirthMap);
break;
case FRIENDS_ID:
queryBuilder.appendWhere(
ID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI "+ uri);
}
if (sortOrder == null || sortOrder == ""){ sortOrder = NAME; }
Cursor cursor = queryBuilder.query(database, projection,
selection, selectionArgs, null, null, sortOrder);
// register to watch a content URI for changes
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
19
@Override
public Uri insert(Uri uri, ContentValues values) {
long row = database.insert(TABLE_NAME, "", values);
if(row > 0) {
Uri newUri= ContentUris.withAppendedId(CONTENT_URI, row);
getContext().getContentResolver().notifyChange(newUri, null);
return newUri;
}
throw new SQLException("Fail to add a new record into " + uri);
}

Dr. Leon Jololian 20


@Override
public int update(Uri uri, ContentValues val,
String selection, String[] args){
int count = 0;
switch (uriMatcher.match(uri)){
case FRIENDS:
count = database.update(TABLE_NAME, val, selection, args);
break;
case FRIENDS_ID:
count = database.update(TABLE_NAME, val, ID +
" = " + uri.getLastPathSegment() +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""), args);
break;
default:
throw new IllegalArgumentException("Unsupported URI "+ uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
21
@Override
public int delete(Uri uri, String selection, String[] selectionArgs){
int count = 0;
switch (uriMatcher.match(uri)){
case FRIENDS:
count=database.delete(TABLE_NAME, selection, selectionArgs);
break;
case FRIENDS_ID:
String id = uri.getLastPathSegment(); //gets the id
count = database.delete( TABLE_NAME, ID + " = " + id +
(!TextUtils.isEmpty(selection) ? " AND (" + selection
+ ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException("Unsupported URI "+uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
Dr. Leon Jololian 22
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)){
// Get all friend-birthday records
case FRIENDS:
return "vnd.android.cursor.dir/vnd.example.friends";
// Get a particular friend
case FRIENDS_ID:
return "vnd.android.cursor.item/vnd.example.friends";
default:
throw new IllegalArgumentException("Err URI: " + uri);
}
}
}

Dr. Leon Jololian 23


<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bestapp.contentproviderbirthday" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=
"com.bestapp.contentproviderbirthday.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name=
"android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Dr. Leon Jololian 24


<provider android:name="BirthdayProvider"
android:authorities="com.bestapp.BirthdayProvider">
</provider>
</application>
</manifest>

Dr. Leon Jololian 25


Contact Viewer

Dr. Leon Jololian 26


<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:android=
"http://schemas.android.com/apk/res/android">

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name "
android:id="@+id/btnName"
27
android:onClick="loadNames"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone"
android:id="@+id/btnPhone"
android:onClick="loadPhones"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Email"
android:id="@+id/btnEmail"
android:onClick="loadEmails"/>
</LinearLayout>
28
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:text=""
android:textSize="20sp"
android:id="@+id/contacts" />
</LinearLayout>

29
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_TO_READ = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkForPermission();
}

30
public void checkForPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS)) {
// Show explanation to user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_CONTACTS},
PERMISSION_TO_READ);
}
} 31
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_TO_READ: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// permission was granted.
} else {
// permission denied. Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other permissions
}
32
}
public void loadNames (View v) {
TextView cv = (TextView) findViewById(R.id.contacts);
cv.setText("");

Uri uri = ContactsContract.Contacts.CONTENT_URI;


String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection =
ContactsContract.Contacts.IN_VISIBLE_GROUP
+ " = '" + ("1") + "'";
String[] selectionArgs = null;

String sortOrder =
ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";

33
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(uri, projection, selection,
selectionArgs, sortOrder);
while (cursor.moveToNext()) {
String displayName = cursor.getString(
cursor .getColumnIndex(
ContactsContract.Data.DISPLAY_NAME));
cv.append("Name: "+displayName+"\n");
}
}

34
public void loadPhones(View v) {
TextView cv = (TextView) findViewById(R.id.contacts);
cv.setText("");
Uri uri = ContactsContract.CommonDataKinds
.Phone.CONTENT_URI;
String[] projection = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
// ContactsContract.CommonDataKinds.
// StructuredPostal.FORMATTED_ADDRESS,
// ContactsContract.CommonDataKinds.Photo.PHOTO};

35
String selection = ContactsContract.Contacts.
HAS_PHONE_NUMBER + " = ?";
String[] selectionArgs = new String[]{ String.valueOf(1)};
String sortOrder =
ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
Cursor cursor = getContentResolver().query(
uri, projection, selection, selectionArgs, sortOrder);
while (cursor.moveToNext()) {
String displayName = cursor.getString(
cursor.getColumnIndex(
ContactsContract.Data.DISPLAY_NAME));
String phoneNo = cursor.getString(
cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
cv.append("Name: "+displayName+"\n");
cv.append("Phone: "+phoneNo+"\n\n\n");
}
} 36
public void loadEmails(View v){
TextView cv = (TextView) findViewById(R.id.contacts);
Uri uri = ContactsContract.
CommonDataKinds.Phone.CONTENT_URI;
Cursor cur = getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
String[] projection = new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Email.DATA };
Cursor names = getContentResolver().query(
uri, projection, null, null, null);
while (cur.moveToNext()) {
cv.setText("");
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
37
Cursor email = getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID+"= ?",
new String[]{id}, null);
cv.append("Name: "+ name +"\n");
while (email.moveToNext()) {
String emailid = email.getString(email.getColumnIndex(
ContactsContract.CommonDataKinds.Email.DATA));
String emailType = email.getString(email.getColumnIndex(
ContactsContract.CommonDataKinds.Email.TYPE));
cv.append(emailType+": "+ emailid + "\n");
}
email.close();
cv.append("\n\n\n");
} //end while
} //end loadEmails
} 38
AndroidManifest.xml
<uses-permission
android:name=
"android.permission.READ_CONTACTS">
</uses-permission>

Dr. Leon Jololian 39


Development Steps
Database Declarations
DBHelper Class
Content Provider Contract
Content Provider Class:
onCreate, query, insert, update, delete, getType
Content provider Manifest File
Client:
include Contract Provider Contract

Dr. Leon Jololian 40


Content Provider

Dr. Leon Jololian 41


// database declarations
private SQLiteDatabase database;
static final String DATABASE_NAME = "BirthdayReminder";
static final String TABLE_NAME = "birthTable";
static final int DATABASE_VERSION = 1;
static final String CREATE_TABLE = " CREATE TABLE " + TABLE_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ " name TEXT NOT NULL, " + " birthday TEXT NOT NULL);" ;

42
class DBHelper extends SQLiteOpenHelper {
// database declarations
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
43
public class ProviderContract {
static final String PROVIDER_NAME=
"com.bestapp.BirthdayProvider";
static final String URL =
"content://"+PROVIDER_NAME+"/friends";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String ID = "id";
static final String NAME = "name";
static final String BIRTHDAY = "birthday";
}

44
public class BirthdayProvider extends ContentProvider {
static final int FRIENDS = 1;
static final int FRIENDS_ID = 2;
DBHelper dbHelper;
static final UriMatcher uriMatcher;
static{
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(
ProviderContract.PROVIDER_NAME, "friends", FRIENDS);
uriMatcher.addURI(
ProviderContract.PROVIDER_NAME, "friends/#",
FRIENDS_ID);
}
@Override
public boolean onCreate () { }
45
@Override
public Cursor query (Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) { }

@Override
public Uri insert (Uri uri, ContentValues values) { }

@Override
public int update (Uri uri, ContentValues val, String selection,
String[] args){ }

@Override
public int delete (Uri uri, String selection, String[] selectionArgs){ }

@Override
public String getType (Uri uri) { }
}

46
@Override
public boolean onCreate() {
dbHelper = new DBHelper(getContext());
SQLiteDatabase database = dbHelper.getWritableDatabase();
if(database == null) return false;
else return true;
}

@Override
public Cursor query (Uri uri, String[] projection, String
selection, String[] selectionArgs, String sortOrder) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
SQLiteQueryBuilder queryBuilder =
new SQLiteQueryBuilder();
queryBuilder.setTables(DBHelper.TABLE_NAME);
47
switch (uriMatcher.match(uri)) {
case FRIENDS:
break;
case FRIENDS_ID:
queryBuilder.appendWhere(
ProviderContract.ID + "=" + uri.getLastPathSegment());
break;
default:
throw new IllegalArgumentException("Unknown URI "+ uri);
}
if (sortOrder == null || sortOrder == "") {
sortOrder = ProviderContract.NAME;
}
Cursor cursor = queryBuilder.query(database, projection,
selection, selectionArgs, null, null, sortOrder);
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
48
@Override
public Uri insert (Uri uri, ContentValues values) {
SQLiteDatabase database = dbHelper.getWritableDatabase();
long row = database.insert(DBHelper.TABLE_NAME, "",
values);
if(row > 0) {
Uri newUri = ContentUris.withAppendedId(
ProviderContract.CONTENT_URI, row);
getContext().getContentResolver().notifyChange(
newUri, null);
return newUri;
}
throw new SQLException("Fail to add new record into " + uri);
}
49
@Override
public int update (Uri uri, ContentValues val,
String selection, String[] args){
SQLiteDatabase database = dbHelper.getWritableDatabase();
int count = 0;
switch (uriMatcher.match(uri)){
case FRIENDS:
count = database.update(
DBHelper.TABLE_NAME, val, selection, args);
break;
case FRIENDS_ID:
count = database.update(
DBHelper.TABLE_NAME, val, ProviderContract.ID
+ " = " + uri.getLastPathSegment()
+ (!TextUtils.isEmpty(selection) ? " AND ("
+ selection + ')' : ""), args);
break; 50
default:
throw new IllegalArgumentException(
"Unsupported URI "+ uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs){
SQLiteDatabase database = dbHelper.getWritableDatabase();
int count = 0;
switch (uriMatcher.match(uri)){
case FRIENDS:
count=database.delete(
DBHelper.TABLE_NAME, selection, selectionArgs);
break;
51
case FRIENDS_ID:
String id = uri.getLastPathSegment(); //gets the id
count = database.delete (DBHelper.TABLE_NAME,
ProviderContract.ID + " = " + id
+ (!TextUtils.isEmpty(selection) ? " AND ("
+ selection + ')' : ""), selectionArgs);
break;
default:
throw new IllegalArgumentException(
"Unsupported URI "+uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
52
@Override
public String getType (Uri uri) {
switch (uriMatcher.match(uri)){
// Get all friend-birthday records
case FRIENDS:
return "vnd.android.cursor.dir/vnd.example.friends";
// Get a particular friend
case FRIENDS_ID:
return "vnd.android.cursor.item/vnd.example.friends";
default:
throw new IllegalArgumentException("Err URI: " +
uri);
}
} 53
Content Provider Manifest File:

<provider android:name=
"com.bestapp.birthdayproviderapp.BirthdayProvider"
android:authorities="com.bestapp.BirthdayProvider"
android:exported="true">
</provider>

54
Client

Dr. Leon Jololian 55


56
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter name" />

Dr. Leon Jololian 57


<EditText
android:id="@+id/birthday"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/name"
android:layout_below="@+id/name"
android:ems="10"
android:hint="Enter birthday" />
<Button
android:id="@+id/btnAdd"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/birthday"
android:layout_below="@+id/birthday"
android:layout_marginTop="30dp"
android:onClick="addBirthday"
android:text="Add Birthday" />
58
<Button
android:id="@+id/btnShow"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnAdd"
android:layout_below="@+id/btnAdd"
android:layout_marginTop="20dp"
android:onClick="showAllBirthdays"
android:text="Show Birthdays" />
<Button
android:id="@+id/btnDelete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btnShow"
android:layout_alignLeft="@+id/btnShow"
android:layout_marginTop="20dp"
android:onClick="deleteAllBirthdays"
android:text="Delete All Birthdays" />
</RelativeLayout>
59
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void deleteAllBirthdays (View view) {


String URL= "content://com.bestapp.BirthdayProvider/friends";
Uri friends = Uri.parse(URL);
int count = getContentResolver().delete(friends, null, null);
Toast.makeText(getBaseContext(), " All records deleted: "
+ count, Toast.LENGTH_LONG).show();
}
60
public void showAllBirthdays (View view) {
String URL="content://com.bestapp.BirthdayProvider/friends";
Uri friends = Uri.parse(URL);
Cursor c = getContentResolver().query(
friends, null, null, null, "name");
String result = "Results:";
if (!c.moveToFirst()) {
Toast.makeText(this, result + "No content!",
Toast.LENGTH_LONG).show();
} else {
do{
result = result + "\n" + c.getString(c.getColumnIndex(
ProviderContract.NAME)) + " with id " + c.getString(
c.getColumnIndex(ProviderContract.ID)) +
" has birthday: " + c.getString(c.getColumnIndex(
ProviderContract.BIRTHDAY));
} while (c.moveToNext());
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
}
61
}
public void addBirthday (View view) {
ContentValues values = new ContentValues();
values.put(ProviderContract.NAME,
((EditText)findViewById(R.id.name)).getText().toString());
values.put(ProviderContract.BIRTHDAY,
((EditText)findViewById(R.id.birthday)).getText().toString());
Uri uri = getContentResolver().insert(
ProviderContract.CONTENT_URI, values);
Toast.makeText(getBaseContext(), uri.toString() +
"inserted!", Toast.LENGTH_LONG).show();
}
}

62
public class ProviderContract {
static final String PROVIDER_NAME=
"com.bestapp.BirthdayProvider";
static final String URL =
"content://"+PROVIDER_NAME+"/friends";
static final Uri CONTENT_URI = Uri.parse(URL);
static final String ID = "id";
static final String NAME = "name";
static final String BIRTHDAY = "birthday";
}

63

Вам также может понравиться