ContentProvider 的使用(2)

[b]ContentProvider 的使用(2)[/b]

紧接上文ContentProvider 的使用(1),我们开发一个有界面的Activity 来访问之前定义好的ContentProvider,并显示相应数据:
1)新建android 项目,项目名称为:ContentResolverDemo;
2)和ContentProvider 的使用(1)中一样,定义一个相同的实体类:Employee:
/*
* Copyright (C) Mesada Technologies Co., Ltd. 2005-2011.
* All rights reserved.
*
* This software is the confidential and proprietary information
* of Mesada Technologies Co., Ltd. ("Confidential Information").
* You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement
* you entered into with Mesada.
*/
package com.mesada.demo;

import android.net.Uri;

/**
* 实体类,封装了相关的一些常量信息.
*
* @author Xiaolong Long
* @date 2011-3-10
* @version 1.0
*/
public class Employee {

public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";
public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";
public static final String MIME_ITEM = "vnd.mesada.employee";
public static final String MIME_TYPE_SINGLE = MIME_ITEM_PREFIX + "/"
+ MIME_ITEM;
public static final String MIME_TYPE_MULTIPLE = MIME_DIR_PREFIX + "/"
+ MIME_ITEM;
public static final String AUTHORITY = "com.mesada.demo.provider.employeeprovider";
public static final String PATH_SINGLE = "employee/#";
public static final String PATH_MULTIPLE = "employee";
public static final String STR = "content://" + AUTHORITY + "/"
+ PATH_MULTIPLE;
public static final Uri CONTENT_URI = Uri.parse(STR);

public static final String ID = "_id";
public static final String NAME = "name";
public static final String AGE = "age";
}

3)继承自Activity并实现 View.OnClickListener 接口的类的代码如下所示:
package com.mesada.demo;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
* This is a demo about access ContentProvider.
*
* @author Xiaolong Long
* @date 2010-12-30
* @version 1.0
*/
public class MainActivity extends Activity implements OnClickListener {

private static final String TAG = "MainActivity";
private static final boolean isDebug = true;

EditText mUserNameView;
EditText mAgeView;
EditText mIdView;

TextView mDataView;

Button mAddView;
Button mDisplayAllView;
Button mEmptyScreenView;
Button mDeleteAllView;
Button mDeleteByIdView;
Button mQueryByIdView;
Button mUpdateByIdView;

ContentResolver mContentResolver;

int counts = 0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
if (isDebug)
Log.i(TAG, "onCreate()...");

super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupControls();

mContentResolver = getContentResolver();

/* Register callbacks to be invoked when the view is clicked. */
mAddView.setOnClickListener(this);
mDeleteAllView.setOnClickListener(this);
mDisplayAllView.setOnClickListener(this);
mEmptyScreenView.setOnClickListener(this);
mDeleteByIdView.setOnClickListener(this);
mQueryByIdView.setOnClickListener(this);
mUpdateByIdView.setOnClickListener(this);

mDataView.setText(getString(R.string.no_data));
}

/**
*
* Finds the views that was identified by the id attribute from the XML.
*
* @param
* @return
* @date 2011-3-10
* @author Xiaolong Long
*/
private void setupControls() {
if (isDebug)
Log.i(TAG, "setupControls()...");

mUserNameView = (EditText) findViewById(R.id.userName);
mAgeView = (EditText) findViewById(R.id.age);
mIdView = (EditText) findViewById(R.id.id);

mDataView = (TextView) findViewById(R.id.data);

mAddView = (Button) findViewById(R.id.addOneRecord);
mDeleteAllView = (Button) findViewById(R.id.deleteAll);
mDisplayAllView = (Button) findViewById(R.id.displayAll);
mEmptyScreenView = (Button) findViewById(R.id.emptyScreen);
mDeleteByIdView = (Button) findViewById(R.id.deleteByID);
mQueryByIdView = (Button) findViewById(R.id.queryByID);
mUpdateByIdView = (Button) findViewById(R.id.updateByID);
}

public void onClick(View v) {
if (isDebug)
Log.i(TAG, "onClick(View v)...");

int id = v.getId();
switch (id) {
// To insert a row into the database.
case R.id.addOneRecord:
addOneRecord();
break;
// To delete rows in the database.
case R.id.deleteAll:
deleteAllRecords();
break;
// Show all data from the table.
case R.id.displayAll:
displayAll();
break;
// Sets the string value of the View.
case R.id.emptyScreen:
emptyScreen();
break;
// About to delete a row.
case R.id.deleteByID:
deleteByID();
break;
// Show the data from the table.
case R.id.queryByID:
queryByID();
break;
// To update rows in the database.
case R.id.updateByID:
updateByID();
break;
default:
break;
}
}

