ANDROID_MARS学习笔记_S01原始版_010_ContentProvider
一、简介
一、代码
1.xml
(1)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">
<Button android:id="@+id/insertButton" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="insert" />
<Button android:id="@+id/queryButton" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="query" />
</LinearLayout>
(2)AndroidManifest.xml.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.s01_original_e16_textcp"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".CPActivity"
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.example.s01_original_e16_textcp.FirstContentProvider"
android:authorities="tony.cp.FirstContentProvider" />
</application> </manifest>
2.java
(1)CPActivity.java
package com.example.s01_original_e16_textcp; import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button; import com.example.s01_original_e16_textcp.FirstProviderMetaData.UserTableMetaData; public class CPActivity extends Activity {
/** Called when the activity is first created. */
private Button insertButton = null;
private Button queryButton = null; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
insertButton = (Button) findViewById(R.id.insertButton);
insertButton.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
ContentValues values = new ContentValues();
values.put(FirstProviderMetaData.UserTableMetaData.USER_NAME,
"zhangsan");
Uri uri = getContentResolver().insert(
FirstProviderMetaData.UserTableMetaData.CONTENT_URI,
values);
System.out.println("uri ---> " + uri.toString());
}
});
queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
Cursor c = getContentResolver().query(
FirstProviderMetaData.UserTableMetaData.CONTENT_URI,
null, null, null, null);
while (c.moveToNext()) {
System.out.println(c.getString(c
.getColumnIndex(UserTableMetaData.USER_NAME)));
} }
});
}
}
(2)FirstContentProvider.java
package com.example.s01_original_e16_textcp; import java.util.HashMap; import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
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 com.example.s01_original_e16_textcp.FirstProviderMetaData.UserTableMetaData; public class FirstContentProvider extends ContentProvider { // UriMatcher用来检查URI是否合法
public static final UriMatcher uriMatcher;
public static final int INCOMING_USER_COLLECTION = 1;
public static final int INCOMING_USER_SINGLE = 2; private DatabaseHelper dh; static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(FirstProviderMetaData.AUTHORITY, "users",
INCOMING_USER_COLLECTION);
uriMatcher.addURI(FirstProviderMetaData.AUTHORITY, "users/#",
INCOMING_USER_SINGLE);
} //相当于给sql的列起别名
public static HashMap<String, String> userProjectionMap;
static {
userProjectionMap = new HashMap<String, String>();
userProjectionMap.put(UserTableMetaData._ID, UserTableMetaData._ID);
userProjectionMap.put(UserTableMetaData.USER_NAME,
UserTableMetaData.USER_NAME);
} @Override
public int delete(Uri arg0, String arg1, String[] arg2) {
// TODO Auto-generated method stub
System.out.println("delete...");
return 0;
} // 根据传入的URI,返回该URI所表示的数据类型
@Override
public String getType(Uri uri) {
System.out.println("getType...");
switch (uriMatcher.match(uri)) {
case INCOMING_USER_COLLECTION:
return UserTableMetaData.CONTENT_TYPE;
case INCOMING_USER_SINGLE:
return UserTableMetaData.CONTENT_TYPE_ITEM;
default:
throw new IllegalArgumentException("Unknow URI " + uri);
}
} /**
* 该函数的返回值是一个Uri,这个Uri表示的是刚刚那使用这个函数所插入的数据
* content://ycitss.cp.firstContentProivder/users/1
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
System.out.println("insert...");
SQLiteDatabase db = dh.getWritableDatabase();
long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);
if (rowId > 0) {
Uri insertedUserUri = ContentUris.withAppendedId(
UserTableMetaData.CONTENT_URI, rowId);
// 通知监听器,数据已经修改
getContext().getContentResolver().notifyChange(insertedUserUri,
null);
return insertedUserUri;
}
throw new SQLException("Failed to insert row into " + uri);
} // 是一个回调方法,所以说在ContentProvider创建的时候执行
@Override
public boolean onCreate() {
dh = new DatabaseHelper(getContext(),
FirstProviderMetaData.DATABASE_NAME);
System.out.println("onCreate...");
return true;
} @Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (uriMatcher.match(uri)) {
case INCOMING_USER_COLLECTION:
qb.setTables(UserTableMetaData.TABLE_NAME);
qb.setProjectionMap(userProjectionMap);
break;
case INCOMING_USER_SINGLE:
qb.setTables(UserTableMetaData.TABLE_NAME);
qb.setProjectionMap(userProjectionMap);
qb.appendWhere(UserTableMetaData._ID + "="
+ uri.getPathSegments().get(1));
break;
}
String orderBy;
if (TextUtils.isEmpty(sortOrder)) {
orderBy = UserTableMetaData.DEFAULT_SORT_ORDER;
} else {
orderBy = sortOrder;
}
SQLiteDatabase db = dh.getWritableDatabase();
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, orderBy);
c.setNotificationUri(getContext().getContentResolver(), uri);
System.out.println("query...");
return c;
} @Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
System.out.println("update...");
return 0;
} }
(3)FirstProviderMetaData.java
package com.example.s01_original_e16_textcp; import android.net.Uri;
import android.provider.BaseColumns; public class FirstProviderMetaData {
// 必需与AndroidManifest.xml中定义的android:authorities一致
public static final String AUTHORITY = "tony.cp.FirstContentProvider";
// 数据库名称
public static final String DATABASE_NAME = "FirstProvider.db";
// 数据库版本
public static final int DATABASE_VERSION = 1;
// 表名
public static final String USERS_TABLE_NAME = "users"; public static final class UserTableMetaData implements BaseColumns {
// 表名
public static final String TABLE_NAME = "users";
// 访问该ContentProvider的URI
public static final Uri CONTENT_URI = Uri.parse("content://"
+ AUTHORITY + "/users");
// 该contentProvider所返回的数据类型的定义
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.firstprovider.user";//访问整张表
public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.firstprovider.user";//取一条数据
// 列名
public static final String USER_NAME = "name";
// 默认的排序方法
public static final String DEFAULT_SORT_ORDER = "_id desc";
}
}
(4)DatabaseHelper.java
package com.example.s01_original_e16_textcp; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper {
private static final int VERSION = 1; public DatabaseHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
} public DatabaseHelper(Context context, String name, int version) {
this(context, name, null, version);
} public DatabaseHelper(Context context, String name) {
this(context, name, VERSION);
} // 该函数是在第一次创建数据库的时候执行,实际上是在第一次得到SQLiteDAtabase对象的时候,才会调用这个方法
@Override
public void onCreate(SQLiteDatabase db) {
System.out.println("cteate a Database");
// execSQL函数用于执行SQL语句
db.execSQL("create table " + FirstProviderMetaData.USERS_TABLE_NAME
+ "(" + FirstProviderMetaData.UserTableMetaData._ID
+ " INTEGER_PARIMARY_AUTOINCREMENT,"
+ FirstProviderMetaData.UserTableMetaData.USER_NAME
+ " varchar(20))");
} @Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
System.out.println("update a Database");
} }
ANDROID_MARS学习笔记_S01原始版_010_ContentProvider的更多相关文章
- ANDROID_MARS学习笔记_S01原始版_005_RadioGroup\CheckBox\Toast
一.代码 1.xml(1)radio.xml <?xml version="1.0" encoding="utf-8"?> <LinearLa ...
- ANDROID_MARS学习笔记_S01原始版_004_TableLayout
1.xml <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android ...
- ANDROID_MARS学习笔记_S01原始版_003_对话框
1.AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest ...
- ANDROID_MARS学习笔记_S01原始版_002_实现计算乘积及menu应用
一.代码 1.xml(1)activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk ...
- ANDROID_MARS学习笔记_S01原始版_001_Intent
一.Intent简介 二.代码 1.activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.co ...
- ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER005_用广播BroacastReciever实现后台播放不更新歌词
一.代码流程1.自定义一个AppConstant.LRC_MESSAGE_ACTION字符串表示广播"更新歌词" 2.在PlayerActivity的onResume()注册Bro ...
- ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER004_同步显示歌词
一.流程分析 1.点击播放按钮,会根据lrc名调用LrcProcessor的process()分析歌词文件,得到时间队列和歌词队列 2.new一个hander,把时间队列和歌词队列传给自定义的线程类U ...
- ANDROID_MARS学习笔记_S01原始版_023_MP3PLAYER003_播放mp3
一.简介 1.在onListItemClick中实现点击条目时,跳转到PlayerActivity,mp3info通过Intent传给PlayerActivity 2.PlayerActivity通过 ...
- ANDROID_MARS学习笔记_S01原始版_022_MP3PLAYER002_本地及remote标签
一.简介 1.在main.xml中用TabHost.TabWidget.FrameLayout标签作布局 2.在MainActivity中生成TabHost.TabSpec,调用setIndicato ...
随机推荐
- Java 简单算法--打印回文数字
package cn.magicdu.algorithm; public class CircleNumber { public static void main(String[] args) { f ...
- HttpClient的使用
HttpClient的使用 一.简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTT ...
- 编译gd-2.0.35.tar.gz时报错:gd_png.c:16:53: error: png.h: No such file or directory
编译gd-2.0.35.tar.gz时报错: gcc -DHAVE_CONFIG_H -I. -I. -I. -I/usr/local/freetype/include/freetype2 -I/us ...
- IOS-用动画组制作花瓣掉落效果(另附iOS动画图表)
重要的两个方法:1.动画的数组:animations 2.启动的时间 beginTime 注意:动画组设置了持续时间(duration)可能会导致动画组里面的持续时间不管用 代码如下: #import ...
- C# ACM poj1007
求逆序数,快排 public static void acm1007(int a, string[] c) { Dictionary<int, string> dic = new Dict ...
- Mysql存储引擎__笔记
Mysql存储引擎(表类型): Mysql数据库: 通常意义上,数据库也就是数据的集合,具体到计算机上数据库可以使存储器上一些文件的集合或者一些内存 数据的内存数据的集合. Mysql数据库是开放源代 ...
- call_user_func
(PHP 4, PHP 5) call_user_func — 把第一个参数作为回调函数调用 mixed call_user_func ( callable $callback [, mixed $p ...
- Linux C 程序 基础语法(1)
1.Linux 下第一支C程序,控制台打印一句话. vi first.c //linux新建文件 #include<stdio.h> int main() { printf("w ...
- [HttpClient]SSL双向实例
package com.jerry.httpclient; import java.io.File; import java.io.FileInputStream; import java.secur ...
- struct--file_operations
struct--file_operations----------------------------------------- struct file_operations是一个字符设备把驱动 ...