android数据存储

                                 《 第一行代码---android 》读书笔记

android提供了三种方式用于简单的实现数据持久化功能,即文件存储,SharedPreference存储以及数据库存储。

文件存储

即不对存储的内容进行任何的格式化处理,所有数据都是原封不动地保存在文件当中,因而比较适合用于存储一些简单的文本数据和二进制数据。

将数据存储到文件中

类似于Java,Context类提供了openFileOutput()方法。第一个参数是文件名,第二个参数文件的操作模式主要有MODE_PRIVATE和MODE_APPEND,前者为默认的操作模式,表示当前所写入的内容将会覆盖原文件的内容,而后者,表示在已存在的内容后追加。


public class MainActivity extends Activity {
	
	private EditText edit;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edit=(EditText) findViewById(R.id.ed);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		String inputText=edit.getText().toString();
		save(inputText);
	}

	private void save(String inputText) {
		// 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(inputText);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(writer!=null){
				try {
					writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}

}

从文件中读取数据

public class MainActivity extends Activity {

	private EditText edit;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edit = (EditText) findViewById(R.id.edit);
		String inputText = load();
		if (!TextUtils.isEmpty(inputText)) {
			edit.setText(inputText);
			edit.setSelection(inputText.length());
			Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		String inputText = edit.getText().toString();
		save(inputText);
	}

	public void save(String inputText) {
		FileOutputStream out = null;
		BufferedWriter writer = null;
		try {
			out = openFileOutput("data", Context.MODE_PRIVATE);
			writer = new BufferedWriter(new OutputStreamWriter(out));
			writer.write(inputText);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (writer != null) {
					writer.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public 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();
	}

}

对字符串判空使用了TextUtils.isEmpty()方法,他可以一次性进行两种值得判空。

SharedPreferences存储

其使用键值对的形式进行存储

Android主要提供了三种方法用于得到SharedPreferences对象:

     1.Context类中的getSharedPreferences()方法  此方法接受两个参数,第一个参数用于指定文件的名称,如果制定的文件不存在,测创建一个。第二个参数用于指定操作模式。

     2.Activity类中的GetPreferences()方法 只接受一个操作模式的参数,使用这个方法是会自动将当前活动的类名作为SharedPreferences的文件名。

     3.PreferenceManager类中的getDefaultSharedPreferences()方法  这是一个静态的方法,他接受一个Context的参数,并使用当前应用程序的包名作为前缀来命名SharedPreferences文件。

将数据存储到SharedPreferences中并取出

public class MainActivity extends Activity {
	
	private Button saveData;
	
	private Button restoreData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		saveData = (Button) findViewById(R.id.save_data);
		restoreData = (Button) findViewById(R.id.restore_data);
		saveData.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
				editor.putString("name", "Tom");
				editor.putInt("age", 28);
				editor.putBoolean("married", false);
				editor.commit();
			}
		});
		restoreData.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
				String name = pref.getString("name", "");
				int age = pref.getInt("age", 0);
				boolean married = pref.getBoolean("married", false);
				Log.d("MainActivity", "name is " + name);
				Log.d("MainActivity", "age is " + age);
				Log.d("MainActivity", "married is " + married);
			}
		});
	}

}

SQLite数据库存储

创建数据库

android提供了SQLiteOpenHelper帮助类,这个类 是一个抽象类,其中有两个抽象方法,分别是onCreate和onUpgrade(),前者用于实现数据库,后者用于升级数据库。

SQLiteOpenHelper中有两个非常重要的实例方法,getReadableDatabase()和getWritableDatabase().这两个方法都可以攒关键或打开一个现有的数据库(如果数据库已存在直接打开,如果数据库不存在创建一个新的数据库),并返回一个可对数据库操作的对象。二者不同的是当数据库已满时,前者返回的对象只能已读的方式大考数据库,而后者会出现异常。

SQLiteOpenHelper有两个构造方法可供重写,一般使用参数比较少的那个构造方法。第一个参数是Context,第二个是数据库名,第三个参数允许我们在查询数据时返回的一个自定义的Cursor,一般都是传入null。第四个为当前数据库的版本号,可用于对数据库进行升级。

public class MyDatabaseHelper extends SQLiteOpenHelper {

	public static final String CREATE_BOOK = "create table Book ("
			+ "id integer primary key autoincrement, " 
			+ "author text, "
			+ "price real, " 
			+ "pages integer, " 
			+ "name text)";
	
	public static final String CREATE_CATEGORY = "create table Category ("
			+ "id integer primary key autoincrement, "
			+ "category_name text, "
			+ "category_code integer)";

