Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 自定義ContentProvider

自定義ContentProvider

編輯:關於Android編程

一、定義
1.編寫一個類,必須繼承自ContentProvider類

2.實現ContentProvider類中所有的抽象方法

3.定義ContentProvider的URI

4.使用UriMatcher對象映射Uri返回代碼

5.根據實際的需要編寫相應方法

6.在AndroidMainfest.xml文件中使用<provider>標簽注冊ContentProvider

以下是實現類:


 

package cn.eoe.region.content.provider; 
 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
 
import android.content.ContentProvider; 
import android.content.ContentValues; 
import android.content.UriMatcher; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.net.Uri; 
import android.util.Log; 
 
public class RegionContentProvider extends ContentProvider 
{ 
    private static UriMatcher uriMatcher; 
    private static final String AUTHORITY = "cn.eoe.regioncontentprovider"; 
    private static final int CITIES = 1; 
    private static final int CITY_CODE = 2; 
    private static final int CITY_NAME = 3; 
    private static final int CITIES_IN_PROVINCE = 4; 
    private SQLiteDatabase database; 
 
    static 
    { 
 
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); 
        // content://cn.eoe.regioncontentprovider/cities  
        uriMatcher.addURI(AUTHORITY, "cities", CITIES); 
        //  content://cn.eoe.regioncontentprovider/code/024  
        uriMatcher.addURI(AUTHORITY, "code/#", CITY_CODE); 
        //  content://cn.eoe.regioncontentprovider/name/北京  
        uriMatcher.addURI(AUTHORITY, "name/*", CITY_NAME); 
        //  content://cn.eoe.regioncontentprovider/cities_in_province/遼寧  
        uriMatcher 
                .addURI(AUTHORITY, "cities_in_province/*", CITIES_IN_PROVINCE); 
 
    } 
 
    private SQLiteDatabase openDatabase()<SPAN style="FONT-SIZE: 14px"><STRONG>//<SPAN style="BACKGROUND-COLOR: rgb(255,204,51)">寫入數據庫到內存卡根目錄</SPAN></STRONG></SPAN>  
    { 
        try 
        { 
            String databaseFilename = "/sdcard/region.db"; 
            if (!(new File(databaseFilename)).exists()) 
            { 
                InputStream is = getContext().getResources().getAssets() 
                        .open("region.db"); 
                FileOutputStream fos = new FileOutputStream(databaseFilename); 
                byte[] buffer = new byte[8192]; 
                int count = 0; 
                while ((count = is.read(buffer)) > 0) 
                { 
                    fos.write(buffer, 0, count); 
                } 
 
                fos.close(); 
                is.close(); 
            } 
            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase( 
                    databaseFilename, null); 
            return database; 
        } 
        catch (Exception e) 
        { 
            Log.d("error", e.getMessage()); 
        } 
        return null; 
    } 
 
    @Override 
    public boolean onCreate() 
    { 
        database = openDatabase(); 
        return true; 
    } 
 
    @Override 
    public Cursor query(Uri uri, String[] projection, String selection,<STRONG><SPAN style="BACKGROUND-COLOR: rgb(51,51,51); COLOR: #ffcc66; FONT-SIZE: 14px">//實現查找功能的關鍵部分</SPAN></STRONG>  
            String[] selectionArgs, String sortOrder) 
    { 
        Cursor cursor = null; 
 
        switch (uriMatcher.match(uri)) 
        { 
            case CITIES: 
 
                cursor = database.query("v_cities_province", projection, 
                        selection, selectionArgs, null, null, sortOrder); 
                break; 
            case CITY_CODE: 
                String cityCode = uri.getPathSegments().get(1); 
                if (selection == null) 
                    selection = "city_code='" + cityCode + "'"; 
                else 
                    selection += " and (city_code='" + cityCode + "')"; 
                cursor = database.query("t_cities", projection, selection, 
                        selectionArgs, null, null, sortOrder); 
 
                break; 
            case CITY_NAME: 
                String cityName = uri.getPathSegments().get(1); 
                if (selection == null) 
                    selection = "city_name='" + cityName + "'"; 
                else 
                    selection += " and (city_name='" + cityName + "')"; 
                cursor = database.query("t_cities", projection, selection, 
                        selectionArgs, null, null, sortOrder); 
 
                break; 
            case CITIES_IN_PROVINCE: 
                String provinceName = uri.getPathSegments().get(1); 
                if (selection == null) 
                    selection = "province_name='" + provinceName + "'"; 
                else 
                    selection += " and (province_name='" + provinceName + "')"; 
                cursor = database.query("v_cities_province", projection, selection, 
                        selectionArgs, null, null, sortOrder);               
                break; 
             
            default: 
                throw new IllegalArgumentException("<" + uri + ">格式不正確."); 
        } 
        return cursor; 
 
    } 
 
    @Override 
    public String getType(Uri uri) 
    { 
        // TODO Auto-generated method stub  
        return null; 
    } 
 
    @Override 
    public Uri insert(Uri uri, ContentValues values) 
    { 
        // TODO Auto-generated method stub  
        return null; 
    } 
 
    @Override 
    public int delete(Uri uri, String selection, String[] selectionArgs) 
    { 
        // TODO Auto-generated method stub  
        return 0; 
    } 
 
    @Override 
    public int update(Uri uri, ContentValues values, String selection, 
            String[] selectionArgs) 
    { 
        // TODO Auto-generated method stub  
        return 0; 
    } 
 
} 

