在数据库中保存了三个字段:id,name,url
首先实现数据库的操作类:代码如下
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int COLUMN_ID = 1;
public static final int COLUMN_INDEX = 0;
public static final int COLUMN_NAME = 2;
public static final int COLUMN_URL = 3;
public static final String ID_STRING = "id";
private static DatabaseHelper mDatabaseHelper = null;
public static final String NAME = "mydatabase.db";
public static final String TABLE_NAME = "web_broadcast";
private static final int VERSION = 1;
public static DatabaseHelper getDatabaseHelper(Context context) {
if (mDatabaseHelper == null) {
mDatabaseHelper = new DatabaseHelper(context);
}
return mDatabaseHelper;
}
private String TABLE_BROADCAST = "name";
private String TABLE_ID = ID_STRING;
private String TABLE_INDEX = "index_num";
private String TABLE_URL = "url";
// private String TABLE_NUM="_num";
// private String TABLE_DATA="_data";
private DatabaseHelper(Context context) {
super(context, NAME, null, VERSION);
// TODO Auto-generated constructor stub
}
/**
* /** 删除记录
*
*
*/
public void delete(String index) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME, "index_num=?", new String[] { index });
}
/**
* 添加数据
*/
public long insert(String id, String name, String url) {
SQLiteDatabase db = getWritableDatabase();// 获取可写SQLiteDatabase对象
// ContentValues类似map,存入的是键值对
ContentValues contentValues = new ContentValues();
contentValues.put(TABLE_ID, id);
contentValues.put(TABLE_BROADCAST, name);
contentValues.put(TABLE_URL, url);
return db.insert(TABLE_NAME, null, contentValues);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql = "CREATE TABLE " + TABLE_NAME + "(" + TABLE_INDEX
+ " INTEGER PRIMARY KEY AUTOINCREMENT," + TABLE_ID + " text,"
+ TABLE_BROADCAST + " text," + TABLE_URL + " text)";
// String sql = "CREATE TABLE "
// + TABLE_NAME
// + "(_idnum INTEGER PRIMARY KEY AUTOINCREMENT,_num text,_data text)";
db.execSQL(sql);// 需要异常捕获
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String sql = "drop table " + TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}
public Cursor query(String selection) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, null, selection, null, null, null,
"index_num desc");
return cursor;
}
/**
* 查询所有数据
*
* @return Cursor
*/
public Cursor select() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { "index_num",
TABLE_ID, TABLE_BROADCAST, TABLE_URL }, null, null, null, null,
"index_num desc"); // desc 降序排列,asc 升序排列
return cursor;
}
/**
* 更新记录的,跟插入的很像
*/
public void update(String index, String id, String name, String url) {
SQLiteDatabase db = getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(TABLE_ID, id);
contentValues.put(TABLE_BROADCAST, name);
contentValues.put(TABLE_URL, url);
db.update(TABLE_NAME, contentValues, "index_num=?",
new String[] { index });
}
}
然后实现一个ContentProvider
package com.tcl.kang;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
public class MyContentProvider extends ContentProvider
{
public static final String PROVIDER_NAME = "com.tcl.myprovider";
public static final Uri CONTENT_URI = Uri.parse("content://"
+ PROVIDER_NAME + "/urls");
public static final String _ID = DatabaseHelper.ID_STRING;
private static final int URLS = 1;
private static final int URL_ID = 2;
private static final UriMatcher uriMatcher;
private static final String DATABASE_TABLE = DatabaseHelper.TABLE_NAME;
private SQLiteDatabase mDb;
private DatabaseHelper mDbHelper;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
// 返回所有的
uriMatcher.addURI(PROVIDER_NAME, "urls", URLS);
// 返回指定的
uriMatcher.addURI(PROVIDER_NAME, "urls/#", URL_ID);
}
@Override
public boolean onCreate() {
Context context = getContext();
mDbHelper = DatabaseHelper.getDatabaseHelper(context);
Log.v("", "kang:mdb="+mDb);
return (mDb == null) ? false : true;
}
@Override
public String getType(Uri uri) {
switch (uriMatcher.match(uri)) {
// ---get all books---
case URLS:
return "vnd.android.cursor.dir/vnd.learn2develop.urls ";
// ---get a particular book---
case URL_ID:
return "vnd.android.cursor.item/vnd.learn2develop.urls ";
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
sqlBuilder.setTables(DATABASE_TABLE);
mDb = mDbHelper.getWritableDatabase();
if (uriMatcher.match(uri) == URL_ID)
// ---if getting a particular book---
sqlBuilder.appendWhere(_ID + " = " + uri.getPathSegments().get(1));
Cursor c = sqlBuilder.query(mDb, projection, selection, selectionArgs,
null, null, sortOrder);
// ---register to watch a content URI for changes---
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
mDb = mDbHelper.getReadableDatabase();
long rowID = mDb.insert(DATABASE_TABLE, "", values);
// ---if added successfully---
if (rowID > 0) {
Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
getContext().getContentResolver().notifyChange(_uri, null);
return _uri;
}
throw new SQLException("Failed to insert row into " + uri);
}
@Override
public int delete(Uri arg0, String arg1, String[] arg2) {
mDb = mDbHelper.getWritableDatabase();
int count = 0;
switch (uriMatcher.match(arg0)) {
case URLS:
count = mDb.delete(DATABASE_TABLE, arg1, arg2);
break;
case URL_ID:
String id = arg0.getPathSegments().get(1);
count = mDb.delete(DATABASE_TABLE, _ID + " = " + id
+ (!TextUtils.isEmpty(arg1) ? " AND (" + arg1 + ')' : ""),
arg2);
break;
default:
throw new IllegalArgumentException("Unknown URI " + arg0);
}
getContext().getContentResolver().notifyChange(arg0, null);
return count;
}
@Override
public int update(Uri uri, ContentValues values,
String selection, String[] selectionArgs)
{
mDb = mDbHelper.getWritableDatabase();
int count = 0;
switch (uriMatcher.match(uri)) {
case URLS:
count = mDb.update(
DATABASE_TABLE,
values,
selection,
selectionArgs);
break;
case URL_ID:
count = mDb.update(
DATABASE_TABLE,
values,
_ID + " = " + uri.getPathSegments().get(1) +
(!TextUtils.isEmpty(selection) ? " AND (" +
selection + ')' : ""),
selectionArgs);
break;
default:
throw new IllegalArgumentException(
"Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
贴上Manifest.xml,在其中添加provider字段
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tcl.kang"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ActivityMain"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider android:name="com.tcl.kang.MyContentProvider"
android:authorities="com.tcl.myprovider"
android:multiprocess="true"
/>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>
测试直接操作数据库:
package com.tcl.kang;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
public class ActivityMain extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper databaseHelper = DatabaseHelper.getDatabaseHelper(this);
databaseHelper.insert("1", "name1", "http://name1");
databaseHelper.insert("2", "name2", "http://name2");
databaseHelper.close();
}
}
测试用ContentProvider操作数据库
package com.tcl.testsql2;
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.widget.ImageView;
public class TestSql2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Uri uri = Uri.parse("content://"+ "com.tcl.myprovider" + "/urls");
ContentResolver resolver = getContentResolver();
ContentValues values = new ContentValues();
// values.put("id", "5");
// values.put("name", "name5");
// values.put("url", "http://name5");
// resolver.insert(uri, values);
Cursor cursor = resolver.query(uri, null, null, null, null);
}
}