Android 数据存储与共享 总结

工作中遇到了contentprovider数据共享机制,下面来总结一下:

一、ContentProvider简介
应用继承ContentProvider类,并重写该类用于提供数据和存储数据的方法,就可以向其他应用共享其数据。虽然使用其他方法也可以对外共享数据,但数据访问方式会因数据存储的方式而不同,如:采用文件方式对外共享数据,需要进行文件操作读写数据;采用sharedpreferences共享数据,需要使用sharedpreferences API读写数据。而使用ContentProvider共享数据的好处是统一了数据访问方式。
二、Uri类简介
Uri代表了要操作的数据,Uri主要包含了两部分信息:1.需要操作的ContentProvider ,2.对ContentProvider中的什么数据进行操作,一个Uri由以下几部分组成:

1.scheme:ContentProvider(内容提供者)的scheme已经由Android所规定为:content://。
2.主机名(或Authority):用于唯一标识这个ContentProvider,外部调用者可以根据这个标识来找到它。
3.路径(path):可以用来表示我们要操作的数据,路径的构建应根据业务而定,如下:
• 要操作contact表中id为10的记录,可以构建这样的路径:/contact/10
• 要操作contact表中id为10的记录的name字段, contact/10/name
• 要操作contact表中的所有记录,可以构建这样的路径:/contact
要操作的数据不一定来自数据库,也可以是文件等他存储方式,如下:
要操作xml文件中contact节点下的name节点,可以构建这样的路径:/contact/name
如果要把一个字符串转换成Uri,可以使用Uri类中的parse()方法,如下:
Uri uri = Uri.parse("content://com.changcheng.provider.contactprovider/contact")
三、UriMatcher、ContentUrist和ContentResolver简介
因为Uri代表了要操作的数据,所以我们很经常需要解析Uri,并从Uri中获取数据。Android系统提供了两个用于操作Uri的工具类,分别为UriMatcher 和ContentUris 。掌握它们的使用,会便于我们的开发工作。

UriMatcher:用于匹配Uri,它的用法如下:
1.首先把你需要匹配Uri路径全部给注册上,如下:
//常量UriMatcher.NO_MATCH表示不匹配任何路径的返回码(-1)。
UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
//如果match()方法匹配content://com.changcheng.sqlite.provider.contactprovider/contact路径,返回匹配码为1
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact”, 1);//添加需要匹配uri,如果匹配就会返回匹配码
//如果match()方法匹配 content://com.changcheng.sqlite.provider.contactprovider/contact/230路径,返回匹配码为2
uriMatcher.addURI(“com.changcheng.sqlite.provider.contactprovider”, “contact/#”, 2);//#号为通配符

2.注册完需要匹配的Uri后,就可以使用uriMatcher.match(uri)方法对输入的Uri进行匹配,如果匹配就返回匹配码,匹配码是调用addURI()方法传入的第三个参数,假设匹配content://com.changcheng.sqlite.provider.contactprovider/contact路径,返回的匹配码为1。

ContentUris:用于获取Uri路径后面的ID部分,它有两个比较实用的方法:
• withAppendedId(uri, id)用于为路径加上ID部分
• parseId(uri)方法用于从路径中获取ID部分

ContentResolver:当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,可以使用Activity提供的getContentResolver()方法。 ContentResolver使用insert、delete、update、query方法,来操作数据。
四、ContentProvider示例程序
Manifest.xml中的代码

<application android:icon="@drawable/icon" android:label="@string/app_name"> 
                <activity android:name=".TestWebviewDemo" android:label="@string/app_name"> 
                        <intent-filter> 
                                <action android:name="android.intent.action.MAIN" /> 
                                <category android:name="android.intent.category.LAUNCHER" /> 
                        </intent-filter> 
                        <intent-filter> 
                                <data android:mimeType="vnd.android.cursor.dir/vnd.ruixin.login" /> 
                        </intent-filter> 
                        <intent-filter> 
                                <data android:mimeType="vnd.android.cursor.item/vnd.ruixin.login" /> 
                        </intent-filter> 
                          
                </activity> 
                <provider android:name="MyProvider" android:authorities="com.ruixin.login" /> 
        </application>
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 EMAIL = "email"; 
        public static final String USERNAME = "username"; 
        public static final String DATE = "date"; 
        public static final String SEX = "sex"; 
          
          
        public static final String AUTOHORITY = "com.ruixin.login"; 
        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"); 
} 

 

然后创建一个数据库:

