Skip to content

Commit

Permalink
Commit
Browse files Browse the repository at this point in the history
  • Loading branch information
CharonChui committed Feb 12, 2014
1 parent eee5d06 commit ab23823
Show file tree
Hide file tree
Showing 2 changed files with 361 additions and 0 deletions.
209 changes: 209 additions & 0 deletions day02Android数据存储.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,215 @@ day02Android数据存储
```
4. SQLiteDatabase
Store structured data in a private database.
Android平台中嵌入了一个关系型数据库SQLite,和其他数据库不同的是SQLite存储数据时不区分类型,例如一个字段声明为Integer类型,我们也可以将一个字符串存入,一个字段声明为布尔型,我们也可以存入浮点数。除非是主键被定义为Integer,这时只能存储64位整数创建数据库的表时可以不指定数据类型,例如:
`CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20))`
`CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name)`
SQLite支持大部分标准SQL语句,增删改查语句都是通用的,分页查询语句和MySQL相同
`SELECT * FROM person LIMIT 20 OFFSET 10`
`SELECT * FROM person LIMIT 10,20`
1. 继承SQLiteOpenHelper
```java
public class NoteSQLiteOpenHelper extends SQLiteOpenHelper {

private static final String TAG = "NoteSQLiteOpenHelper";
/**
* context 上下文 name 数据库的名称 cursorfactory 游标工厂 一般设置null 默认游标工厂 version 数据库的版本
* 版本号从1开始的
*
* @param context
*/
public NoteSQLiteOpenHelper(Context context) {
super(context, "note.db", null, 1);
}

/**
* oncreate 方法 会在数据库第一创建的时候的是被调用 适合做数据库表结构的初始化
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "oncreate 方法被调用了...");
db.execSQL("create table account (id integer primary key autoincrement , name varchar(20), money varchar(20) )");
}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
Log.i(TAG,"onupdate 方法被调用了 ,在这个方法里面做更新数据库表结构的操作");
db.execSQL("DROP TABLE IF EXISTS " + account);
this.onCreate(db);
}
}
```
2. 获取
```java
public class NoteDao {
// 因为 任何一个操作都是需要 得到 NoteSQLiteOpenHelper helper
// 把他放在构造方法里面初始化
private NoteSQLiteOpenHelper helper;

public NoteDao(Context context) {
helper = new NoteSQLiteOpenHelper(context);
}

/**
* 添加一条账目信息 到数据库
*
* @param name
* 花销的名称
* @param money
* 金额
*/
public void add(String name, float money) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("insert into account (name,money) values (?,?)",
new Object[] { name, money });
// 记住 关闭.
db.close();
}

public void delete(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("delete from account where id=?", new Object[] { id });
db.close();
}

public void update(int id, float newmoney) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update account set money =? where id=?", new Object[] {
newmoney, id });
db.close();
}

/**
* 返回数据库所有的条目
*
* @return
*/
public List<NoteBean> findAll() {
// 得到可读的数据库
SQLiteDatabase db = helper.getReadableDatabase();
List<NoteBean> noteBeans = new ArrayList<NoteBean>();
// 获取到数据库查询的结果游标
Cursor cursor = db.rawQuery("select id,money,name from account ", null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
float money = cursor.getFloat(cursor.getColumnIndex("money"));
NoteBean bean = new NoteBean(id, money, name);
noteBeans.add(bean);
bean = null;
}

db.close();
return noteBeans;
}

/**
* 模拟一个转账的操作. 使用数据库的事务
*
* @throws Exception
*/
public void testTransaction() throws Exception {
// 得到可写的数据库
SQLiteDatabase db = helper.getWritableDatabase();
db.beginTransaction(); // 开始事务
try {
db.execSQL("update account set money = money - 5 where id=? ",
new String[] { "2" });
db.execSQL("update account set money = money + 5 where id=? ",
new String[] { "3" });
db.setTransactionSuccessful();
} catch (Exception e) {
// TODO: handle exception
} finally {
db.endTransaction();//关闭事务.
db.close();
}
}
}
```

```java
public class NoteDao2 {
private NoteSQLiteOpenHelper helper;

public NoteDao2(Context context) {
helper = new NoteSQLiteOpenHelper(context);
}

/**
* 添加一条账目信息 到数据库
*
* @param name
* 花销的名称
* @param money
* 金额
*
* @return true 插入成功 false 失败
*/
public boolean add(String name, float money) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("money", money);
long rawid = db.insert("account", null, values);
db.close();
if (rawid > 0) {
return true;
} else {
return false;
}
}

public boolean delete(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
int result = db.delete("account", "id=?", new String[] { id + "" });
db.close();
if (result > 0) {
return true;
} else {
return false;
}
}

public boolean update(int id, float newmoney) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", id);
values.put("money", newmoney);
int result = db.update("account", values, "id=?", new String[] { id
+ "" });
db.close();
if (result > 0) {
return true;
} else {
return false;
}
}