package cn.eoe.region.content.provider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

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

public class RegionContentProvider extends ContentProvider
{
 private static UriMatcher uriMatcher;
 private static final String AUTHORITY = "cn.eoe.regioncontentprovider";
 private static final int CITIES = 1;
 private static final int CITY_CODE = 2;
 private static final int CITY_NAME = 3;
 private static final int CITIES_IN_PROVINCE = 4;
 private SQLiteDatabase database;

 static
 {

  uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  // content://cn.eoe.regioncontentprovider/cities
  uriMatcher.addURI(AUTHORITY, "cities", CITIES);
  //  content://cn.eoe.regioncontentprovider/code/024
  uriMatcher.addURI(AUTHORITY, "code/#", CITY_CODE);
  //  content://cn.eoe.regioncontentprovider/name/北京
  uriMatcher.addURI(AUTHORITY, "name/*", CITY_NAME);
  //  content://cn.eoe.regioncontentprovider/cities_in_province/遼寧
  uriMatcher
    .addURI(AUTHORITY, "cities_in_province/*", CITIES_IN_PROVINCE);

 }

 private SQLiteDatabase openDatabase()//寫入數據庫到內存卡根目錄
 {
  try
  {
   String databaseFilename = "/sdcard/region.db";
   if (!(new File(databaseFilename)).exists())
   {
    InputStream is = getContext().getResources().getAssets()
      .open("region.db");
    FileOutputStream fos = new FileOutputStream(databaseFilename);
    byte[] buffer = new byte[8192];
    int count = 0;
    while ((count = is.read(buffer)) > 0)
    {
     fos.write(buffer, 0, count);
    }

    fos.close();
    is.close();
   }
   SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
     databaseFilename, null);
   return database;
  }
  catch (Exception e)
  {
   Log.d("error", e.getMessage());
  }
  return null;
 }

 @Override
 public boolean onCreate()
 {
  database = openDatabase();
  return true;
 }

 @Override
 public Cursor query(Uri uri, String[] projection, String selection,//實現查找功能的關鍵部分
   String[] selectionArgs, String sortOrder)
 {
  Cursor cursor = null;

  switch (uriMatcher.match(uri))
  {
   case CITIES:

    cursor = database.query("v_cities_province", projection,
      selection, selectionArgs, null, null, sortOrder);
    break;
   case CITY_CODE:
    String cityCode = uri.getPathSegments().get(1);
    if (selection == null)
     selection = "city_code='" + cityCode + "'";
    else
     selection += " and (city_code='" + cityCode + "')";
    cursor = database.query("t_cities", projection, selection,
      selectionArgs, null, null, sortOrder);

    break;
   case CITY_NAME:
    String cityName = uri.getPathSegments().get(1);
    if (selection == null)
     selection = "city_name='" + cityName + "'";
    else
     selection += " and (city_name='" + cityName + "')";
    cursor = database.query("t_cities", projection, selection,
      selectionArgs, null, null, sortOrder);

    break;
   case CITIES_IN_PROVINCE:
    String provinceName = uri.getPathSegments().get(1);
    if (selection == null)
     selection = "province_name='" + provinceName + "'";
    else
     selection += " and (province_name='" + provinceName + "')";
    cursor = database.query("v_cities_province", projection, selection,
      selectionArgs, null, null, sortOrder);    
    break;
   
   default:
    throw new IllegalArgumentException("<" + uri + ">格式不正確.");
  }
  return cursor;

 }

 @Override
 public String getType(Uri uri)
 {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public Uri insert(Uri uri, ContentValues values)
 {
  // TODO Auto-generated method stub
  return null;
 }

 @Override
 public int delete(Uri uri, String selection, String[] selectionArgs)
 {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public int update(Uri uri, ContentValues values, String selection,
   String[] selectionArgs)
 {
  // TODO Auto-generated method stub
  return 0;
 }

}

URI分為authority和path兩部分,其中authority就是
“content://authority”中的authority,相當於網址中的域名,而path
就是“content://authority/”後面的部分,與網址中的路徑類似。


二、實現
使用ContentResolver類,獲得Uri,查到相關記錄並處理。
 

package cn.eoe.invoke.content.provider; 
 
import android.app.Activity; 
import android.content.ContentResolver; 
import android.database.Cursor; 
import android.net.Uri; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ListView; 
import android.widget.SimpleCursorAdapter; 
import android.widget.Toast; 
 
public class Main extends Activity 
{ 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    {   
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
    } 
   
    public void onClick_Show_Cities(View view) 
    { 
        ContentResolver contentResolver = getContentResolver(); 
        Uri uri = Uri 
                .parse("content://cn.eoe.regioncontentprovider/cities"); 
        Cursor cursor = contentResolver.query(uri, new String[] 
        { "city_code as _id", "city_name", "province_code" }, null, null, null); 
 
        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, 
                android.R.layout.simple_list_item_1, cursor, new String[] 
                { "city_name" }, new int[] 
                { android.R.id.text1 }); 
 
        ListView lvCities = (ListView) findViewById(R.id.lvCities); 
        lvCities.setAdapter(simpleCursorAdapter); 
 
        uri = Uri 
                .parse("content://cn.eoe.regioncontentprovider/code/024"); 
        cursor = contentResolver.query(uri, null, null, null, null); 
        if (cursor.moveToFirst()) 
        { 
            Toast.makeText( 
                    this, 
                    "024:" 
                            + cursor.getString(cursor 
                                    .getColumnIndex("city_name")), 
                    Toast.LENGTH_LONG).show(); 
        } 
 
        uri = Uri 
                .parse("content://cn.eoe.regioncontentprovider/name/沈陽"); 
        cursor = contentResolver.query(uri, null, null, null, null); 
        if (cursor.moveToFirst()) 
        { 
            Toast.makeText( 
                    this, 
                    "沈陽:" 
                            + cursor.getString(cursor 
                                    .getColumnIndex("city_code")), 
                    Toast.LENGTH_LONG).show(); 
        } 
    } 
 
    public void onClick_Show_Lining_Cities(View view) 
    { 
        ContentResolver contentResolver = getContentResolver(); 
        Uri uri = Uri 
                .parse("content://cn.eoe.regioncontentprovider/cities_in_province/遼寧"); 
        Cursor cursor = contentResolver.query(uri, new String[] 
        { "city_code as _id", "city_name", "province_code" }, null, null, 
                "city_code"); 
 
        SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this, 
                android.R.layout.simple_list_item_1, cursor, new String[] 
                { "city_name" }, new int[] 
                { android.R.id.text1 }); 
 
        ListView lvCities = (ListView) findViewById(R.id.lvCities); 
        lvCities.setAdapter(simpleCursorAdapter); 
    } 
} 

