软件世界网 购物 网址 三丰软件 | 小说 美女秀 图库大全 游戏 笑话 | 下载 开发知识库 新闻 开发 图片素材
多播视频美女直播
↓电视,电影,美女直播,迅雷资源↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
移动开发 架构设计 编程语言 Web前端 互联网
开发杂谈 系统运维 研发管理 数据库 云计算 Android开发资料
  软件世界网 -> 移动开发 -> 扣丁学堂笔记第17天ContentProvider组件与Loaders -> 正文阅读
移动开发 最新文章
深入了解android中的消息机制Handler
Android
Libgdx之BitmapFont字体
AndroidApp发布到应用市场的流程
Android开发找工作之前先看看这些知识点吧
View的事件分发机制解析
简单介绍了解白鹭引擎Egret
Cocos2d
android获取本地图片(二)
动画特效七:碰撞动画

[移动开发]扣丁学堂笔记第17天ContentProvider组件与Loaders

  2016-04-02 20:53:17

1.ContentProvider简介与准备工作



首先自定义ContentProvider类继承自ContentProvider,实现它的6个方法;
然后创建一个DatabaseAdapter类,创建一个DatabaseHelper继承自SQLiteOpenHelper,重写它的构造方法和实现2个方法
然后再DatabaseAdapter类中添加增删改查方法的代码;
然后在清单文件中注册ContentProvider

2.ContentProvider定义匹配器与添加数据
3.ContentProvider删除修改查询方法与数据类型
4.ContentProvider调用内容提供器
PersonMetaData.java
package com.example.contentprovidertest;

import android.provider.BaseColumns;

public final class PersonMetaData {

	private PersonMetaData(){}
	public static abstract class PersonTable implements BaseColumns{
		public static final String TABLE_NAME = "table_name";
		public static final String NAME = "name";
		public static final String AGE = "age";
	}
}

DatabaseAdapter
package com.example.contentprovidertest;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseAdapter {

	private DatabaseHelper dbHelper;

	public DatabaseAdapter(Context context) {
		dbHelper = new DatabaseHelper(context);
	}

	public void save(Person person) {
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(PersonMetaData.PersonTable.NAME, person.getName());
		values.put(PersonMetaData.PersonTable.AGE, person.getAge());
		db.insert(PersonMetaData.PersonTable.TABLE_NAME, null, values);
		db.close();
	}
	
	public void delete(int id){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(PersonMetaData.PersonTable.TABLE_NAME, PersonMetaData.PersonTable._ID+"=?", 
				new String[]{String.valueOf(id)});
		db.close();
	}

	public void update(Person person){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put(PersonMetaData.PersonTable.NAME, person.getName());
		values.put(PersonMetaData.PersonTable.AGE, person.getAge());
		db.update(PersonMetaData.PersonTable.TABLE_NAME, values, PersonMetaData.PersonTable._ID+"=?", 
				new String[]{String.valueOf(person.getId())});
		db.close();
	}
	
	public ArrayList<Person> findAll(){
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor c = db.query(PersonMetaData.PersonTable.TABLE_NAME, null, null, null, null, null, null);
		ArrayList<Person> list = new ArrayList<Person>();
		Person p = null;
		while(c.moveToNext()){
			p.setId(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.PersonTable._ID)));
			p.setName(c.getString(c.getColumnIndexOrThrow(PersonMetaData.PersonTable.NAME)));
			p.setAge(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.PersonTable.AGE)));
			list.add(p);
		}
		c.close();
		db.close();
		return list;
		
	}
	
	public Person findById(int id){
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor c = db.query(PersonMetaData.PersonTable.TABLE_NAME, null, PersonMetaData.PersonTable._ID+"=?", new String[]{String.valueOf(id)}, null, null, null);
		Person p = null;
		if(c.moveToNext()){
			p.setId(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.PersonTable._ID)));
			p.setName(c.getString(c.getColumnIndexOrThrow(PersonMetaData.PersonTable.NAME)));
			p.setAge(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.PersonTable.AGE)));
		}
		c.close();
		db.close();
		return p;
		
	}
	
	public class DatabaseHelper extends SQLiteOpenHelper {

		private static final String DB_NAME = "cp.db";
		private static final int VERSION = 1;
		private static final String CRETATE_TABLE = "CREATE TABLE person(_id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,age INTEGER)";
		private static final String DROP_TABLE = "DROP TABLE IF EXISTS person";

		public DatabaseHelper(Context context) {
			super(context, DB_NAME, null, VERSION);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			// TODO Auto-generated method stub
			db.execSQL(CRETATE_TABLE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			// TODO Auto-generated method stub
			db.execSQL(DROP_TABLE);
			db.execSQL(CRETATE_TABLE);
		}

	}
}

