android数据存储
2016-01-09 09:37
363 查看
《 第一行代码---android 》读书笔记
android提供了三种方式用于简单的实现数据持久化功能,即文件存储,SharedPreference存储以及数据库存储。
对字符串判空使用了TextUtils.isEmpty()方法,他可以一次性进行两种值得判空。
Android主要提供了三种方法用于得到SharedPreferences对象:
1.Context类中的getSharedPreferences()方法 此方法接受两个参数,第一个参数用于指定文件的名称,如果制定的文件不存在,测创建一个。第二个参数用于指定操作模式。
2.Activity类中的GetPreferences()方法 只接受一个操作模式的参数,使用这个方法是会自动将当前活动的类名作为SharedPreferences的文件名。
3.PreferenceManager类中的getDefaultSharedPreferences()方法 这是一个静态的方法,他接受一个Context的参数,并使用当前应用程序的包名作为前缀来命名SharedPreferences文件。
SQLiteOpenHelper中有两个非常重要的实例方法,getReadableDatabase()和getWritableDatabase().这两个方法都可以攒关键或打开一个现有的数据库(如果数据库已存在直接打开,如果数据库不存在创建一个新的数据库),并返回一个可对数据库操作的对象。二者不同的是当数据库已满时,前者返回的对象只能已读的方式大考数据库,而后者会出现异常。
SQLiteOpenHelper有两个构造方法可供重写,一般使用参数比较少的那个构造方法。第一个参数是Context,第二个是数据库名,第三个参数允许我们在查询数据时返回的一个自定义的Cursor,一般都是传入null。第四个为当前数据库的版本号,可用于对数据库进行升级。
第三个参数对应的是SQL语句的where部分,表示去更新所有name等于?的行,而?是一个占位符,可以通过第四个参数提供的一个字符串数组为第三个参数中的每个占位符指定的相应内容。
2.columns:查询的列名
3.selection:指定where的约束条件
4.selectionArgs:为where中的占位符提供具体的值
5.groupBy:指定需要group bu的列
6.having:对group by后的结果进一步约束
7.orderBy:指定查询结果的排序方式
使用事务:事务的特性可以保证让某一系列的操作要么全部完成,要么一个都不会完成。
新增了一条见表语句,在onUpgrade()方法中添加了一个switch判断。
当用户当前数据库版本的版本号为1,就只会建第二张表。
当用户是直接安装第二版程序时,就会将两张表一起创建。
而当用户是使用第二版的程序覆盖第一版时,就会进入到升级程序,此时第一张表已经存在,因此只建立第二张表。
如果要在第一张表中添加一个category_id的字段。
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
相关文章推荐
- Android控件之RadioGroup和RadioButton
- Ubuntu 14.04 64位编译Android4.2.2源代码
- Android中的MVP
- Android使用criteria选择合适的地理位置服务实现方法
- Android实现自定义带文字和图片的Button
- Android Calendar的应用
- Android中特殊图形的生成样例
- Android控件之CheckBox
- Android编程中@id和@+id的区别分析
- Android控件之ToggleButton
- android基本控件ToggleButton&Switch使用指南
- 如何在Android Studio中设置*md文件打开方式
- Android开发Tips(1)
- Android之AIDL使用详解
- AlertDialog中的EditText不能输入
- Android media媒体库分析之:MediaProvider
- Android Studio 初体验(So库的添加)
- android程序出错了怎么更友好的处理
- android的locationManager—执行onLocationChanged方法.
- Android第一阶段day1