ContentProvider实例

这篇文章记录使用ContentProvider的方法,提供了最简单安全的移植方法

首先在工程目录建立包名对应的database目录

放入如下三个文件:

DBHelper.java:

package com.sprd.fileexplorer.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * DBHelper
 * @author chrison.chai
 *
 */
public final class DBHelper extends SQLiteOpenHelper {
private static final String TAG = "DBHelper";
  private static final int DB_VERSION = 1;
  private static final String DB_NAME = "fileexplorer.db";
  public static final String ID = "_id";
  
  //favorate table
  public static final String TABLE_NAME_FAVORATE = "favorates";
  public static final String FAVORATE_TITLE = "title";
  public static final String FAVORATE_DATA = "_data";
  public static final String FAVORATE_DATE_MODIFIED = "date_modified";
  public static final String FAVORATE_SIZE = "_size";
  
  public DBHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
  }
  
  private SQLiteDatabase mWritableDatabase;
  private SQLiteDatabase mReadableDatabase;
  
  public synchronized SQLiteDatabase openWritableDatabase() {
	  if (mWritableDatabase == null) {
		  mWritableDatabase = getWritableDatabase();
	  }
	  return mWritableDatabase;
  }
  
  public synchronized SQLiteDatabase openReadableDatabase() {
	  if (mReadableDatabase == null) {
		  mReadableDatabase = getReadableDatabase();
	  }
	  return mReadableDatabase;
  }
  
  public synchronized void closeReadableDatabase() {
	  if (mReadableDatabase != null && mReadableDatabase.isOpen()) {
		  mReadableDatabase.close();
		  mReadableDatabase = null;
	  }
  }
  
  public synchronized void closeWritableDatabase() {
	  if (mWritableDatabase != null && mWritableDatabase.isOpen()) {
		  mWritableDatabase.close();
		  mWritableDatabase = null;
	  }
  }
  
  public synchronized void closeDatabase() {
	  closeReadableDatabase();
	  closeWritableDatabase();
  }

  @Override
  public void onCreate(SQLiteDatabase sqLiteDatabase) {
	  Log.d("huasong", "oncreate db helper..");
  	  createFavorateTable(sqLiteDatabase);
  }
  
  private void createFavorateTable(SQLiteDatabase sqLiteDatabase) {
	  sqLiteDatabase.execSQL(
	            "CREATE TABLE " + TABLE_NAME_FAVORATE + " (" +
	            ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
	            FAVORATE_TITLE + " TEXT, " +
	            FAVORATE_DATA + " TEXT, " +
	            FAVORATE_DATE_MODIFIED + " TEXT, " +
	            FAVORATE_SIZE + " TEXT" +
	            ");");
  }
  
  @Override
  public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
	  sqLiteDatabase.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME_FAVORATE + ";");
      onCreate(sqLiteDatabase);
  }
}
FavorateContent.java:

package com.sprd.fileexplorer.database;


import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;

public class FavorateContent {

	public static final String PKG_NAME = "com.sprd.fileexplorer";
	public static final String AUTHORITY = PKG_NAME + ".provider.FavorateProvider";
    public static final String NOTIFIER_AUTHORITY =  PKG_NAME + ".notify.FavorateProvider";

    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
    
    public static final String _ID = "_id";

    public static final String[] COUNT_COLUMNS = new String[]{"count(*)"};

    public static final String[] ID_PROJECTION = new String[] {
    	_ID
    };
    public static final int ID_PROJECTION_COLUMN = 0;
    
    public static class FavorateFile extends FavorateContent{
    	public static final Uri CONTENT_URI = Uri.withAppendedPath(FavorateContent.CONTENT_URI, "favoratefile");
    }
    
    public static long existed(ContentResolver cr, Uri uri, String where, String[] selectionArgs) {
    	long id = -1;
		Cursor c = cr.query(uri, ID_PROJECTION, where, selectionArgs, null);
		if (c != null) {
			if (c.moveToNext()) {
				id = c.getLong(0);
			}
			c.close();
		}
		return id;
	}
	
	public static int update(ContentResolver cr, Uri uri, ContentValues values, String where, String[] selectionArgs) {
		return cr.update(uri, values, where, selectionArgs);
	}
	
	public static Uri insert(ContentResolver cr, Uri uri, ContentValues values) {
		return cr.insert(uri, values);
	}
	
	public static int delete(ContentResolver cr, Uri uri,  String where, String[] selectionArgs) {
		return cr.delete(uri, where, selectionArgs);
	}
}
FavorateProvider.java:
package com.sprd.fileexplorer.database;


import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;

public class FavorateProvider extends ContentProvider{
	private static final String TAG = "BjnoteProvider";
	private SQLiteDatabase mContactDatabase;
	private String[] mTables = new String[]{
			DBHelper.TABLE_NAME_FAVORATE,
	};
	private static final int BASE = 8;
	
