软件世界网 购物 网址 三丰软件 | 小说 美女秀 图库大全 游戏 笑话 | 下载 开发知识库 新闻 开发 图片素材
多播视频美女直播
↓电视,电影,美女直播,迅雷资源↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
移动开发 架构设计 编程语言 Web前端 互联网
开发杂谈 系统运维 研发管理 数据库 云计算 Android开发资料
  软件世界网 -> 移动开发 -> 扣丁学堂笔记第17天ContentProvider组件与Loaders -> 正文阅读

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


1.ContentProvider简介与准备工作
[img]http://img.blog.csdn.net/20160401183550755?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
[img]http://img.blog.csdn.net/20160401184108476[img]http://img.blog.csdn.net/20160401194218093[img]http://img.blog.csdn.net/20160401194250484
[img]http://img.blog.csdn.net/20160401184116195
首先自定义ContentProvider类继承自ContentProvider,实现它的6个方法;
然后创建一个DatabaseAdapter类,创建一个DatabaseHelper继承自SQLiteOpenHelper,重写它的构造方法和实现2个方法
然后再DatabaseAdapter类中添加增删改查方法的代码;
然后在清单文件中注册ContentProvider
[img]http://img.blog.csdn.net/20160401194921080[img]http://img.blog.csdn.net/20160401194952830
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访问联系人
[img]http://img.blog.csdn.net/20160401211822192
[img]http://img.blog.csdn.net/20160401212051584[img]http://img.blog.csdn.net/20160401212121287
[img]http://img.blog.csdn.net/20160401212246725[img]http://img.blog.csdn.net/20160401212252522
[img]http://img.blog.csdn.net/20160401212407507
[img]http://img.blog.csdn.net/20160401212459945
[img]http://img.blog.csdn.net/20160401212545273
[img]http://img.blog.csdn.net/20160401212624102
6.Loaders概述与准备
[img]http://img.blog.csdn.net/20160402082256078[img]http://img.blog.csdn.net/20160402082327953[img]http://img.blog.csdn.net/20160402082401047
[img]http://img.blog.csdn.net/20160402084129569[img]http://img.blog.csdn.net/20160402084134554[img]http://img.blog.csdn.net/20160402084139382[img]http://img.blog.csdn.net/20160402084144616[img]http://img.blog.csdn.net/20160402084159288[img]http://img.blog.csdn.net/20160402084205038[img]http://img.blog.csdn.net/20160402084209648[img]http://img.blog.csdn.net/20160402084213773
7.使用CursorLoader加载数据
[img]http://img.blog.csdn.net/20160402084229335[img]http://img.blog.csdn.net/20160402084302820
8.Loaders_自定义AsyncTaskLoader加载数据
[img]http://img.blog.csdn.net/20160402084359086
详见:http://blog.csdn.net/dt235201314/article/details/50512749
......显示全文...
    点击查看全文


上一篇文章      下一篇文章      查看所有文章
2016-04-02 20:51:48  
移动开发 最新文章
深入了解android中的消息机制Handler
Android
Libgdx之BitmapFont字体
AndroidApp发布到应用市场的流程
Android开发找工作之前先看看这些知识点吧
View的事件分发机制解析
简单介绍了解白鹭引擎Egret
Cocos2d
android获取本地图片(二)
动画特效七:碰撞动画
360图书馆 软件开发资料 文字转语音 购物精选 软件下载 美食菜谱 新闻资讯 电影视频 小游戏 Chinese Culture 股票 租车
生肖星座 三丰软件 视频 开发 短信 中国文化 网文精选 搜图网 美图 阅读网 多播 租车 短信 看图 日历 万年历 2018年1日历
2018-1-16 17:33:53
多播视频美女直播
↓电视,电影,美女直播,迅雷资源↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  软件世界网 --