扣丁学堂笔记第17天ContentProvider组件与Loaders

1.ContentProvider简介与准备工作

扣丁学堂笔记第17天ContentProvider组件与Loaders_第1张图片

扣丁学堂笔记第17天ContentProvider组件与Loaders_第2张图片扣丁学堂笔记第17天ContentProvider组件与Loaders_第3张图片

首先自定义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访问联系人

扣丁学堂笔记第17天ContentProvider组件与Loaders_第4张图片

扣丁学堂笔记第17天ContentProvider组件与Loaders_第5张图片

扣丁学堂笔记第17天ContentProvider组件与Loaders_第6张图片

扣丁学堂笔记第17天ContentProvider组件与Loaders_第7张图片

扣丁学堂笔记第17天ContentProvider组件与Loaders_第8张图片


6.Loaders概述与准备

扣丁学堂笔记第17天ContentProvider组件与Loaders_第9张图片扣丁学堂笔记第17天ContentProvider组件与Loaders_第10张图片扣丁学堂笔记第17天ContentProvider组件与Loaders_第11张图片


扣丁学堂笔记第17天ContentProvider组件与Loaders_第12张图片扣丁学堂笔记第17天ContentProvider组件与Loaders_第13张图片扣丁学堂笔记第17天ContentProvider组件与Loaders_第14张图片扣丁学堂笔记第17天ContentProvider组件与Loaders_第15张图片扣丁学堂笔记第17天ContentProvider组件与Loaders_第16张图片


7.使用CursorLoader加载数据

扣丁学堂笔记第17天ContentProvider组件与Loaders_第17张图片


8.Loaders_自定义AsyncTaskLoader加载数据

扣丁学堂笔记第17天ContentProvider组件与Loaders_第18张图片

详见:http://blog.csdn.net/dt235201314/article/details/50512749

你可能感兴趣的:(扣丁学堂笔记第17天ContentProvider组件与Loaders)