/**
*
* To update rows in the database.
*
* @param
* @return
* @date 2011-3-11
* @author Xiaolong Long
*/
private void updateByID() {
if (isDebug)
Log.i(TAG, "updateByID()...");

String userName = null;
String str1 = null;
String str2 = null;
userName = String.valueOf(mUserNameView.getText()).trim();
str1 = String.valueOf(mAgeView.getText()).trim();
str2 = String.valueOf(mIdView.getText()).trim();

if (!(userName.length() > 0) || !(str1.length() > 0)
|| !(str2.length() > 0)) {
Toast.makeText(this, getString(R.string.cannot_be_null),
Toast.LENGTH_SHORT).show();
return;
} else {
long id = Long.parseLong(str2);
Uri uri = Uri.parse(Employee.STR + "/" + id);
Cursor cursor = mContentResolver.query(uri, null, null, null, null);
if (cursor == null || cursor.getCount() == 0) {
mDataView.setText("ID 为" + id + "的记录没有找到.");
return;
}
ContentValues values = new ContentValues();
values.put(Employee.NAME, userName);
values.put(Employee.AGE, str1);
mContentResolver.update(uri, values, null, null);
Toast.makeText(this, getString(R.string.operation_successful),
Toast.LENGTH_SHORT).show();
displayAll();
}
}

/**
*
* Show the data from the table.
*
* @param
* @return
* @date 2011-3-11
* @author Xiaolong Long
*/
private void queryByID() {
if (isDebug)
Log.i(TAG, "queryByID()...");

String str = null;
str = String.valueOf(mIdView.getText()).trim();
if (!(str.length() > 0)) {
Toast.makeText(this, getString(R.string.cannot_be_null),
Toast.LENGTH_SHORT).show();
return;
} else {
long id = Long.parseLong(str);
Uri uri = Uri.parse(Employee.STR + "/" + id);
Cursor cursor = mContentResolver.query(uri, null, null, null, null);
System.err.println("queryByID()-->" + cursor.getCount());
if (cursor == null || cursor.getCount() == 0) {
mDataView.setText("数据库中没有数据");
return;
}

StringBuffer appStr = new StringBuffer();
if (cursor.moveToFirst()) {
appStr.append("\t\t编号: "
+ cursor.getInt(cursor.getColumnIndex(Employee.ID))
+ ",\t\t\t姓名: "
+ cursor.getString(cursor.getColumnIndex(Employee.NAME))
+ ",\t\t\t年龄: "
+ cursor.getInt(cursor.getColumnIndex(Employee.AGE))
+ "\n");
}
mDataView.setText(appStr);
}
}

/**
*
* Delete special rows in the database.
*
* @param
* @return
* @date 2011-3-11
* @author Xiaolong Long
*/
private void deleteByID() {
if (isDebug)
Log.i(TAG, "deleteByID()...");

String str = null;
str = String.valueOf(mIdView.getText()).trim();
if (!(str.length() > 0)) {
Toast.makeText(this, getString(R.string.cannot_be_null),
Toast.LENGTH_SHORT).show();
return;
} else {
long id = Long.parseLong(str);
Uri uri = Uri.parse(Employee.STR + "/" + id);
Cursor cursor = mContentResolver.query(uri, null, null, null, null);
System.err.println("deleteByID-->" + cursor.getCount());
if (cursor == null || cursor.getCount() == 0) {
System.err.println("deleteByID-->" + cursor.getCount());
mDataView.setText("数据库中没有数据");
return;
} else {
mContentResolver.delete(uri, null, null);
Toast.makeText(this, getString(R.string.operation_successful),
Toast.LENGTH_SHORT).show();
displayAll();
}
}
}
/**
*
* Sets the string value of the View.
*
* @param
* @return
* @date 2011-3-15
* @author Xiaolong Long
*/
private void emptyScreen() {
mUserNameView.setText("");
mAgeView.setText("");
mIdView.setText("");
mDataView.setText(getString(R.string.no_data));
}

