ContentProvider的创建和ContentResolver的使用

简介: 1、创建contentProvider   定义(客户端调用时需知的内容)接口 package com.gogler.content;import android.net.Uri;import android.

1、创建contentProvider

 

定义(客户端调用时需知的内容)接口

package com.gogler.content;

import android.net.Uri;
import android.provider.BaseColumns;

public class Users {
	public static final String AUTHORITY = "com.gogler.content";
	public static final class User implements BaseColumns{
		public static final Uri CONTENT_URI  = Uri.parse("content://com.gogler.content");
 	      public static final String  USER_NAME  = "USER_NAME";
	 
	}
}

 

实现内容提供器

 

package com.gogler.content;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;

public class SumaryContentProvider extends ContentProvider {
	private SQLiteDatabase     sqlDB;
private DatabaseHelper    dbHelper;
private static final String  DATABASE_NAME     = "Users.db";
private static final int        DATABASE_VERSION         = 1;
private static final String TABLE_NAME   = "User";
private static final String TAG = "SumaryContentProvider";

private static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

   @Override
    public void onCreate(SQLiteDatabase db) {
        //创建用于存储数据的表
    db.execSQL("Create table " + TABLE_NAME + "( _id INTEGER PRIMARY KEY AUTOINCREMENT, " +
    		"USER_NAME TEXT);");
    }

   @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}

@Override
public int delete(Uri uri, String s, String[] as) {
    return 0;
}

@Override
public String getType(Uri uri) {
    return null;
}

@Override
public Uri insert(Uri uri, ContentValues contentvalues) {
    sqlDB = dbHelper.getWritableDatabase();
    long rowId = sqlDB.insert(TABLE_NAME, "", contentvalues);
    if (rowId > 0) {
        Uri rowUri = ContentUris.appendId(Users.User.CONTENT_URI.buildUpon(), rowId).build();
        getContext().getContentResolver().notifyChange(rowUri, null);
        return rowUri;
    }
    throw new SQLException("Failed to insert row into " + uri);
}

@Override
public boolean onCreate() {
    dbHelper = new DatabaseHelper(getContext());
    return (dbHelper == null) ? false : true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    qb.setTables(TABLE_NAME);
    Cursor c = qb.query(db, projection, selection, null, null, null, sortOrder);
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}

@Override
public int update(Uri uri, ContentValues contentvalues, String s, String[] as) {
    return 0;
}


}


 

2、使用内容提供器ContentResolver(客户端)

 

package com.gogler.content;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Toast;

public class ContentSumaryActivity extends Activity {
	@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        for(int i =1; i<=10; i++){
        insertRecord("User"+i);
        }
        displayRecords();
    }
   
    private void insertRecord(String userName) {
        ContentValues values = new ContentValues();
        values.put(Users.User.USER_NAME, userName);
        getContentResolver().insert(Users.User.CONTENT_URI, values);
    }

   private void displayRecords() {
        String columns[] = new String[] { Users.User._ID, Users.User.USER_NAME };
        Uri myUri = Users.User.CONTENT_URI;
        Cursor cur = managedQuery(myUri, columns,null, null, null );
        if (cur.moveToFirst()) {
            String id = null;
            String userName = null;
            do {
                id = cur.getString(cur.getColumnIndex(Users.User._ID));
                userName = cur.getString(cur.getColumnIndex(Users.User.USER_NAME));
                Toast.makeText(this, id + " " + userName, Toast.LENGTH_LONG).show();
           } while (cur.moveToNext());
       }
    }


}


 

3、参考

《Android基础 :  Android Content Provider》

相关文章
|
7月前
|
存储 缓存 Java
ContentProvider的启动
ContentProvider的启动
88 1
|
7月前
|
存储 数据库
ContentProvider的简单使用
ContentProvider的简单使用
45 1
|
Java Android开发
Android 中通过Intent传递类对象,通过实现Serializable和Parcelable接口两种方式传递对象
Android 中通过Intent传递类对象,通过实现Serializable和Parcelable接口两种方式传递对象
140 1
|
Java Android开发
Android 四大组件之ContentProvider 访问通讯录进行增删改查操作
Android 四大组件之ContentProvider 访问通讯录进行增删改查操作
96 0
|
存储 API 数据库
Android:四大组件之 ContentProvider(外共享数据)
数据库在 Android 当中是私有的,不能将数据库设为 WORLD_READABLE,每个数据库都只能允许创建它的包访问。这意味着只有创建这个数据库的应用程序才可访问它。也就是说不能跨越进程和包的边界,直接访问别的应用程序的数据库。那么如何在应用程序间交换数据呢? 如果需要在进程间传递数据,可以使用 ContentProvider 来实现。
354 0
Android:四大组件之 ContentProvider(外共享数据)
|
API 数据库 数据库管理
ContentProvider初探
ContentProvider初探
65 0
|
数据库
ContentProvider
构建content URI public class TaskContract { /* COMPLETED (1) Add content provider constants to the Contract Clients need to know how to access the task data, and it's your job to provide these content URI's for the path to that data: 1) Content authority, 2) Base content
145 0
ContentProvider