数据存储技术

一、文件存储

1,使用java I/O技术完成存储

1)、保存string到默认路径data文件中

	private void saveinput(String string) {
		// TODO Auto-generated method stub
		FileOutputStream out = null;
		BufferedWriter writer = null;
		try {
			out = openFileOutput("data", Context.MODE_PRIVATE);
			writer = new BufferedWriter(new OutputStreamWriter(out));
			writer.write(string);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

2)、从data文件读取数据,返回string

	private String load() {
		FileInputStream in = null;
		BufferedReader reader = null;
		StringBuilder content = new StringBuilder();
		try {
			in = openFileInput("data");
			reader = new BufferedReader(new InputStreamReader(in));
			String line = "";
			while ((line = reader.readLine()) != null) {
				content.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return content.toString();
	}

3)、点击EditText区域以外关闭输入法的方法

	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			View v = getCurrentFocus();
			if (isShouldHideInput(v, ev)) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if (imm != null) {
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				}
			}
			return super.dispatchTouchEvent(ev);
		}
		// 必不可少,否则所有的组件都不会有TouchEvent了
		if (getWindow().superDispatchTouchEvent(ev)) {
			return true;
		}
		return onTouchEvent(ev);
	}

	public boolean isShouldHideInput(View v, MotionEvent event) {
		if (v != null && (v instanceof EditText)) {
			int[] leftTop = { 0, 0 };
			// 获取输入框当前的location位置
			v.getLocationInWindow(leftTop);
			int left = leftTop[0];
			int top = leftTop[1];
			int bottom = top + v.getHeight();
			int right = left + v.getWidth();
			if (event.getX() > left && event.getX() < right
					&& event.getY() > top && event.getY() < bottom) {
				// 点击的是输入框区域,保留点击EditText的事件
				return false;
			} else {
				return true;
			}
		}
		return false;
	}

二、SharedPreferences存储

1、获取SharedPreferences对象,有3种方式

1)、Context 类中的getSharedPreferences()方法

2)、Activity 类中的getPreferences()方法

3)、PreferenceManager 类中的getDefaultSharedPreferences()方法

2、调用SharedPreferences 对象的edit()方法来获取一个SharedPreferences.Editor 对象,再向SharedPreferences.Editor 对象中添加数据,最后调用commit()方法将添加的数

据提交,保存位置默认。代码如下

		SharedPreferences.Editor editor = getSharedPreferences("data",
				MODE_PRIVATE).edit();
		editor.putString("name", "Tom");
		editor.putInt("age", 28);
		editor.putBoolean("married", false);
		editor.commit();

3、读取内容代码如下

			StringBuffer stringBuffer = new StringBuffer();
			SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
			stringBuffer.append("name is" + pref.getString("name", "") + ","
					+ "age is" + pref.getInt("age", 0) + "," + "married is "
					+ pref.getBoolean("married", false));

三、数据库存储

1、SQL基础

1)、数据类型:integer、real、text、blob

2)、建表语句

	creat table Book(
		id integer primary key autoincrement,
		author text,
		price real,
		page integer,
		name text)

2、创建数据库

1)、继承SQLiteOpenHelper类封装对数据库的创建升级操作,需要重写4参数构造器,实现抽象方法onCreate()和onUpGrade(),注意inCreat()方法在只在建数据库时会自动调

public class MyDataBaseHelper extends SQLiteOpenHelper { 

	public static final String CREAT_TABLE = "creat table Book("
			+ "id integer primary key autoincrement," + "author text,"
			+ "price real," + "page integer," + "name text)";

	public MyDataBaseHelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// 执行建表语句
		db.execSQL(CREAT_TABLE);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
		// TODO Auto-generated method stub
	}
}

2)、在活动中构建出SQLiteOpenHelper 的实例之后,再调用它的getReadableDatabase()或getWritableDatabase()方法就能够创建数据库

	MyDataBaseHelper dbHelper = new MyDataBaseHelper(
		getApplicationContext(), "BookStore.db", null, 1);
	dbHelper.getReadableDatabase();

3)、查看数据库文件

	//进入设备控制台
	adb shell
	//进入数据库文件所在文件夹
	cd data/data/com.study.hello/databases
	//查看此文件夹下的问价
	ls
	//打开数据库文件
	sqlite3 BookStore.db
	//查看数据库表
	.table
	//查看建表语句
	.schema<pre class="html" name="code">	//查看Book表内容
	select * from Book;
 

3、升级数据库

1)、在现有数据库中加入新表,需要添加建表语句,并在inCreate()方法中调用之

	public static final String CREATE_CATEGORY = "create table Category ("
			+ "id integer primary key autoincrement, category_name text, "
			+ "category_code integer)";
	db.execSQL(CREATE_CATEGORY);