/**
*
* Show all data from the table.
*
* @param
* @return
* @date 2011-3-11
* @author Xiaolong Long
*/
private void displayAll() {
if (isDebug)
Log.i(TAG, "displayAll()...");

Cursor cursor = mContentResolver.query(Employee.CONTENT_URI, null,
null, null, null);

// counts = cursor.getCount();
if (cursor == null || cursor.getCount() == 0) {
mDataView.setText("数据库中没有数据");
return;
} else {
StringBuffer appStr = new StringBuffer();
if (cursor.moveToFirst()) {
do {
appStr.append("\t编号: "
+ cursor.getInt(cursor.getColumnIndex(Employee.ID))
+ ",\t\t\t姓名: "
+ cursor.getString(cursor
.getColumnIndex(Employee.NAME))
+ ",\t\t\t年龄: "
+ cursor.getInt(cursor.getColumnIndex(Employee.AGE))
+ "\n");
} while (cursor.moveToNext());
}
mDataView.setText(appStr);
}

}
/**
*
* Removes data from the table.
*
* @param
* @return
* @date 2011-3-11
* @author Xiaolong Long
*/
private void deleteAllRecords() {
if (isDebug)
Log.i(TAG, "deleteAllRecords()...");

Cursor cursor = mContentResolver.query(Employee.CONTENT_URI, null,
null, null, null);
if (cursor == null || cursor.getCount() == 0) {
Toast.makeText(this, getString(R.string.no_data),
Toast.LENGTH_SHORT).show();
return;
} else {
mContentResolver.delete(Employee.CONTENT_URI, null, null);
Toast.makeText(this, getString(R.string.operation_successful),
Toast.LENGTH_SHORT).show();
emptyScreen();
}
}
/**
*
* Insert one record to the table which called employee.
*
* @param
* @return
* @date 2011-3-11
* @author Xiaolong Long
*/
private void addOneRecord() {
if (isDebug)
Log.i(TAG, "addOneRecord()...");

String userName = null;
String str = null;

userName = String.valueOf(mUserNameView.getText()).trim();
str = String.valueOf(mAgeView.getText()).trim();
if (!(userName.length() > 0) || !(str.length() > 0)) {
Toast.makeText(this, getString(R.string.cannot_be_null),
Toast.LENGTH_SHORT).show();
return;
} else {
try {
ContentValues values = new ContentValues();
values.put(Employee.NAME, userName);
values.put(Employee.AGE, Integer.parseInt(str));
mContentResolver.insert(Employee.CONTENT_URI, values);
Toast.makeText(this, getString(R.string.operation_successful),
Toast.LENGTH_SHORT).show();
emptyScreen();
displayAll();
} catch (Exception e) {
Toast.makeText(this, getString(R.string.operation_failed),
Toast.LENGTH_SHORT).show();
}

}
}
}
4)main.xml 文件的代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="@string/name" />
<EditText
android:id="@+id/userName"
android:layout_width="370px"
android:layout_height="wrap_content"
android:singleLine="true"></EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="100px"
android:layout_height="wrap_content"
android:text="@string/age" />
<EditText
android:id="@+id/age"
android:layout_width="370px"
android:layout_height="wrap_content"
android:singleLine="true"
android:numeric="integer"></EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/addOneRecord"
android:text="@string/add"
android:layout_width="120px"
android:layout_height="wrap_content"></Button>
<Button
android:id="@+id/displayAll"
android:text="@string/display_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
<Button
android:text="@string/empty_screen"
android:id="@+id/emptyScreen"
android:layout_width="120px"
android:layout_height="wrap_content"></Button>
<Button
android:text="@string/delete_all"
android:id="@+id/deleteAll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></Button>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:text="@string/conditional_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<EditText
android:id="@+id/id"
android:layout_width="370px"
android:layout_height="wrap_content"
android:numeric="integer"></EditText>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button
android:text="@string/delete_id"
android:id="@+id/deleteByID"
android:layout_width="150px"
android:layout_height="wrap_content"></Button>
<Button
android:id="@+id/queryByID"
android:text="@string/query_id"
android:layout_width="150px"
android:layout_height="wrap_content"></Button>
<Button
android:id="@+id/updateByID"
android:text="@string/update_id"
android:layout_width="150px"
android:layout_height="wrap_content"></Button>
</LinearLayout>
<TextView
android:text="@string/txt_display_all"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TextView>
<TextView
android:id="@+id/data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>

好了,ContentProvider 的应用的例子开发已经完毕,其可以实现对数据的增删改查的所有功能,顺便上传截图如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值