博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
类查找android中跨项目的数据库操作ContentProvider的使用
阅读量:5788 次
发布时间:2019-06-18

本文共 10737 字,大约阅读时间需要 35 分钟。

上班之余抽点时间出来写写博文,希望对新接触的朋友有帮助。今天在这里和大家一起学习一下类查找

    RuiXin.java类

package com.gtl.data.two;import android.net.Uri;public class RuiXin {		public static final String DBNAME = "ruixinonlinedb";     public static final String TNAME = "ruixinonline";    public static final int VERSION = 3;        public static String TID = "tid";    public static final String USERNAME = "username";    public static final String DATE = "date";    public static final String SEX = "sex";        public static final String AUTOHORITY = "com.gtl.data.two";    public static final int ITEM = 1;    public static final int ITEM_ID = 2;        public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.ruixin.login";    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.ruixin.login";        public static final Uri CONTENT_URI = Uri.parse("content://" + AUTOHORITY + "/ruixinonline");}

    DBlite.java类

package com.gtl.data.two;import android.content.ContentValues;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class DBlite extends SQLiteOpenHelper {	public DBlite(Context context) {		super(context, RuiXin.DBNAME, null, RuiXin.VERSION);	}	@Override	public void onCreate(SQLiteDatabase db) {		db.execSQL("create table "+RuiXin.TNAME+"(" +                 RuiXin.TID+" integer primary key autoincrement not null,"+                 RuiXin.USERNAME+" text not null," +                 RuiXin.DATE+" interger not null,"+                 RuiXin.SEX+" text not null);");	}	@Override	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {		db.execSQL("DROP TABLE IF EXISTS "+RuiXin.TNAME);		onCreate(db);	}		public void add(String username,String date,String sex){        SQLiteDatabase db = getWritableDatabase();        ContentValues values = new ContentValues();        values.put(RuiXin.USERNAME, username);        values.put(RuiXin.DATE, date);        values.put(RuiXin.SEX, sex);        db.insert(RuiXin.TNAME,"",values);	}		public void del(){		 SQLiteDatabase db = getWritableDatabase();		 db.delete(RuiXin.TNAME,RuiXin.DATE+"=?" , new String[]{"time=1368497000287"});	}		public void update(){		SQLiteDatabase db = getWritableDatabase();		ContentValues values = new ContentValues();		values.put(RuiXin.USERNAME, "louis koo");	    values.put(RuiXin.DATE, "today");	    values.put(RuiXin.SEX, "男");		db.update(RuiXin.TNAME, values, RuiXin.DATE+"=?" , new String[]{"time=1368497006097"});	}}

    MyProvider.java类