?1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 public class DBlite extends SQLiteOpenHelper { 
        public DBlite(Context context) { 
                super(context, RuiXin.DBNAME, null, RuiXin.VERSION); 
                // TODO Auto-generated constructor stub 
        } 
        @Override
        public void onCreate(SQLiteDatabase db) { 
                // TODO Auto-generated method stub 
                        db.execSQL("create table "+RuiXin.TNAME+"(" + 
                                RuiXin.TID+" integer primary key autoincrement not null,"+ 
                                RuiXin.EMAIL+" text 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) { 
                // TODO Auto-generated method stub 
        } 
        public void add(String email,String username,String date,String sex){ 
                SQLiteDatabase db = getWritableDatabase(); 
                ContentValues values = new ContentValues(); 
                values.put(RuiXin.EMAIL, email); 
                values.put(RuiXin.USERNAME, username); 
                values.put(RuiXin.DATE, date); 
                values.put(RuiXin.SEX, sex); 
                db.insert(RuiXin.TNAME,"",values); 
        } 
} 

接着创建一个Myprovider.java对数据库的接口进行包装:

?1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102 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 int delete(Uri uri, String selection, String[] selectionArgs) { 
                // TODO Auto-generated method stub 
                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 String getType(Uri uri) { 
                // TODO Auto-generated method stub 
                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) { 
                // TODO Auto-generated method stub 
                  
                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 boolean onCreate() { 
                // TODO Auto-generated method stub 
                this.dBlite = new DBlite(this.getContext()); 
//                db = dBlite.getWritableDatabase(); 
//                return (db == null)?false:true; 
                return true; 
        } 
  
        @Override
        public Cursor query(Uri uri, String[] projection, String selection, 
                        String[] selectionArgs, String sortOrder) { 
                // TODO Auto-generated method stub 
                db = dBlite.getWritableDatabase();                 
                Cursor c; 
                Log.d("-------", String.valueOf(sMatcher.match(uri))); 
                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: 
                        Log.d("!!!!!!", "Unknown URI"+uri); 
                        throw new IllegalArgumentException("Unknown URI"+uri); 
                } 
                c.setNotificationUri(getContext().getContentResolver(), uri); 
                return c; 
        } 
        @Override
        public int update(Uri uri, ContentValues values, String selection, 
                        String[] selectionArgs) { 
                // TODO Auto-generated method stub 
                return 0; 
        } 
} 



最后创建测试类:

?1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 public class Test extends Activity { 
    /** Called when the activity is first created. */
   private DBlite dBlite1 = new DBlite(this);; 
        private ContentResolver contentResolver; 
                    public void onCreate(Bundle savedInstanceState) { 
                super.onCreate(savedInstanceState); 
                setContentView(R.layout.main); 
                //先对数据库进行添加数据 
            dBlite1.add(email,username,date,sex); 
            //通过contentResolver进行查找 
             contentResolver = TestWebviewDemo.this.getContentResolver(); 
            Cursor cursor = contentResolver.query( 
                  RuiXin.CONTENT_URI, new String[] { 
                  RuiXin.EMAIL, RuiXin.USERNAME, 
                  RuiXin.DATE,RuiXin.SEX }, null, null, null); 
                while (cursor.moveToNext()) { 
                     Toast.makeText( 
                    TestWebviewDemo.this, 
                    cursor.getString(cursor.getColumnIndex(RuiXin.EMAIL)) 
                            + " "
                            + cursor.getString(cursor.getColumnIndex(RuiXin.USERNAME)) 
                            + " "
                            + cursor.getString(cursor.getColumnIndex(RuiXin.DATE)) 
                            + " "
                            + cursor.getString(cursor.getColumnIndex(RuiXin.SEX)), 
                           Toast.LENGTH_SHORT).show(); 
                     } 
                   startManagingCursor(cursor);  //查找后关闭游标 
            } 
        } 

http://www.cnblogs.com/chenglong/articles/1892029.html


02:

  SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。实现SharedPreferences存储的步骤如下:

  一、根据Context获取SharedPreferences对象

  二、利用edit()方法获取Editor对象。

  三、通过Editor对象存储key-value键值对数据。

  四、通过commit()方法提交数据。

  具体实现代码如下:

复制代码
 1 public class MainActivity extends Activity {
 2     @Override
 3     public void onCreate(Bundle savedInstanceState) {
 4        super.onCreate(savedInstanceState);
 5        setContentView(R.layout.main);
 6        
 7        //获取SharedPreferences对象
 8        Context ctx = MainActivity.this;       
 9        SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
10        //存入数据
11        Editor editor = sp.edit();
12        editor.putString("STRING_KEY", "string");
13        editor.putInt("INT_KEY", 0);
14        editor.putBoolean("BOOLEAN_KEY", true);
15        editor.commit();
16        
17        //返回STRING_KEY的值
18        Log.d("SP", sp.getString("STRING_KEY", "none"));
19        //如果NOT_EXIST不存在,则返回值为"none"
20        Log.d("SP", sp.getString("NOT_EXIST", "none"));
21     }
22 }
复制代码

   这段代码执行过后,即在/data/data/com.test/shared_prefs目录下生成了一个SP.xml文件,一个应用可以创建多个这样的xml文件。如图所示:

  SP.xml文件的具体内容如下:

1 <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
2 <map>
3 <string name="STRING_KEY">string</string>
4 <int name="INT_KEY" value="0" />
5 <boolean name="BOOLEAN_KEY" value="true" />
6 </map>

  在程序代码中,通过getXXX方法,可以方便的获得对应Key的Value值,如果key值错误或者此key无对应value值,SharedPreferences提供了一个赋予默认值的机会,以此保证程序的健壮性。如下图运行结果中因为并无值为"NOT_EXIST"的Key,所以Log打印出的是其默认值:“none”。在访问一个不存在key值这个过程中,并无任何异常抛出。  

  SharedPreferences对象与SQLite数据库相比,免去了创建数据库,创建表,写SQL语句等诸多操作,相对而言更加方便,简洁。但是SharedPreferences也有其自身缺陷,比如其职能存储boolean,int,float,long和String五种简单的数据类型,比如其无法进行条件查询等。所以不论SharedPreferences的数据存储操作是如何简单,它也只能是存储方式的一种补充,而无法完全替代如SQLite数据库这样的其他数据存储方式。

http://www.cnblogs.com/wisekingokok/archive/2011/09/16/2177833.html


003

 SQLite是一种转为嵌入式设备设计的轻型数据库,其只有五种数据类型,分别是:

    NULL: 空值

    INTEGER: 整数

    REAL: 浮点数

    TEXT: 字符串

    BLOB: 大数据

  在SQLite中,并没有专门设计BOOLEAN和DATE类型,因为BOOLEAN型可以用INTEGER的0和1代替true和false,而DATE类型则可以拥有特定格式的TEXT、REAL和INTEGER的值来代替显示,为了能方便的操作DATE类型,SQLite提供了一组函数,详见:http://www.sqlite.org/lang_datefunc.html。这样简单的数据类型设计更加符合嵌入式设备的要求。关于SQLite的更多资料,请参看:http://www.sqlite.org/

  在Android系统中提供了android.database.sqlite包,用于进行SQLite数据库的增、删、改、查工作。其主要方法如下:

  beginTransaction(): 开始一个事务。

  close(): 关闭连接,释放资源。

  delete(String table, String whereClause, String[] whereArgs): 根据给定条件,删除符合条件的记录。

  endTransaction(): 结束一个事务。

  execSQL(String sql): 执行给定SQL语句。

  insert(String table, String nullColumnHack, ContentValues values): 根据给定条件,插入一条记录。 

  openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory): 根据给定条件连接数据库,如果此数据库不存在,则创建。

  query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy): 执行查询。

  rawQuery(String sql, String[] selectionArgs): 根据给定SQL,执行查询。

  update(String table, ContentValues values, String whereClause, String[] whereArgs): 根据给定条件,修改符合条件的记录。

  除了上诉主要方法外,Android还提供了诸多实用的方法,总之一句话:其实Android访问数据库是一件很方便的事儿。

  一、 创建数据库

  通过openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)方法创建数据库。    

