初识 sqlite 与 content provider 学习笔记

前端之家收集整理的这篇文章主要介绍了初识 sqlite 与 content provider 学习笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1,sqlite 简单使用

@H_403_61@

1,sqlite支持的数据类型

  • NULL. The value is a NULL value.

  • INTEGER. The value is a signed integer,stored in 1,2,3,4,6,or 8 bytes depending on the magnitude of the value.

  • REAL. The value is a floating point value,stored as an 8-byte IEEE floating point number.

  • TEXT. The value is a text string,stored using the database encoding (UTF-8,UTF-16BE or UTF-16LE).

  • BLOB. The value is a blob of data,stored exactly as it was input.

2,相关数据库定义数据类型词与sqlite数据类型的关联表

@H_403_61@ @H_403_61@ @H_403_61@ @H_403_61@ @H_403_61@ @H_403_61@
Example Typenames From The
CREATE TABLE Statement
or CAST Expression
Resulting Affinity Rule Used To Determine Affinity
INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8
INTEGER 1
CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
TEXT 2
BLOB
no datatype specified
NONE 3
REAL
DOUBLE
DOUBLE PRECISION
FLOAT
REAL 4
NUMERIC
DECIMAL(10,5)
BOOLEAN
DATE
DATETIME
NUMERIC 5

把数据类型搞定了…我们就开始使用我们的android的sqlite了…

