正文  基础知识 > 程序示例 >

ContentProvider

package www.gxw.com.sqlit.provider; import www.gxw.com.sqlit.dataBase.DataBaseHelpe...

package www.gxw.com.sqlit.provider;

import www.gxw.com.sqlit.dataBase.DataBaseHelper;
import android.R.integer;
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 UserContentProivder extends ContentProvider {

	private static final String AUTHORITIES = "www.gxw.com.sqlit.provider.usercontentproivder";

	private DataBaseHelper dataBaseHelper;

	private static UriMatcher uriMatcher;

	private static final int USERSCODE = 1;
	private static final int USERCODE = 2;
	private String USERS_DIR = "vnd.android.cursor.dir/";
	private String USERS_ITEM = "vnd.android.cursor.item/";

	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		// www.gxw.com.sqlit.provider.usercontentproivder/user代表用户信息操作
		uriMatcher.addURI(AUTHORITIES, "users", USERSCODE);
		// www.gxw.com.sqlit.provider.usercontentproivder/user/1代表查询用户信息
		uriMatcher.addURI(AUTHORITIES, "users/#", USERCODE);

	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		this.dataBaseHelper = new DataBaseHelper(getContext(), 1);
		return false;
	}

	

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		Cursor c = null;
		switch (uriMatcher.match(uri)) {
		case USERCODE:
			long id =  ContentUris.parseId(uri);
			c = db.query("users", projection, "userid",
					new String[] { "" + id }, null, null, sortOrder);
			break;
		case USERSCODE:
			c = db.query("users", projection, selection, selectionArgs, null,
					null, sortOrder);
			break;
		default:
			throw new IllegalArgumentException("Unkonw uri" + uri);
		}

		return c;
	}
	
	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		/**
		 * 操作的条目是多个还是一个
		 */
		String value = null;
		switch (uriMatcher.match(uri)) {
		case USERSCODE:
			value = USERS_DIR;
			break;
		case USERCODE:
			value = USERS_ITEM;
			break;
		}
		return value;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		if (uriMatcher.match(uri) != USERSCODE) {
			throw new IllegalArgumentException("Unkonw uri" + uri);
		}
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		long rowId = db.insert("users", "username", values);
		//db.close();
		//注册监听 通知所有注册在uri上的监听者
		getContext().getContentResolver().notifyChange(uri, null);
		return ContentUris.withAppendedId(uri, rowId);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		int rows = -1;
		switch (uriMatcher.match(uri)) {
		case USERCODE:
			long id = ContentUris.parseId(uri);
			rows = db.delete("users", "userid=?", new String[] { "" + id });
			db.close();
			break;
		case USERSCODE:
			rows = db.delete("users", selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unkonw uri" + uri);
		}

		return rows;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
		int rows = -1;
		switch (uriMatcher.match(uri)) {
		case USERCODE:
			long id = ContentUris.parseId(uri);
			rows = db.update("users", values, "userid=?",
					new String[] { "" + id });
			db.close();
			break;
		case USERSCODE:
			rows = db.update("users", values, selection, selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unkonw uri" + uri);
		}

		return rows;
	}

}
package www.gxw.com.sqlit.dao.impl;