MyContentProvider
package com.example.contentprovidertest;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class MyContentProvider extends ContentProvider{

	
	private static final String AUTHORITY = "com.example.contentprovidertest.mycontentprovider";
	private static final int SINGLE_CODE = 1;//返回单个记录匹配码
	private static final int MUTIPLE_CODE = 2;//返回多个记录匹配码

	private static final String SINGLE_TYPE = "vnd.android.cursor.item/person";
	private static final String MUTIPLE_TYPE = "vnd.android.cursor.dir/person";
	//创建一个uri匹配器
	private static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	static{
		uriMatcher.addURI(AUTHORITY, "person", MUTIPLE_CODE);
		uriMatcher.addURI(AUTHORITY, "person/#", SINGLE_CODE);
	}
	
	private DatabaseAdapter.DatabaseHelper dbHelper; 
	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		dbHelper = new DatabaseAdapter.DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		switch(uriMatcher.match(uri)){
		case SINGLE_CODE:
			SQLiteDatabase db = dbHelper.getReadableDatabase();
			long id = ContentUris.parseId(uri);
			selection = PersonMetaData.PersonTable._ID+"=?";
			selectionArgs = new String[]{String.valueOf(id)};
			return db.query(true, PersonMetaData.PersonTable.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder,null);
		case MUTIPLE_CODE:
			db = dbHelper.getReadableDatabase();
			return db.query(true, PersonMetaData.PersonTable.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder,null);	
		}
		
		return null;
	}

	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		switch(uriMatcher.match(uri)){
		case SINGLE_CODE:
			return SINGLE_TYPE;
		case MUTIPLE_CODE:
			return MUTIPLE_TYPE;
		}
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		switch(uriMatcher.match(uri)){
			case MUTIPLE_CODE:
				SQLiteDatabase db = dbHelper.getWritableDatabase();
				long id = db.insert(PersonMetaData.PersonTable.TABLE_NAME, null, values);
				uri = ContentUris.withAppendedId(uri, id);
				db.close();
				break;
			
		}
		return uri;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		switch(uriMatcher.match(uri)){
		case MUTIPLE_CODE:
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			long id = ContentUris.parseId(uri);
			selection = PersonMetaData.PersonTable._ID+"=?";
			selectionArgs = new String[]{String.valueOf(id)};
			int row = db.delete(PersonMetaData.PersonTable.NAME, selection, selectionArgs);
			db.close();
			return row;
		case SINGLE_CODE:
			db = dbHelper.getWritableDatabase();
			row = db.delete(PersonMetaData.PersonTable.NAME, selection, selectionArgs);
			db.close();
			return row;
		}
		return 0;
		
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		switch(uriMatcher.match(uri)){
		case MUTIPLE_CODE:
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			long id = ContentUris.parseId(uri);
			selection = PersonMetaData.PersonTable._ID+"=?";
			selectionArgs = new String[]{String.valueOf(id)};
			int row = db.update(PersonMetaData.PersonTable.NAME,values, selection, selectionArgs);
			db.close();
			return row;
		case SINGLE_CODE:
			db = dbHelper.getWritableDatabase();
			row = db.update(PersonMetaData.PersonTable.NAME,values, selection, selectionArgs);
			db.close();
			return row;
		}
		return 0;
		
	}

}

MainActivity
package com.example.contentprovidertest;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;


public class MainActivity extends Activity {

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


   public void addClick(View view){
	   ContentResolver cr = this.getContentResolver();
	   //调用cp的添加方法
	   Uri uri = Uri.parse("content://com.example.contentprovidertest.mycontentprovider/person");
	   ContentValues values = new ContentValues();
	   values.put(PersonMetaData.PersonTable.NAME, "Jack");
	   values.put(PersonMetaData.PersonTable.AGE,18);
	   cr.insert(uri, values);
   }
   
   public void deleteClick(View view){
	   ContentResolver cr = this.getContentResolver();
	   //调用cp的添加方法
	   Uri uri = Uri.parse("content://com.example.contentprovidertest.mycontentprovider/person1");
	   cr.delete(uri, null, null);
   }
   
   public void updateClick(View view){
	   ContentResolver cr = this.getContentResolver();
	   //调用cp的添加方法
	   Uri uri = Uri.parse("content://com.example.contentprovidertest.mycontentprovider/person1");
	   ContentValues values = new ContentValues();
	   values.put(PersonMetaData.PersonTable.NAME, "Jack");
	   values.put(PersonMetaData.PersonTable.AGE,20);
	   cr.update(uri, values, null, null);
   }
   
   public void queryClick(View view){
	   ContentResolver cr = this.getContentResolver();
	   //调用cp的添加方法
	   Uri uri = Uri.parse("content://com.example.contentprovidertest.mycontentprovider/person1");
	   Cursor c = cr.query(uri, null, null, null, null);
	   while(c.moveToNext()){
		   System.out.println(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.PersonTable._ID)));
		   System.out.println(c.getString(c.getColumnIndexOrThrow(PersonMetaData.PersonTable.NAME)));
		   System.out.println(c.getInt(c.getColumnIndexOrThrow(PersonMetaData.PersonTable.AGE)));
	   }
	   c.close();
   }
}

activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.contentprovidertest.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:text="add"
        android:onClick="addClick" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/button1"
        android:layout_below="@+id/button1"
        android:text="delete"
        android:onClick="deleteClick" />

    <Button
        android:id="@+id/button3"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignRight="@+id/button2"
        android:layout_below="@+id/button2"
        android:text="update"
        android:onClick="updateClick" />

    <Button
        android:id="@+id/button4"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/button3"
        android:layout_below="@+id/button3"
        android:text="query"
        android:onClick="queryClick" />

</RelativeLayout>

AndroidMainfest
<provider android:name=".MyContentProvider"
            android:authorities="com.example.contentprovidertest.mycontentprovider"/>

5.ContentProvider访问联系人







6.Loaders概述与准备


7.使用CursorLoader加载数据

8.Loaders_自定义AsyncTaskLoader加载数据

详见:http://blog.csdn.net/dt235201314/article/details/50512749
上一篇文章      下一篇文章      查看所有文章
2016-04-02 20:51:48  
360图书馆 论文大全 母婴/育儿 软件开发资料 网页快照 文字转语音 购物精选 软件 美食菜谱 新闻中心 电影下载 小游戏 Chinese Culture
生肖星座解梦 三沣玩客 拍拍 视频 开发 Android开发 站长 古典小说 网文精选 搜图网 天下美图 中国文化英文 多播视频 装修知识库
2017-1-20 11:48:27
多播视频美女直播
↓电视,电影,美女直播,迅雷资源↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  软件世界网 --