package cn.eoe.invoke.content.provider;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class Main extends Activity
{
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState)
 { 
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 }
 
 public void onClick_Show_Cities(View view)
 {
  ContentResolver contentResolver = getContentResolver();
  Uri uri = Uri
    .parse("content://cn.eoe.regioncontentprovider/cities");
  Cursor cursor = contentResolver.query(uri, new String[]
  { "city_code as _id", "city_name", "province_code" }, null, null, null);

  SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
    android.R.layout.simple_list_item_1, cursor, new String[]
    { "city_name" }, new int[]
    { android.R.id.text1 });

  ListView lvCities = (ListView) findViewById(R.id.lvCities);
  lvCities.setAdapter(simpleCursorAdapter);

  uri = Uri
    .parse("content://cn.eoe.regioncontentprovider/code/024");
  cursor = contentResolver.query(uri, null, null, null, null);
  if (cursor.moveToFirst())
  {
   Toast.makeText(
     this,
     "024:"
       + cursor.getString(cursor
         .getColumnIndex("city_name")),
     Toast.LENGTH_LONG).show();
  }

  uri = Uri
    .parse("content://cn.eoe.regioncontentprovider/name/沈陽");
  cursor = contentResolver.query(uri, null, null, null, null);
  if (cursor.moveToFirst())
  {
   Toast.makeText(
     this,
     "沈陽:"
       + cursor.getString(cursor
         .getColumnIndex("city_code")),
     Toast.LENGTH_LONG).show();
  }
 }

 public void onClick_Show_Lining_Cities(View view)
 {
  ContentResolver contentResolver = getContentResolver();
  Uri uri = Uri
    .parse("content://cn.eoe.regioncontentprovider/cities_in_province/遼寧");
  Cursor cursor = contentResolver.query(uri, new String[]
  { "city_code as _id", "city_name", "province_code" }, null, null,
    "city_code");

  SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,
    android.R.layout.simple_list_item_1, cursor, new String[]
    { "city_name" }, new int[]
    { android.R.id.text1 });

  ListView lvCities = (ListView) findViewById(R.id.lvCities);
  lvCities.setAdapter(simpleCursorAdapter);
 }
}

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved