Android 它们的定义ContentProvider和ContentObserver充分利用
在他们的定义ContentProvider结合ContentObserver一起使用时,自己写的ContentProvider,在运行完insert、delete和update后,要手动地调用getContentResolver().notifyChange()这种方法来通知修改的产生。
直接上代码:
MainActivity
package com.jackie.contentobserver; import java.util.ArrayList; import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView; public class MainActivity extends Activity { private ArrayList<Person> mList;
private ListView mListView;
private ContentResolver resolver;
private MyBaseAdapter mBaseAdapter;
private Handler mHandler; private AdapterContentObserver mAdapterContentObserver; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); mListView = (ListView) findViewById(R.id.lv_person);
initData(); mBaseAdapter = new MyBaseAdapter(this, mList);
mListView.setAdapter(mBaseAdapter); mHandler = new Handler(); mAdapterContentObserver = new AdapterContentObserver(this, mHandler);
resolver.registerContentObserver(Uri.parse("content://com.jackie.provider.person/person"), true, mAdapterContentObserver);
//注冊短信变化监听
//this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, content)
} @Override
protected void onDestroy() {
resolver.unregisterContentObserver(mAdapterContentObserver);
super.onDestroy();
} private ArrayList<Person> initData() {
mList = new ArrayList<Person>();
resolver = getContentResolver();
Cursor cursor = resolver.query(Uri.parse("content://com.jackie.provider.person/person"), null, null, null, null);
while (cursor.moveToNext()) {
Person person = new Person();
person.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
mList.add(person);
} return mList;
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
} @Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_settings:
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("提示").setMessage("您确定要退出?");
// builder.create().show();
ContentValues values = new ContentValues();
values.put("name", "Jackie");
Uri mUri = resolver.insert(Uri.parse("content://com.jackie.provider.person/person"), values); //方法一: 又一次查询数据库实时刷新
// mBaseAdapter = new MyBaseAdapter(this, initData());
// mListView.setAdapter(mBaseAdapter); //方法二: 当adapter绑定的list变化时,调用adapter的notifyDataSetChanged方法实时刷新(不用反复查询数据库,效率更高)
// long id = ContentUris.parseId(mUri);
// mList.add(new Person(id, "chengjie"));
// mBaseAdapter.notifyDataSetChanged(); //方法三: 内容观察者ContentObserver
//自己写的ContentProvider,在运行完insert、delete和update后,要手动地调用getContentResolver().notifyChange()这种方法来通知修改的产生(请參考MyProvider.java的方法) break; default:
break;
}
return super.onMenuItemSelected(featureId, item);
} }
AdapterContentObserver.java
package com.jackie.contentobserver; import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast; public class AdapterContentObserver extends ContentObserver {
private Context context;
private Handler handler; private static final int PERSON_UPDATE = 0; public AdapterContentObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
} public AdapterContentObserver(Context context, Handler handler) {
super(handler);
this.context = context;
this.handler = handler;
} //当监听的Uri发生变化。便会运行这种方法
@Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri); ContentResolver resolver = context.getContentResolver();
// 获取最新的一条数据
Cursor cursor = resolver.query(uri, null, null, null, "_id desc limit 1");
while (cursor.moveToNext()) {
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
Toast.makeText(context, "数据库更新了, _id 为: " + _id, Toast.LENGTH_SHORT).show();
}
cursor.close();
}
}
DBHelper.java
package com.jackie.contentobserver; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper; public class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
} @Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists person(_id integer primary key autoincrement, name text)");
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
MyBaseAdapter.java
package com.jackie.contentobserver; import java.util.ArrayList; import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView; public class MyBaseAdapter extends BaseAdapter { private ViewHolder holder;
private Context context;
private ArrayList<Person> mList; public MyBaseAdapter(Context context, ArrayList<Person> mList) {
this.context = context;
this.mList = mList;
} @Override
public int getCount() {
return mList.size();
} @Override
public Object getItem(int position) {
return mList.get(position);
} @Override
public long getItemId(int position) {
return position;
} @Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.listview_item, null);
holder.idTexitView = (TextView) convertView.findViewById(R.id.tv_id);
holder.nameTextView = (TextView) convertView.findViewById(R.id.tv_name);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.idTexitView.setText(mList.get(position).get_id() + "");
holder.nameTextView.setText(mList.get(position).getName());
return convertView;
} class ViewHolder {
TextView idTexitView;
TextView nameTextView;
}
}
MyProvider.java
package com.jackie.contentobserver; 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 MyProvider extends ContentProvider {
private final static String AUTHORITH = "com.jackie.provider.person"; private final static String PERSONS_PATH = "person"; private final static String PERSON_PATH = "person/#"; private final static int PERSON = 1; private final static int PERSONS = 2; private final static String DATABASE_NAME = "person_db"; private final static String TABLE_NAME = "person"; private final static String TABLE_COLUMN_ID = "_id"; private final static String TABLE_COLUMN_NAME = "name"; private final static UriMatcher mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static {
mUriMatcher.addURI(AUTHORITH, PERSONS_PATH, PERSONS);
mUriMatcher.addURI(AUTHORITH, PERSON_PATH, PERSON);
} private DBHelper helper = null; @Override
public boolean onCreate() {
helper = new DBHelper(getContext(), DATABASE_NAME, null, 1);
return true;
} @Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
SQLiteDatabase database = helper.getWritableDatabase();
switch (mUriMatcher.match(uri)) {
case PERSON:
long id = ContentUris.parseId(uri);
String where = TABLE_COLUMN_ID + "=" + id;
if (selection != null && !"".equals(selection)) {
selection = where + "and" + selection;
}
return database.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); case PERSONS:
return database.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); default:
throw new IllegalArgumentException("UnKnown uri: " + uri);
}
} @Override
public String getType(Uri uri) {
switch (mUriMatcher.match(uri)) {
case PERSON:
return "vnd.android.cursor.item"; case PERSONS:
return "vnd.android.cursor.dir"; default:
throw new IllegalArgumentException("UnKnown uri: " + uri);
}
} @Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase database = helper.getWritableDatabase();
long id = database.insert(TABLE_NAME, TABLE_COLUMN_NAME, values);
//向外界通知该ContentProvider里的数据发生了变化 ,以便ContentObserver作出对应
getContext().getContentResolver().notifyChange(uri, null);
return ContentUris.withAppendedId(uri, id);
} @Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase database = helper.getWritableDatabase();
switch (mUriMatcher.match(uri)) {
case PERSON:
long id = ContentUris.parseId(uri);
String where = TABLE_COLUMN_ID + "=" + id;
if (selection != null && !"".equals(selection)) {
selection = where + "and" + selection;
}
return database.delete(TABLE_NAME, selection, selectionArgs); case PERSONS:
return database.delete(TABLE_NAME, selection, selectionArgs); default:
throw new IllegalArgumentException("UnKnown uri: " + uri);
}
} @Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO Auto-generated method stub
return 0;
} }
Person.java
package com.jackie.contentobserver; public class Person { private long _id;
private String name;
public Person(long _id, String name) {
super();
this._id = _id;
this.name = name;
} public Person() {
super();
// TODO Auto-generated constructor stub
} public long get_id() {
return _id;
} public void set_id(long _id) {
this._id = _id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} }
版权声明:本文博主原创文章。博客,未经同意不得转载。
Android 它们的定义ContentProvider和ContentObserver充分利用的更多相关文章
- java攻城狮之路(Android篇)--ListView与ContentProvider
一.ListView 1.三种Adapter构建ListView ListView添加条目的时候, 可以使用setAdapter(ListAdapter)方法, 常用的ListAdapter有三种 B ...
- android菜鸟学习笔记22----ContentProvider(二)ContentObserver的简单使用
现在有这样一个应用A通过ContentProvider提供自己的数据给其他应用,应用B通过ContentResolver获取应用A中提供的数据,并将其展示在ListView中,而应用C通过Conten ...
- Android 这 13 道 ContentProvider 面试题,你都会了吗?
前言 作为 Android 的四大组件之一,ContentProvider 可以说是无处不在了. 但是对于我而言,开发过程中看似 ContentProvider 用得很娴熟,却一直没能形成一个完整的体 ...
- android四大组件之ContentProvider(一)
ContentProvider学习笔记 1. ContentProvider基本概念 ContentProvider向我们提供了我们在应用程序之间共享数据的一种机制,虽然采用文件和SharedPref ...
- android学习笔记54——ContentProvider
ContentProvider ContentProvider用于实现数据共享. ContentProvider是不同应用程序之间进行数据交换的标准API,其以某种Uri的形式对外提供数据,允许其他应 ...
- Android四大组件之——ContentProvider(一)
Android四大组件之--ContentProvider(一) 本人邮箱:JohnTsai.Work@gmail.com,欢迎交流讨论. 欢迎转载,转载请注明网址:http://www.cnblog ...
- 【Android】19.3 ContentProvider及安卓进一步封装后的相关类
分类:C#.Android.VS2015: 创建日期:2016-03-08 一.简介 ContentProvider:内容提供程序. Android的ContentProvider与.NET框架的EF ...
- Android四大组件之contentProvider
Activity,Service,broadcast and Contentprovider android 4 大组件. ContentProvider:使用: public class Image ...
- 初学android:四大组件之contentprovider
一.ContentProvider的概念ContentProvider:为存储和获取数据提供统一的接口.可以在不同的应用程序之间共享数据.Android已经为常见的一些数据提供了默认的ContentP ...
随机推荐
- ORACLE中%TYPE和%ROWTYPE的使用
1 %TYPE说明 为了使一个变量的数据类型与还有一个已经定义了的变量(尤其是表的某一列)的数据类型相一致,Oracle提供了%TYPE定义方式.当被參照的那个变量的数据类型改变了之后,这个新定 ...
- C++ Primer中文版(第5版)
<C++ Primer中文版(第5版)> 基本信息 作者: (美)Stanley B. Lippman(斯坦利 李普曼) Josee Lajoie(约瑟 拉乔伊) Barbar ...
- leetcode 之 Permutation Sequence
Permutation Sequence The set [1,2,3,-,n] contains a total of n! unique permutations. By listing and ...
- 服务器编程入门(7)I/O复用
问题聚焦: 前篇提到了I/O处理单元的四种I/O模型. 本篇详细介绍实现这些I/O模型所用到的相关技术. 核心思想:I/O复用 使用情景: 客户端程序要同时处理多个socket ...
- 用链表实现栈----《数据结构与算法分析----C语言描述》
一.头文件: #ifndef _STACK_LINK_H_ #define _STACK_LINK_H_ struct stack_record; typedef struct stack_recor ...
- Android中的动画具体解释系列【1】——逐帧动画
逐帧动画事实上非常easy,以下我们来看一个样例: <?xml version="1.0" encoding="utf-8"?> <anima ...
- finger用户名、主目录、停滞时间、登录时间
finger yum install finger 1.作用 finger用来查询一台主机上的登录账号的信息,通常会显示用户名.主目录.停滞时间.登录时间.登录Shell等信息,使用权限为 ...
- Mina框架断包、粘包问题解决方式
Mina框架断包.粘包问题解决方式 Apache Mina Server 是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP.UDP/IP协议栈的通信框架(当然.也能够提供JAVA 对象的序 ...
- MAC地址格式小结
之前一段时间在做网卡驱动的工作,如今产品量产,利用ifconfig eth hw ether在配置mac地址时发现一个问题, 随机配置一个mac地址,发现有的会报出Cannot assign requ ...
- FluentData
FluentData微型ORM 最近在帮朋友做一个简单管理系统,因为笔者够懒,但是使用过的NHibernate用来做这中项目又太不实际了,索性百度了微型ORM,FluentData是第一个跳入我眼睛的 ...