/**
* 返回数据库所有的条目
*
* @return
*/
public List<NoteBean> findAll() {
// 得到可读的数据库
SQLiteDatabase db = helper.getReadableDatabase();
List<NoteBean> noteBeans = new ArrayList<NoteBean>();
Cursor cursor = db.query("account", new String[] { "id", "name",
"money" }, null, null, null, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
float money = cursor.getFloat(cursor.getColumnIndex("money"));
NoteBean bean = new NoteBean(id, money, name);
noteBeans.add(bean);
bean = null;
}
db.close();
return noteBeans;
}
}
```
5. Network
Store data on the web with your own network server.

Expand Down
152 changes: 152 additions & 0 deletions day03内容提供者.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
day02Android数据存储
===

1. ContentProvider
一个可以在不同应用程序间共享数据的组件,相当于一个中间人,一边把数据暴露给这个中间人,另一边是别的应用通过这个中间人获取相应的数据。
1. 继承ContentProvider,并实现相应的方法,由于是一个中间人,我们要检查这个中间人是不是冒牌的,所以就要去验证URI
```java
public class NoteInfoProvider extends ContentProvider {

private static final int QUERY = 1;
private static final int INSERT = 2;
private static final int DELETE = 3;
private static final int UPDATE = 4;

// 参数code 代表如果uri不匹配的返回值
// 在当前应用程序的内部 声明一个路径的检查者
private static UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
private SQLiteDatabase db;

static {
// 建立一个匹配规则
// 1.如果发现一个路径 com.itheima.note.noteprovider/query 查询的操作
matcher.addURI("com.itheima.note.noteprovider", "query", QUERY);
matcher.addURI("com.itheima.note.noteprovider", "insert", INSERT);
matcher.addURI("com.itheima.note.noteprovider", "delete", DELETE);
matcher.addURI("com.itheima.note.noteprovider", "update", UPDATE);
}

@Override
public boolean onCreate() {
NoteSQLiteOpenHelper helper = new NoteSQLiteOpenHelper(getContext());
db = helper.getWritableDatabase();
return false;
}

/**
* 内容提供者暴露的查询的方法.
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// 1.重要的事情 ,检查 uri的路径.
int code = matcher.match(uri);
if (code == QUERY) {
// 查询处理
NoteSQLiteOpenHelper helper = new NoteSQLiteOpenHelper(getContext());
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from account", null);
return cursor;
} else {
throw new IllegalArgumentException("路径不能被识别,我不认识你...");
}
}

@Override
public String getType(Uri uri) {
int code = matcher.match(uri);
if (code == QUERY) {
//返回一条数据
return "vnd.android.cursor.item/note";
//返回多条数据
//return "vnd.android.cursor.dir/note"
}
return null;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
int code = matcher.match(uri);
if (code == INSERT) {
db.insert("account", null, values);
} else {
throw new IllegalArgumentException("路径不能被识别,我不认识你...");
}

return null;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int code = matcher.match(uri);
if (code == DELETE) {
db.delete("account", selection, selectionArgs);
} else {
throw new IllegalArgumentException("路径不能被识别,我不认识你...");
}

return 0;
}

@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int code = matcher.match(uri);
if (code == UPDATE) {
db.update("account", values, selection, selectionArgs);
} else {
throw new IllegalArgumentException("路径不能被识别,我不认识你...");
}
return 0;
}
}
```
2. 在清单文件中进行注册,并且指定其authorities
```xml
<provider
android:name="com.itheima.note.provider.NoteInfoProvider"
android:authorities="com.itheima.note.noteprovider" >
```
3. 在另外一个应用程序中使用内容提供者获取数据,使用ContentResolver去操作ContentProvider,ContentResolver用于管理ContentProvider实例,并且可实现找到指定的Contentprovider并获取到Contentprovider的数据。
```java
public void query(View view){
//得到内容提供者的解析器 中间人
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.itheima.note.noteprovider/queryaa");
Cursor cursor = resolver.query(uri, null, null, null, null);
while(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("name"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
float money = cursor.getFloat(cursor.getColumnIndex("money"));
System.out.println("id="+id+",name="+name+",money="+money);
}
cursor.close();
}
public void insert(View view){
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.itheima.note.noteprovider/insert");
ContentValues values = new ContentValues();
values.put("name", "买洗头膏");
values.put("money", 22.58f);
resolver.insert(uri, values);
}
public void update(View view){
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.itheima.note.noteprovider/update");
ContentValues values = new ContentValues();
values.put("name", "买洗头膏");
values.put("money", 42.58f);
resolver.update(uri, values, "name=?", new String[]{"买洗头膏"});
}
public void delete(View view){
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://com.itheima.note.noteprovider/delete");
resolver.delete(uri, "name=?", new String[]{"买洗头膏"});
}
```
---

- 邮箱 :[email protected]
- Good Luck!

0 comments on commit ab23823

Please sign in to comment.