package com.gtl.data.two;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;import android.text.TextUtils;public class MyProvider extends ContentProvider {		DBlite dBlite;    SQLiteDatabase db;    private static final UriMatcher sMatcher;    static{            sMatcher = new UriMatcher(UriMatcher.NO_MATCH);            sMatcher.addURI(RuiXin.AUTOHORITY,RuiXin.TNAME, RuiXin.ITEM);            sMatcher.addURI(RuiXin.AUTOHORITY, RuiXin.TNAME+"/#", RuiXin.ITEM_ID);    }	@Override	public boolean onCreate() {		this.dBlite = new DBlite(this.getContext());		return true;	}	@Override	public Cursor query(Uri uri, String[] projection, String selection,			String[] selectionArgs, String sortOrder) {		 db = dBlite.getWritableDatabase();                         Cursor c;         switch (sMatcher.match(uri)) {	         case RuiXin.ITEM:	                 c = db.query(RuiXin.TNAME, projection, selection, selectionArgs, null, null, null);	                 break;	         case RuiXin.ITEM_ID:	                 String id = uri.getPathSegments().get(1);	                 c = db.query(RuiXin.TNAME, projection, 	                		 RuiXin.TID+"="+id+(!TextUtils.isEmpty(selection)?"AND("+selection+')':""),	                		 selectionArgs, null, null, sortOrder);	             break;	         default:	                 throw new IllegalArgumentException("Unknown URI"+uri);         }         c.setNotificationUri(getContext().getContentResolver(), uri);         return c;	}	@Override	public String getType(Uri uri) {		switch (sMatcher.match(uri)) {		    case RuiXin.ITEM:		        return RuiXin.CONTENT_TYPE;		    case RuiXin.ITEM_ID:		        return RuiXin.CONTENT_ITEM_TYPE;		    default:		        throw new IllegalArgumentException("Unknown URI"+uri);	    }	}	@Override	public Uri insert(Uri uri, ContentValues values) {		db = dBlite.getWritableDatabase();        long rowId;        if(sMatcher.match(uri)!=RuiXin.ITEM){             throw new IllegalArgumentException("Unknown URI"+uri);        }        rowId = db.insert(RuiXin.TNAME,RuiXin.TID,values);        if(rowId>0){            Uri noteUri=ContentUris.withAppendedId(RuiXin.CONTENT_URI, rowId);            getContext().getContentResolver().notifyChange(noteUri, null);            return noteUri;        }        throw new IllegalArgumentException("Unknown URI"+uri);	}	@Override	public int delete(Uri uri, String selection, String[] selectionArgs) {		 db = dBlite.getWritableDatabase();         int count = 0;         switch (sMatcher.match(uri)) {	         case RuiXin.ITEM:	              count = db.delete(RuiXin.TNAME,selection, selectionArgs);	              break;	         case RuiXin.ITEM_ID:	              String id = uri.getPathSegments().get(1);	              count = db.delete(RuiXin.TID, 	             		 RuiXin.TID+"="+id+(!TextUtils.isEmpty(RuiXin.TID="?")?"AND("+selection+')':""), 	             		 selectionArgs);	             break;	         default:	                 throw new IllegalArgumentException("Unknown URI"+uri);         }         getContext().getContentResolver().notifyChange(uri, null);         return count;	}	@Override	public int update(Uri uri, ContentValues values, String selection,			String[] selectionArgs) {		SQLiteDatabase db = dBlite.getWritableDatabase();		int count;		switch (sMatcher.match(uri)){			case RuiXin.ITEM:				count = db.update(RuiXin.TNAME, values, selection, selectionArgs);				break;			case RuiXin.ITEM_ID:				String Id = uri.getPathSegments().get(1);				count = db.update(RuiXin.TNAME, values,						RuiXin.TID + "=" + Id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""),						selectionArgs);				break;			default:				throw new IllegalArgumentException("Unknown URI " + uri);		}		getContext().getContentResolver().notifyChange(uri, null);		return count;	}}
    每日一道理
记不清有多少个夜晚,在我翻阅纸张的指间滑落;记不清有多少支蜡烛,在我的凝视中化为灰烬。逝者如斯,我时时刻刻会听见自己对生命承诺的余音,感到岁月的流转在渐渐稀释我的年少无知,我愿自己是一只上足了发条的时钟,在昼夜不停的流转中留下自己充实的每一刻。

    主类Test.java类