import www.gxw.com.sqlit.dao.BaseDao;
import www.gxw.com.sqlit.dataBase.DataBaseHelper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class BaseDaoImpl implements BaseDao{
	// 依赖DataBaseHelper的对象
		private DataBaseHelper dataBaseHelper;

		public BaseDaoImpl(DataBaseHelper dataBaseHelper) {
			// TODO Auto-generated constructor stub
			this.dataBaseHelper = dataBaseHelper;
		}

		@Override
		public long insert(String table, String nullColumnHack, ContentValues values) {
			SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
			long insert = db.insert(table, nullColumnHack, values);
			db.close();
			return insert;
		}

		@Override
		public Cursor query(String table, String columns[], String selection,
				String[] selectionArgs, String groupBy, String having,
				String orderBy) {
			SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
			return db.query(table, columns, selection, selectionArgs, groupBy,
					having, orderBy);

		}

		@Override
		public Cursor query(String table, String columns[], String selection,
				String[] selectionArgs, String groupBy, String having,
				String orderBy, String limit) {
			SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
			return db.query(table, columns, selection, selectionArgs, groupBy,
					having, orderBy, limit);
		}

		@Override
		public int update(String table, ContentValues values, String whereClause,
				String whereArgs[]) {
			SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
			int i = db.update(table, values, whereClause, whereArgs);
			db.close();
			return i;
		}

		@Override
		public int delete(String table, String whereClause, String[] whereArgs) {
			SQLiteDatabase db = dataBaseHelper.getWritableDatabase();
			int i = db.delete(table, whereClause, whereArgs);
			db.close();
			return i;
		}

}
package www.gxw.com.other2;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity implements OnScrollListener {

	private boolean flag = false;
	private boolean isLastRow = false;

	private ListView lv_users;
	private TextView tv_tip;

	private SimpleCursorAdapter adapter;
	private ContentResolver contentResolver;

	private static final String URL = "content://www.gxw.com.sqlit.provider.usercontentproivder/users";

	private static final int INSERT = 1;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case INSERT:
				tv_tip.setVisibility(View.VISIBLE);
				flag = true;
				tv_tip.setText("有新信息");
				break;

			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		tv_tip = (TextView) findViewById(R.id.tv_tip);
		tv_tip.setVisibility(View.GONE);// 不占用位置,彻底隐藏

		lv_users = (ListView) findViewById(R.id.lv_users);
		// 获取解析内容
		contentResolver = getContentResolver();
		initData();

		lv_users.setOnScrollListener(this);

		// 注册监听器Observer
		/**
		 * 如果为true 模糊匹配
		 */
		getContentResolver().registerContentObserver(Uri.parse(URL), true,
				new UserContentObserver(handler));
	}

	private void initData() {
		Cursor c = contentResolver.query(Uri.parse(URL), new String[] {
				"userid as _id", "username", "userphone" }, null, null,
				"userid desc");
		// 控制层
		adapter = new SimpleCursorAdapter(this, R.layout.list_item_user, c,
				new String[] { "username", "userphone" }, new int[] {
						R.id.tv_name, R.id.tv_phone },
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);

		lv_users.setAdapter(adapter);
	}
	//
	class UserContentObserver extends ContentObserver {

		private Handler handler;

		public UserContentObserver(Handler handler) {
			super(handler);
			// TODO Auto-generated constructor stub
			this.handler = handler;
		}

		@Override
		public void onChange(boolean selfChange) {
			// TODO Auto-generated method stub
			super.onChange(selfChange);
			System.out.println("有新信息插入");
			/*
			 * System.out.println("iiiiiiii"); Toast.makeText(MainActivity.this,
			 * "fasdf", Toast.LENGTH_LONG) .show();
			 */

			handler.sendEmptyMessage(INSERT);
			tv_tip.setText("有新信息");
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		// TODO Auto-generated method stub
	/*	Toast.makeText(this, "========" + scrollState, Toast.LENGTH_LONG)
				.show();*/
		// 有新消息 更新的时候去加载数据
		if (flag && scrollState == OnScrollListener.SCROLL_STATE_FLING) {
			initData();
			flag = false;
	 		tv_tip.setVisibility(View.GONE);
		}

		if (isLastRow && scrollState == OnScrollListener.SCROLL_STATE_FLING) {
			// 去加载数据
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		// TODO Auto-generated method stub
	/*	Toast.makeText(
				this,
				firstVisibleItem + "========" + visibleItemCount + "========="
						+ totalItemCount, Toast.LENGTH_LONG).show();*/

		if ((firstVisibleItem + visibleItemCount) >= totalItemCount
				&& totalItemCount > 0) {
			// 发送请求处理
			isLastRow = true;
		}
	}
}