	private static final int FAVORATE = 0x0000;
	private static final int FAVORATE_ID = 0x0001;
	
	
	private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	 static {
	        // URI matching table
	        UriMatcher matcher = sURIMatcher;
	        matcher.addURI(FavorateContent.AUTHORITY, "favoratefile", FAVORATE);
	        matcher.addURI(FavorateContent.AUTHORITY, "favoratefile/#", FAVORATE_ID);
	        
	 }
	
	synchronized SQLiteDatabase getDatabase(Context context) {
		  Log.d("huasong", "getDatabase..");
        // Always return the cached database, if we've got one
        if (mContactDatabase != null) {
            return mContactDatabase;
        }


        DBHelper helper = new DBHelper(context);
        mContactDatabase = helper.getWritableDatabase();
        mContactDatabase.setLockingEnabled(true);
        return mContactDatabase;
	}
	
	@Override
	public boolean onCreate() {
		  Log.d("huasong", "onCreate return false..");
		return false;
	}
	
	/**
     * Wrap the UriMatcher call so we can throw a runtime exception if an unknown Uri is passed in
     * @param uri the Uri to match
     * @return the match value
     */
    private static int findMatch(Uri uri, String methodName) {
        int match = sURIMatcher.match(uri);
        if (match < 0) {
            throw new IllegalArgumentException("Unknown uri: " + uri);
        } 
        return match;
    }
    
    private void notifyChange(int match) {
    	Context context = getContext();
    	Uri notify = FavorateContent.CONTENT_URI;
    	switch(match) {
    	case FAVORATE:
    	case FAVORATE_ID:
    		notify = FavorateContent.FavorateFile.CONTENT_URI;
    		break;			
    	}
    	ContentResolver resolver = context.getContentResolver();
        resolver.notifyChange(notify, null);
    }

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int match = findMatch(uri, "delete");
        Context context = getContext();

        SQLiteDatabase db = getDatabase(context);
        String table = mTables[match>>BASE];
        int count = 0;
        switch(match) {
        default:
        	count = db.delete(table, buildSelection(match, uri, selection), selectionArgs);
        }
        if (count >0) notifyChange(match);
		return count;
	}

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

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		 int match = findMatch(uri, "insert");
         Context context = getContext();

         SQLiteDatabase db = getDatabase(context);
         String table = mTables[match>>BASE];
         if (values.containsKey(DBHelper.ID)) {
      		values.remove(DBHelper.ID);
      	 }
     	 long id = db.insert(table, null, values);
     	 if (id > 0) {
     		notifyChange(match);
   		    return ContentUris.withAppendedId(uri, id);
     	 }
		 return null;
	}
	private static final String[] COLUMN_NAME = { MediaStore.Images.ImageColumns.DATA};
	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		 int match = findMatch(uri, "query");
         Context context = getContext();
         SQLiteDatabase db = getDatabase(context);
         int i =match>>BASE;
         String table = mTables[i];
         Cursor result = null;
         switch(match) {
         default:
        	     result = db.query(table, projection, selection, selectionArgs, null, null, sortOrder);
         }
         if(result != null)result.setNotificationUri(getContext().getContentResolver(), uri);
		return result;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		int match = findMatch(uri, "update");
        Context context = getContext();
        
        SQLiteDatabase db = getDatabase(context);
        String table = mTables[match>>BASE];
        int count = 0;
        switch(match) {
        default:
        	    count = db.update(table, values, buildSelection(match, uri, selection), selectionArgs);
        }
        if (count >0) notifyChange(match);
		return count;
	}
	
	private String buildSelection(int match, Uri uri, String selection) {
		long id = -1;
		switch(match) {
	    	case FAVORATE_ID:
			try {
				id = ContentUris.parseId(uri);
			} catch(java.lang.NumberFormatException e) {
				e.printStackTrace();
			}
			break;
		}
		
		if (id == -1) {
			return selection;
		}
		StringBuilder sb = new StringBuilder();
		sb.append(DBHelper.ID);
		sb.append("=").append(id);
		if (!TextUtils.isEmpty(selection)) {
			sb.append(" and ");
			sb.append(selection);
		}
		return sb.toString();
	}
}
AndroidManifest.xml里面加入:

        <provider android:name="com.sprd.fileexplorer.database.FavorateProvider"
            android:authorities="com.sprd.fileexplorer.provider.FavorateProvider"/>
调用insert方法保存数据:

            	ContentValues values = new ContentValues();
            	values.put(DBHelper.FAVORATE_TITLE, mClickedFile.getName());
            	values.put(DBHelper.FAVORATE_DATA, mClickedFile.getPath());
            	values.put(DBHelper.FAVORATE_DATE_MODIFIED, System.currentTimeMillis());
            	values.put(DBHelper.FAVORATE_SIZE, mClickedFile.length());
            	
            	FavorateContent.insert(mContext.getContentResolver(), FavorateContent.FavorateFile.CONTENT_URI, values);
调用uri = FavorateContent.FavorateFile.CONTENT_URI;进行查询数据库的值






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值