package com.gtl.data.two;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.content.ContentResolver;import android.database.Cursor;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.Toast;import com.gtl.R;public class Test extends Activity implements OnClickListener{		private DBlite dBlite1 ;    private ContentResolver contentResolver;    private Button addbtn,delbtn,querybtn,updatebtn;    private ListView lv;    	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		dBlite1 = new DBlite(this);		setContentView(R.layout.contentprovide);		addbtn = (Button)findViewById(R.id.btnadd);		delbtn = (Button)findViewById(R.id.btndelete);		querybtn = (Button)findViewById(R.id.btnquery);		updatebtn = (Button)findViewById(R.id.btnupdate);		addbtn.setOnClickListener(this);		delbtn.setOnClickListener(this);		querybtn.setOnClickListener(this);		updatebtn.setOnClickListener(this);		lv = (ListView)findViewById(R.id.lv);			}	private List
strlist; @Override public void onClick(View v) { if(v==addbtn){ dBlite1.add("carman lee","time="+System.currentTimeMillis(),"女"); }else if(v==delbtn){ dBlite1.del(); }else if(v==querybtn){ //通过contentResolver停止查找 strlist = new ArrayList
(); contentResolver = this.getContentResolver(); Cursor cursor = contentResolver.query( RuiXin.CONTENT_URI, new String[] {RuiXin.USERNAME, RuiXin.DATE,RuiXin.SEX }, null, null, null); while (cursor.moveToNext()) { strlist.add(cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME)) + " "+ cursor.getString(cursor.getColumnIndex(RuiXin.DATE)) + " "+ cursor.getString(cursor.getColumnIndex(RuiXin.SEX))); } startManagingCursor(cursor); //查找后关闭游标 ArrayAdapter
adpater = new ArrayAdapter
(Test.this, android.R.layout.simple_expandable_list_item_1,strlist); lv.setAdapter(adpater); }else if(v==updatebtn){ dBlite1.update(); } }}

    接下来在另外一个项目中停止测试,共用一个数据库

    MainActivity.java类

package com.example.contentprovidertest;import java.util.ArrayList;import java.util.List;import android.os.Bundle;import android.app.Activity;import android.content.ContentResolver;import android.database.Cursor;import android.widget.ArrayAdapter;import android.widget.ListView;public class MainActivity extends Activity {		private ContentResolver contentResolver;	private List
strlist; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ListView lv = new ListView(this); //通过contentResolver停止查找 strlist = new ArrayList
(); contentResolver = this.getContentResolver(); Cursor cursor = contentResolver.query( RuiXin.CONTENT_URI, new String[] {RuiXin.USERNAME, RuiXin.DATE,RuiXin.SEX }, null, null, null); while (cursor.moveToNext()) { strlist.add(cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME)) + " "+ cursor.getString(cursor.getColumnIndex(RuiXin.DATE)) + " "+ cursor.getString(cursor.getColumnIndex(RuiXin.SEX))); } startManagingCursor(cursor); //查找后关闭游标 ArrayAdapter
adpater = new ArrayAdapter
(this, android.R.layout.simple_expandable_list_item_1,strlist); lv.setAdapter(adpater); setContentView(lv); }}

    将参数也复制到该项目工程中去

    清单文件AndroidManifest.xml

 

文章结束给大家分享下程序员的一些笑话语录: 很多所谓的牛人也不过如此,离开了你,微软还是微软,Google还是Google,苹果还是苹果,暴雪还是暴雪,而这些牛人离开了公司,自己什么都不是。

转载地址:http://whlyx.baihongyu.com/

你可能感兴趣的文章
9套Android实战经典项目资料分享给大家
查看>>
第2个程序:用C语言实现点亮一盏led
查看>>
.net消息队列
查看>>
sys.stdout.write与sys.sterr.write(一)
查看>>
向Maven的本地库中添加jar文件
查看>>
centos7.0上安装五笔输入法
查看>>
10.1综合强化刷题 Day1 morning
查看>>
Ubuntu notes
查看>>
spring之jdbcTemplate的增删改查操作--不使用配置文件
查看>>
iOS8中添加的extensions总结(一)——今日扩展
查看>>
luogu P1462 通往奥格瑞玛的道路
查看>>
IOS中的多线程之GCD
查看>>
oracle快速创建可用用户
查看>>
添加捕获异常
查看>>
POJ 1745 Divisibility【DP】
查看>>
KVM虚拟机管理
查看>>
BloomFilter ——大规模数据处理利器
查看>>
数位DP按位枚举模板
查看>>
配置LANMP环境(9)-- 安装Git与vsftp
查看>>
Java 中的PO VO DTO BO
查看>>