Android组件ContentProvider使用

Android四大组件之一Contentprovider的两大功能

1.进程间通信

2.数据有变化及时通知使用者

这篇文章讲解数据变化时通知使用者的功能,对于及时需要知道数据变化的场景有很大帮助。

文件下载过程, 使用该监听很好实现对ListView列表进行刷新。
这里贴出来刷新UI相关的代码,下载模块,自己实现就ok了,只要数据表中的数据发生变化,就会回调ContentObserver的onChange(...)方法。

初始化BaseAdapter时,注册监听数据表变化的观察者。


public class ListDownloadDocHandler extends BaseAdapter {
    private DownloadObserver localObserver;

    private ListDownloadDocHandler listDownloadDocHandler;

    public ListDocDownloadAdapter(Context context) {
        localObserver = new DownloadObserver(null, listNonDownloadDocHandler);
        //注册数据观察者
        mContext.getContentResolver().registerContentObserver(ICorporateDocDao.COLUMNS.CONTENT_URI,
                true, localObserver);
    }
    /**
     *文档全部下载完,取消数据观察者
     *
     */
    public void unregisterContentObserver() {
        mContext.getContentResolver().unregisterContentObserver(localObserver);
    }
	static class ListDownloadDocHandler extends Handler {      
	 	 WeakReference<ListDocDownloadAdapter> listDocAdapter;
        ListDocDownloadAdapter locallistDocAdapter;

        public ListNonDownloadDocHandler(ListDocNondownloadAdapter listDocAdapter) {
            this.listDocAdapter = new WeakReference<ListDocDownloadAdapter>(listDocAdapter);
        }

        ...
        ...

        public void handleMessage(Message msg) {
            if (listDocAdapter == null) {
                Logger.d(loggerName, "listDocAdapter is null");
                return;
            }
            locallistDocAdapter = listDocAdapter.get();
            switch (msg.what) {
                case DownloadKeys.DOWNLOADING_TASK:
                    locallistDocAdapter.uiRefresh();
                    break;
                default:
                    break;
            }
        }
    }
    /**
     * 实现子类DownloadObserver继承 ContentObserver接口
     *
     */class DownloadObserver extends ContentObserver {
        private Handler handler;

        public DownloadObserver(Uri mediaUri, Handler paramHandler) {
            super(paramHandler);
            handler = paramHandler;
        }
        
    /**
     *ICorporateDocDao.COLUMNS.CONTENT_URI数据变化时,回调onChange(...)
     */
        @Override
        public void onChange(boolean paramBoolean) {
            super.onChange(paramBoolean);
            if (dataList == null || dataList.isEmpty()) {
                Logger.d(loggerName, "dataList is null");
                return;
            }
            handler.sendEmptyMessage(DownloadKeys.DOWNLOADING_TASK);
        }
    }

 
public class CorporateDocProvider extends ContentProvider {
    private final String TAG = "CorporateDocProvider";

    private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

    private static final int MEDIA = 1000;

    private static final int MEDIA_ID = 1001;

    static {
        URI_MATCHER.addURI("com.demo.emm", "media_doc", 1000);
        URI_MATCHER.addURI("com.demo.emm", "media_doc/#", 1001);
    }

    @Override
    public boolean onCreate() {
        return false;
    }

    @Override
    public Cursor query(Uri paramUri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder localSQLiteQueryBuilder = new SQLiteQueryBuilder();
        int i = URI_MATCHER.match(paramUri);
        switch (i) {
            case MEDIA:
                localSQLiteQueryBuilder.setTables("media_doc");
                break;
            case MEDIA_ID:
                localSQLiteQueryBuilder.setTables("media_doc");
                localSQLiteQueryBuilder.appendWhere("content_id = "
                        + (String)paramUri.getPathSegments().get(1));
                break;

            default:
                break;
        }
        Cursor localCursor = localSQLiteQueryBuilder.query(
                MDMDatabaseUtils.getInstance(getContext()).openDatabase(), projection, selection,
                selectionArgs, null, null, sortOrder);
        if (localCursor != null) {
            localCursor.setNotificationUri(getContext().getContentResolver(), paramUri);
        } else {
            Logger.d(TAG, "localCursor == null");
        }
        return localCursor;
    }

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

    @Override
    public Uri insert(Uri paramUri, ContentValues values) {
        SQLiteDatabase localSQLiteDatabase = MDMDatabaseUtils.getInstance(getContext())
                .openDatabase();
        Uri localUri = null;
        int i = URI_MATCHER.match(paramUri);
        try {
            localSQLiteDatabase.beginTransaction();
            switch (i) {
                case MEDIA:
                case MEDIA_ID:
                    long l1 = localSQLiteDatabase.insert("media_doc", null, ensureFile(values));
                    if (l1 > 0) {
                        localSQLiteDatabase.setTransactionSuccessful();
                    } else {
                        Logger.d(TAG, "insert media_doc data failure" + values.toString());
                    }
                    if (paramUri != null) {
                        getContext().getContentResolver().notifyChange(paramUri, null);
                        localUri = paramUri;
                    }
                    break;
                default:
                    throw new UnsupportedOperationException("Invalid URI " + paramUri);
            }

        } catch (Exception e) {
            Logger.d(TAG, e.getMessage());
        } finally {
            if (null != localSQLiteDatabase) {
                localSQLiteDatabase.endTransaction();
            }
        }

        return localUri;
    }

    @Override
    public int delete(Uri paramUri, String whereClause, String[] whereArgs) {
        SQLiteDatabase localSQLiteDatabase = MDMDatabaseUtils.getInstance(getContext())
                .openDatabase();
        int flag = 0;
        int i = URI_MATCHER.match(paramUri);
        try {
            localSQLiteDatabase.beginTransaction();
            switch (i) {
                case MEDIA_ID:
                    String id = (String)paramUri.getPathSegments().get(1);
                    if (!TextUtils.isEmpty(id)) {
                        String str3 = COLUMNS.CONTENT_ID + " = "
                                + (String)paramUri.getPathSegments().get(1);
                        if (whereClause == null) {
                            whereClause = str3;
                        } else {
                            whereClause = str3 + " AND (" + whereClause + ")";
                        }
                    }
                    int l1 = localSQLiteDatabase.delete("media_doc", whereClause, whereArgs);

                    if (l1 > 0) {
                        localSQLiteDatabase.setTransactionSuccessful();
                    } else {
                        Logger.d(TAG, "media_doc delete fail=" + whereClause + "="
                                + whereArgs.length);
                    }
                    if (paramUri != null)
                        getContext().getContentResolver().notifyChange(paramUri, null);
                    break;
                case MEDIA:
                    int l2 = localSQLiteDatabase.delete("media_doc", whereClause, whereArgs);
                    if (l2 > 0) {
                        localSQLiteDatabase.setTransactionSuccessful();
                    } else {
                        Logger.d(TAG, "media_doc delete fail=" + whereClause + "="
                                + whereArgs.length);
                    }
                    if (paramUri != null)
                        getContext().getContentResolver().notifyChange(paramUri, null);
                    break;

                default:
                    break;
            }

        } catch (Exception e) {
            Logger.d(TAG, e.getMessage());
        } finally {
            if (null != localSQLiteDatabase) {
                localSQLiteDatabase.endTransaction();
            }
        }
        return flag;
    }

    @Override
    public int update(Uri paramUri, ContentValues values, String selection, String[] selectionArgs) {
        SQLiteDatabase localSQLiteDatabase = MDMDatabaseUtils.getInstance(getContext())
                .openDatabase();
        int i = URI_MATCHER.match(paramUri);
        localSQLiteDatabase.beginTransaction();
        int index = -1;
        Uri localUri = null;
        try {
            switch (i) {
                case MEDIA:
                case MEDIA_ID:
                    int l1 = localSQLiteDatabase.update("media_doc", values, selection,
                            selectionArgs);
                    if (l1 > 0) {
                        localSQLiteDatabase.setTransactionSuccessful();
                    } else {
                        Logger.d(TAG, "update fail=" + values);
                    }
                    if (paramUri != null)
                        getContext().getContentResolver().notifyChange(paramUri, null);
                    break;

                default:
                    break;
            }

        } catch (Exception e) {
            Logger.d(TAG, e.getMessage());
        } finally {
            if (null != localSQLiteDatabase) {
                localSQLiteDatabase.endTransaction();
            }
        }
        return index;
    }

    private ContentValues ensureFile(ContentValues paramContentValues) {
        return paramContentValues;
    }
}


AndroidManifest.xml配置文件中设置:

 <provider
            android:name="com.polysaas.mdm.dao.impl.CorporateDocProvider"
            android:authorities="com.demo.emm" >
        </provider>



 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值