1 SQLiteDatabase db = this.openOrCreateDatabase("test_db.db", Context.MODE_PRIVATE, null);
2 SQLiteDatabase db2 = SQLiteDatabase.openOrCreateDatabase("/data/data/com.test/databases/test_db2.db3", null);

  如上两种方式均能创建数据库,this.openOrCreateDatabase是对SQLiteDatabase.openOrCreateDatabase而来,如代码所见,原生的SQLiteDatabase.openOrCreateDatabase()方法第一参数要求输入绝对路劲,而所有的数据库都是储存于“data/data/应用报名/databases”目录下,所以输入完全的绝对路劲是一件重复且繁杂的工作。采用this.openOrCreateDatabase则省去了此操作。执行操作后的结果如下图:  

 

  另外还可以通过写一个继承SQLiteOpenHelper类的方式创建数据库,此种方式是一种更加进阶的创建方式,所以在此不做描述。

  二、创建数据表,插入数据。

  Android系统并没有提供特别的创建数据表的方法,数据表通过SQL语句创建,代码如下:

1 db.execSQL("create table tab(_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)");

  表创建好之后,通过insert(String table, String nullColumnHack, ContentValues values)方法插入数据,其中参数含义分别为:

    table: 目标表名

    nullColumnHack: 指定表中的某列列名。因为在SQLite中,不允许不允许插入所有列均为null的记录,因此初始值有值为空时,此列需显式赋予null

    values: ContentValues对象,类似于java中的Map。以键值对的方式保存数据。

  数据插入代码如下:

1  ContentValues values = new ContentValues();
2    for(int i=0;i<10;i++){
3        values.put("name", "test" + i);
4        db.insert("tab", "_id", values);
5    }

  执行此操作后,会新增一个名为“tab”的数据表,利用SQLite客户端(推荐:SQLite Expert Personal 3)可轻松查看此表结构和数据。如下图:

  

  三、修改数据

  update(String table, ContentValues values, String whereClause, String[] whereArgs)方法用于修改数据,其四个参数的具体含义如下:

    table: 目标表名

    values: 要被修改成为的新值

    whereClause: where子句,除去where关键字剩下的部分,其中可带?占位符。如没有子句,则为null。

    whereArgs: 用于替代whereClause参数中?占位符的参数。如不需传入参数,则为null。

  数据修改代码如下:

1 ContentValues values = new ContentValues();
2 values.put("name", "name");
3 db.update("tab", values, "_id=1", null); 
4 db.update("tab", values, "_id=?", new String[]{"5"});

  执行结果如下图,_id=1和_id=5的数据,name字段的值被修改为了“name”。

  四、查询数据。

  之前一直使用SQLite客户端查看数据情况了,这里就使用android提供的query()和rowQuery()方法执行查询。具体代码如下:

复制代码
 1 Cursor c = db.query("tab", null, null, null, null, null, null);
 2 c.moveToFirst();
 3 while(!c.isAfterLast()){
 4     int index = c.getColumnIndex("name");
 5     Log.d("SQLite", c.getString(index));
 6     c.moveToNext();
 7 }
 8 c = db.rawQuery("select * from tab", null);
 9 c.moveToFirst();
10 while(!c.isAfterLast()){
11     int index = c.getColumnIndex("name");
12     Log.d("SQLite", c.getString(index));
13     c.moveToNext();
14 }
复制代码

  查询结果如下图:

  可以清晰的在查询结果中,红线上下的数据是完全一致的,也就是说query和rawQuery方法在的不同仅仅在于所需参数的不同。rawQuery方法需要开发者手动写出查询SQL,而query方法是由目标表名、where子句、order by子句、having子句等诸多子句由系统组成SQL语句。两方法同返回Cursor对象,所以两方在使用时孰优孰劣,就看具体情况了。本人更喜欢rawQuery的方式,因为此方式更接近传统Java开发,也可以由专业DBA来书写SQL语句,这样更符合MVC的思想,而且这样的代码可读性更高。(query方法里面参数实在太多,有点记不住谁是order by子句,谁是having子句了)

  Cursor对象可以理解为游标对象,凡是对数据有所了解的人,相信对此对象都不会陌生,在这里机不再累述。只提醒一点,在第一次读取Cursor对象中的数据时,一定要先移动游标,否则此游标的位置在第一条记录之前,会引发异常。

  五、删除数据

  删除数据也是一件很简单的事,只需要调用delete方法,传入参数即可,delete(String table, String whereClause, String[] whereArgs)的参数三个参数具体含义如下:

    table: 目标表名

    whereClause: where子句,除去where关键字剩下的部分,其中可带?占位符。如没有子句,则为null。

    whereArgs: 用于替代whereClause参数中?占位符的参数。如不需传入参数,则为null。

  具体代码如下:

db.delete("tab", "_id=? or name=?", new String[]{"8", "name"});

  执行结果如下:

  其中_id=8和name=‘name’的数据统统被删除了。

  整个数据库的CRUD操作到此演示完了。最后提醒一点,在操作完数据后,一定要记得调用close()方法关闭连接,释放资源。这个原因相信大家都是懂的。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值