	private Context mContext;

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

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_BOOK);
		db.execSQL(CREATE_CATEGORY);
		Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
	}

添加数据

SQLiteDatabase db = dbHelper.getWritableDatabase();
				ContentValues values = new ContentValues();
				values.put("name", "The Da Vinci Code");
				values.put("author", "Dan Brown");
				values.put("pages", 454);
				values.put("price", 16.96);
				db.insert("Book", null, values);
				values.clear();
				values.put("name", "The Lost Symbol");
				values.put("author", "Dan Brown");
				values.put("pages", 510);
				values.put("price", 19.95);
				db.insert("Book", null, values);


更新数据

SQLiteDatabase db = dbHelper.getWritableDatabase();
				ContentValues values = new ContentValues();
				values.put("price", 10.99);
				db.update("Book", values, "name = ?",
						new String[] { "The Da Vinci Code" });//经名字是the da vinci code的这本书的介个改为10.99

第三个参数对应的是SQL语句的where部分,表示去更新所有name等于?的行,而?是一个占位符,可以通过第四个参数提供的一个字符串数组为第三个参数中的每个占位符指定的相应内容。

删除数据

SQLiteDatabase db = dbHelper.getWritableDatabase();
				db.delete("Book", "pages > ?", new String[] { "500" });

查询数据----最少的方法需要传入七个参数

1.table:表名

2.columns:查询的列名

3.selection:指定where的约束条件

4.selectionArgs:为where中的占位符提供具体的值

5.groupBy:指定需要group bu的列

6.having:对group by后的结果进一步约束

7.orderBy:指定查询结果的排序方式

SQLiteDatabase db = dbHelper.getWritableDatabase();
				Cursor cursor = db.query("Book", null, null, null, null, null,
						null);
				if (cursor.moveToFirst()) {
					do {
						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());

使用事务:事务的特性可以保证让某一系列的操作要么全部完成,要么一个都不会完成。

SQLiteDatabase db = dbHelper.getWritableDatabase();
				db.beginTransaction();//开启事物
				try{
				ContentValues values = new ContentValues();
				values.put("name", "The Da Vinci Code");
				values.put("author", "Dan Brown");
				values.put("pages", 454);
				values.put("price", 16.96);
				db.insert("Book", null, values);
				values.clear();
				values.put("name", "The Lost Symbol");
				values.put("author", "Dan Brown");
				values.put("pages", 510);
				values.put("price", 19.95);
				db.insert("Book", null, values);
				db.setTransactionSuccessful();//事务已经执行成功
				}catch(Exception e){
					
				}finally{
					db.endTransaction();//结束事物
				}

升级数据库的最佳写法

public class MyDatabaseHelper extends SQLiteOpenHelper {

	public static final String CREATE_BOOK = "create table Book ("
			+ "id integer primary key autoincrement, " 
			+ "author text, "
			+ "price real, " 
			+ "pages integer, " 
			+ "name text)";
	
	public static final String CREATE_CATEGORY = "create table Category ("
			+ "id integer primary key autoincrement, "
			+ "category_name text, "
			+ "category_code integer)";

	private Context mContext;

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

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_BOOK);
		db.execSQL(CREATE_CATEGORY);
		Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		switch (oldVersion) {
		case 1:
			db.execSQL(CREATE_CATEGORY);
			

		default:
			
		}
		
	}

}


新增了一条见表语句,在onUpgrade()方法中添加了一个switch判断。

当用户当前数据库版本的版本号为1,就只会建第二张表。

当用户是直接安装第二版程序时,就会将两张表一起创建。

而当用户是使用第二版的程序覆盖第一版时,就会进入到升级程序,此时第一张表已经存在,因此只建立第二张表。


如果要在第一张表中添加一个category_id的字段。

public class MyDatabaseHelper extends SQLiteOpenHelper {

	public static final String CREATE_BOOK = "create table Book ("
			+ "id integer primary key autoincrement, " 
			+ "author text, "
			+ "price real, " 
			+ "pages integer, " 
			+ "name text)"
			+"category_id integer)";
	
	public static final String CREATE_CATEGORY = "create table Category ("
			+ "id integer primary key autoincrement, "
			+ "category_name text, "
			+ "category_code integer)";

	private Context mContext;

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

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(CREATE_BOOK);
		db.execSQL(CREATE_CATEGORY);
		Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		switch (oldVersion) {
		case 1:
			db.execSQL(CREATE_CATEGORY);
		case 2:
			db.execSQL("alter table Book add column category_id integer");

		default:
			
		}
		
	}

}
注意的是:这里的switch语句不能使用break






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值