2)、在onUPgrade()方法中添加如下语句,同时,主活动建数据库语句版本号参数改大。注意此方式会删掉旧表数据

	db.execSQL("drop table if exists Book");
	db.execSQL("drop table if exists Category");
	onCreate(db);
	dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);

4、添加数据

1)、主活动中获取数据库实例,定义数据容器组装数据,使用inser()方法添加至数据库,清空容器再重新组装。注意组装要与建表字段顺序一致

	SQLiteDatabase db = dbHelper.getReadableDatabase();
	ContentValues values = new ContentValues();
	// 开始组装第一条数据		values.put("author", "Dan Brown");
	values.put("price", 16.96);
	values.put("pages", 454);
	values.put("name", "The Da Vinci Code");
	db.insert("Book", null, values); // 插入第一条数据
	values.clear();
	// 开始组装第二条数据
	values.put("author", "Dan Brown");
	values.put("price", 19.95);
	values.put("pages", 510);
	values.put("name", "The Lost Symbol");
	db.insert("Book", null, values);
	values.clear();

5、修改数据

1)、upDate()方法:接收4个参数,第一个为表名,第2个为数据容器,第三个为where,第四个提供字符数组匹配占位符,默认则修改所有。ContentValues使用与上例类似

	values.put("price", 10.99);
	db.update("Book", values, "name = ?", new String[] { "The Da Vinci Code"});

6、删除数据

1)、delete()方法:接收3个参数,没有数据参数

	db.delete("Book", "name = ?", new String[] { "The Da Vinci Code"});

7、查询数据

1)、query()方法:返回一个Cursor对象,最简单的一个重载方法接收7个参数,第一个为表名,第二个为列名,第三、四制定约束条件,第五指定要group by的列,第六对第

五的结果约束,第七指定查询结果的排序方式。注意Cursor使用后要关闭。

	Cursor cursor = db.query("Book", null, "price = ?",
			new String[] { "16.96" }, null, null, null);
	if (cursor.moveToFirst()) {
		do {
			// 遍历Cursor对象,取出数据并打印
			String name = cursor.getString(cursor.getColumnIndex("name"));
			String author = cursor.getString(cursor
					.getColumnIndex("author"));
			int pages = cursor.getInt(cursor.getColumnIndex("pages"));
			double price = cursor.getDouble(cursor.getColumnIndex("price"));
			Log.d("MainActivity", "book name is " + name);
			Log.d("MainActivity", "book author is " + author);
			Log.d("MainActivity", "book pages is " + pages);
			Log.d("MainActivity", "book price is " + price);
		} while (cursor.moveToNext());
	}
	else {
		Log.d("MainActivity", "Not Found");
		
	}
	cursor.close();

8、直接使用SQL执行数据操作

9、使用事物

1)、SQLite支持事物,保证一系列操作可以合并,要么都完成,要么一个都不做。

	SQLiteDatabase db = dbHelper.getReadableDatabase();
	db.beginTransaction(); // 开启事务
	try {
		db.delete("Book", null, null);
//		if (true) {
//			在这里模拟一次失败,手动抛出一个异常,让事务失败
//			throw new NullPointerException();
//		}
		ContentValues values = new ContentValues();
		values.put("name", "Game of Thrones");
		values.put("author", "George Martin");
		values.put("pages", 720);
		values.put("price", 20.85);
		db.insert("Book", null, values);
		db.setTransactionSuccessful(); // 事务已经执行成功
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		db.endTransaction(); // 结束事务
	}

10、升级数据库优化

1)、3中提供了一种数据库升级方案,但是在升级时删除旧表会导致原有数据丢失,下例在onUpGrade()方法中使用switch语句,case为原始版本号,其中添加升级要执行的语

句,表示从旧版本升级到新版本需要执行的变更;同时在onCreate()方法中执行历次更新执行的语句,保证首次安装也可以创建成最新版本

	public void onCreate(SQLiteDatabase db) {
		// 建表
		db.execSQL(CREAT_TABLE);
		db.execSQL(CREATE_CATEGORY);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		switch (oldVersion) {
		case 1:
			db.execSQL(CREATE_CATEGORY);
		default:
		}

	}

2)、现要对上例2张表建立联系,在Book表中添加category_id 字段,则在原Book建表语句中添加此字段,然后添加case项,添加相应SQL操作


	public static final String CREAT_TABLE = "create table Book ("
			+ "id integer primary key autoincrement, author text, "
			+ "price real, pages integer, name text" + "category_id integer)";
<pre class="html" name="code">	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		switch (oldVersion) {
		case 1:
			db.execSQL(CREATE_CATEGORY);
		case 2:
			db.execSQL("alter table Book add column category_id integer");
		default:
		}

	}

 



















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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值