第一步:实现一个sqliteOpenHelper类

      
      
  1. //创建一个继承sqliteOpenHelper类
  2. publicclassMyOpenHelperextendssqliteOpenHelper{
  3. //必须实现的一个构造方法publicMyOpenHelper(Contextcontext,Stringname,CursorFactoryfactory,intversion){super(context,name,factory,version);
  4. //TODOAuto-generatedconstructorstub}
  5. //设置数据库初始化版本号
  6. privatestaticfinalintDATABASE_VERSION=1;
  7. //设置数据库创建的表名
  8. privatestaticfinalStringTABLE_NAME="users";
  9. //构建创建表的sql的语句
  10. privatestaticfinalStringTABLE_CREATE_sql="CREATETABLE"+
  11. TABLE_NAME+"(idINTEGERprimarykey,nameTEXT)";
  12. //自定义构造方法传入content,与数据库名字
  13. publicMyOpenHelper(Contextcontext,Stringname){this(context,null,DATABASE_VERSION);}
  14. //自定义构造方法传入用来升级数据库的版本号
  15. publicMyOpenHelper(Contextcontext,intversion){
  16. this(context,version);}@OverridepublicvoidonCreate(sqliteDatabasedb){
  17. //TODOAuto-generatedmethodstub
  18. Log.d("sqlite","sql-->CreateTable"+TABLE_CREATE_sql);
  19. db.execsql(TABLE_CREATE_sql);}
  20. @Override
  21. publicvoidonUpgrade(sqliteDatabasedb,intoldVersion,intnewVersion){
  22. //TODOAuto-generatedmethodstub}}

ok

第二步:使用MyOpenHelper

     
     
  1. //某
  2. String dataBaseName = "employee"';
  3. MyOpenHelper moh = new MyOpenHelper(sqlite_contentproviderActivity.this,dataBaseName );
  4. sqliteDatabase sdb = moh.getReadableDatabase();
  5. toastsql = Toast.makeText(context,"创建数据库成功",Toast.LENGTH_LONG);
  6. toastsql.show();

1,我们到adb 中查看在设备中我们保存的数据库文件

cd /data/data/<package_name>/databases

2,ls 命令看下

3,用sqlite3命令进入数据库

这样我们就看到我们刚才创建的表了…

这里给出插入操作的代码

     
     
  1. StringdatabaseName="employee";
  2. MyOpenHelpermoh=newMyOpenHelper(sqlite_contentproviderActivity.this,databaseName);
  3. //获取一个可写操作
  4. sqliteDatabasesdb=moh.getWritableDatabase();
  5. ContentValuescv=newContentValues();
  6. String[]name={"tom","achai","nevin","week"};
  7. for(inti=0;i<name.length;i++){
  8. cv.put("name",name[i]);
  9. sdb.insert("users",cv);
  10. }

剩下的操作…请阅读官方文档sqliteDatabase里面的方法

2,创建属于自己的content provider

@H_403_61@

1,建立一个属于自己的content provider你必须要做

  1. 设置一个存储数据的地方,可以使用android 提供的文件存储方法,或者使用sqlite databases,然而,你可以存储任何你想要的数据,android提供的sqliteOpenHelper可以帮助你创建属于和管理你自己的数据库,
  2. 实现ContentProvider 提供用于访问数据的类
  3. 在AndroidManifest.xml,声明你的 content provider

2,编写一个数据工具类
       
       
  1. publicclassContentProviderData{
  2. publicstaticfinalStringAUTHORIY="kg.tom.FirstProvider";
  3. publicclassContentProviderData{
  4. //定义我们provider使用的认证uri
  5. publicstaticfinalStringAUTHORIY="kg.tom.FirstProvider";
  6. //定义我们数据库的名字
  7. publicstaticfinalStringDATABASE_NAME="kg_tom_pro_test";
  8. //定义数据库的版本号
  9. publicstaticfinalintDATABASE_VERSION=1;
  10. //定义创建表的名字
  11. publicstaticfinalStringUSERS_TABLE_NAME="users";
  12. //实现BaseColums,自带两列,_id,_count
  13. publicstaticfinalclassUserTableMetaDataimplementsBaseColumns{
  14. //定义创建表的名字
  15. publicstaticfinalStringTABLE_NAME="users";
  16. //定义provider的uri
  17. publicstaticfinalUriCONTENT_URI=Uri.parse("content://"+AUTHORIY+"/users");
  18. //定义一条数据的类型
  19. publicstaticfinalStringCONTENT_TYPE="vnd.android.cursor.dir/vnd.firstprovider.user";
  20. //定义一组数据的类型
  21. publicstaticfinalStringCONTENT_TYPE_ITEM="vnd.android.cursor.item/vnd.fiRSStprovider.user";
  22. //定义列名
  23. publicstaticfinalStringUSER_NAME="name";
  24. //定义排序规则
  25. publicstaticfinalStringDEFULT_SORT_ORDER="_iddesc";
  26. }}

2,继承content provider 类

继承这个类我们同时要实现以下几个方法:

query()
insert()
update()
delete()
getType()
onCreate()

还有必须添加一个UriMatcher对象

关于UriMatcher对象的使用文档有很好的解释

     
     
  1. //定义URI标识符,数值定义请参考文档
  2. publicstaticfinalintINCOMING_USER_COLLECTION=1;
  3. publicstaticfinalintINCOMING_USER_SINGLE=2;
  4. //定义UriMatcher对象
  5. publicstaticfinalUriMatcheruMatcher;
  6. //把标识符加入到URI中,固定写法
  7. static{
  8. uMatcher=newUriMatcher(UriMatcher.NO_MATCH);
  9. //第一个参数为
  10. contentproviderauthoriy
  11. uMatcher.addURI(AUTHORIY,"users",INCOMING_USER_COLLECTION);
  12. uMatcher.addURI(AUTHORIY,"users/#",INCOMING_USER_SINGLE);}

一个完整的content provider

     
     
  1. publicclassFirstProviderextendsContentProvider{
  2. //定义URI标识符
  3. publicstaticfinalintINCOMING_USER_COLLECTION=1;
  4. publicstaticfinalintINCOMING_USER_SINGLE=2;
  5. //定义UriMatcher对象
  6. publicstaticfinalUriMatcheruMatcher;
  7. //把标识符加入到URI中,固定写法
  8. static{
  9. uMatcher=newUriMatcher(UriMatcher.NO_MATCH);uMatcher.addURI(ContentProviderData.AUTHORIY,INCOMING_USER_COLLECTION);
  10. uMatcher.addURI(ContentProviderData.AUTHORIY,INCOMING_USER_SINGLE);}
  11. //这里是定义查询用的列名的别名
  12. publicstaticHashMap<String,String>userMap;
  13. privateDataBaseHelperdh;
  14. static{
  15. userMap=newHashMap<String,String>();
  16. userMap.put(UserTableMetaData._ID,"id");
  17. userMap.put(UserTableMetaData.USER_NAME,
  18. UserTableMetaData.USER_NAME);}
  19. @Override
  20. publicintdelete(Uriuri,Stringselection,String[]selectionArgs){
  21. //TODOAuto-generatedmethodstub
  22. return0;}
  23. //根据传入的URI
  24. @Override
  25. publicStringgetType(Uriuri){
  26. //TODOAuto-generatedmethodstub
  27. Log.d("sqlite","getType-->");
  28. switch(uMatcher.match(uri)){
  29. caseINCOMING_USER_COLLECTION:
  30. returnUserTableMetaData.CONTENT_TYPE;
  31. caseINCOMING_USER_SINGLE:
  32. returnUserTableMetaData.CONTENT_TYPE_ITEM;default:
  33. thrownewIllegalArgumentException("unKnownuri"+uri);}}
  34. @Override
  35. publicUriinsert(Uriuri,ContentValuesvalues){
  36. //TODOAuto-generatedmethodstub
  37. Log.d("insert","class"+getClass());
  38. Log.d("insert","content"+getContext());
  39. sqliteDatabasedb=dh.getWritableDatabase();
  40. longrowId=db.insert(UserTableMetaData.TABLE_NAME,values);
  41. if(rowId>0){
  42. UriinsertUri=ContentUris.withAppendedId
  43. (UserTableMetaData.CONTENT_URI,rowId);
  44. getContext().getContentResolver().notifyChange(insertUri,null);
  45. returninsertUri;}
  46. returnnull;}
  47. @Override
  48. publicbooleanonCreate(){
  49. //TODOAuto-generatedmethodstub
  50. Log.d("sqlite","createPro--->");
  51. dh=newDataBaseHelper(getContext(),ContentProviderData.DATABASE_NAME);
  52. //sqliteDatabasedb=dh.getReadableDatabase();returntrue;}
  53. @Override
  54. publicCursorquery(Uriuri,String[]projection,
  55. String[]selectionArgs,StringsortOrder){
  56. //TODOAuto-generatedmethodstub
  57. sqliteQueryBuilderqb=newsqliteQueryBuilder();
  58. switch(uMatcher.match(uri)){
  59. caseINCOMING_USER_COLLECTION:
  60. qb.setTables(UserTableMetaData.TABLE_NAME);
  61. qb.setProjectionMap(userMap);
  62. break;
  63. caseINCOMING_USER_SINGLE:
  64. qb.setTables(UserTableMetaData.TABLE_NAME);
  65. qb.setProjectionMap(userMap);
  66. qb.appendWhere(UserTableMetaData._ID+"="+
  67. uri.getPathSegments().get(1));
  68. break;}
  69. StringorderBy;
  70. if(TextUtils.isEmpty(sortOrder)){
  71. orderBy=UserTableMetaData.DEFULT_SORT_ORDER;}else{
  72. orderBy=sortOrder;}
  73. sqliteDatabasedb=dh.getWritableDatabase();
  74. Cursorc=qb.query(db,projection,selection,
  75. selectionArgs,sortOrder);
  76. c.setNotificationUri(getContext().getContentResolver(),uri);
  77. Log.d("sqlite","first--->>");returnc;}
  78. @Override
  79. publicintupdate(Uriuri,ContentValuesvalues,
  80. String[]selectionArgs){
  81. //TODOAuto-generatedmethodstub
  82. return0;}}

3,在activity中的方法中用上这几行代码就可以进行插入

     
     
  1. //定义插入用数据的对象,本质是一个
  2. mapContentValuesvalues=newContentValues();
  3. //键,值对values.put("id",1);
  4. //定义表名
  5. Stringname=ContentProviderData.USERS_TABLE_NAME;
  6. //键值对
  7. values.put(ContentProviderData.UserTableMetaData.USER_NAME,"tom");
  8. //进行contentprovider的插入操作
  9. Uriuri=getContentResolver().insert(
  10. ContentProviderData.UserTableMetaData.CONTENT_URI,values);

至于剩下的

query()

delete()

自己参照文档补全吧

原文链接:https://www.f2er.com/sqlite/202515.html

猜你在找的Sqlite相关文章