安卓数据持久化:文件存储、SharedPreferences存储以及数据库存储
private void save(String inputText ) { FileOutputStream fos = null; BufferedWriter writer = null; try { fos = openFileOutput( "data", Context.MODE_PRIVATE); writer = new BufferedWriter( new OutputStreamWriter(fos)); writer.write( inputText); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if( writer != null) writer.close(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
//帮助我们返回一个目录 //context.getCacheDir ()的话就是保存到cache缓存文件夹下面 File file=new File(context.getFilesDir(), "userinfo.txt"); FileOutputStream fos= new FileOutputStream( file); //zhangsan 123 fos.write(( username+ "##"+ password).getBytes()); fos.close();
private void read( ) { FileInputStream fis= null; BufferedReader reader = null; StringBuilder sb=new StringBuilder(); try { fis= openFileInput( "data"); reader= new BufferedReader( new InputStreamWriter(fis)); String line=""; while((line=reader.readerLine())!=null){ sb.append(line) } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if( reader!= null) reader.close(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }主界面中
String inputText = load(); if (!TextUtils.isEmpty(inputText)) { edit.setText(inputText); edit.setSelection(inputText.length()); Toast.makeText(this, "Restoring succeeded", Toast.LENGTH_SHORT).show(); }
@Override public void onClick(View v) { // TODO Auto-generated method stub SharedPreferences.Editor editor=getSharedPreferences( "data", MODE_PRIVATE).edit(); editor.putString( "name", "hl174"); editor.putInt( "age", 18); editor.putBoolean( "吃饭没", false ); editor.commit(); } });最后看结果
restore_button .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SharedPreferences pref=getSharedPreferences( "data", MODE_PRIVATE); String name= pref.getString( "name", ""); int age= pref.getInt( "age", 0); boolean lunch= pref.getBoolean( "吃饭没", false ); Log. d("MainActivity" , "名字是:" +name ); Log. d("MainActivity" , "年龄是:" +age ); Log. d("MainActivity" , "吃饭没:" +lunch ); } }); }结果如下;
a,自建立一个MyDatabaseHelper实现抽象类SQLiteOpenHelper,里面有相应的建表数据,oncreate()被执行的时候表也会跟着建立起来
public class MyDatabaseHelper extends SQLiteOpenHelper { /* 补充一下建表的一些类型 integer ---整型 real-----浮点类型 text---文本类型 blob---二进制类型 */ public static final String CREATE_BOOK= "create table book(id integer primary key autoincrement," + "author text" + "price real" + "pages integer" + "name text)"; private Context mContext ; public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) { super( context, name, factory, version); // TODO Auto-generated constructor stub mContext= context; } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub //执行建表语句 db.execSQL(CREATE_BOOK); Toast.makeText(mContext , "数据库创建成功" , Toast.LENGTH_SHORT).show(); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } }
再看看主活动里面,非常简单主要就是 dbHelper. getWritableDatabase();
dbHelper= new MyDatabaseHelper( this, "BookStore.db", null, 1); Button createDatabase=(Button) findViewById(R.id.create_database ); createDatabase.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub dbHelper. getWritableDatabase(); } });
C:\Users\Administrator>adb shell root@generic_x86:/ # cd /data/data/com.example.databasetest/databases/ cd /data/data/com.example.databasetest/databases/ root@generic_x86:/data/data/com.example.databasetest/databases # ls ls BookStore.db BookStore.db-journal root@generic_x86:/data/data/com.example.databasetest/databases # sqlite3 BookSto re.db BookStore.db < SQLite version 3.7.11 2012-03-20 11:35:50 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .table .table android_metadata book sqlite> .schema .schema CREATE TABLE android_metadata (locale TEXT); CREATE TABLE book(id integer primary key autoincrement,author textprice realpage s integername text); sqlite> .exit .exit root@generic_x86:/data/data/com.example.databasetest/databases # exit exit
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, intnewVersion) { // TODO Auto-generated method stub db.execSQL( "drop table if exists book" ); db.execSQL( "drop table if exists category" ); onCreate( db); }
public long insert (String table, String nullColumnHack, ContentValues values)
Convenience method for inserting a row into the database.
Parameters
table | the table to insert the row into |
---|---|
nullColumnHack |
optional; may be null . SQL doesn‘t allow inserting a completely empty row without naming at least one column name. If your provided values is
empty, no column names are known and an empty row can‘t be inserted. If not set to null, thenullColumnHack parameter provides the name of nullable column name to explicitly insert a
NULL into in the case where your values is empty. |
values | this map contains the initial column values for the row. The keys should be the column names and the values the column values |
Returns
- the row ID of the newly inserted row, or -1 if an error occurred
Button addData =(Button) findViewById(R.id. add_data); addData.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SQLiteDatabase dbOperate= dbHelper.getWritableDatabase(); ContentValues values= new ContentValues(); //下面没有给表中的id赋值,因为在建表的时候,id是默认自动增长的 //添加第一条记录到Book values.put( "name", "安卓入门之路" ); values.put( "author", "hl174"); values.put( "pages", 800); values.put( "price", 50); dbOperate.insert( "book", null, values); values.clear(); //插入第二条记录到book values.put( "name", "安卓精通" ); values.put( "author", "hl174"); values.put( "pages", 700); values.put( "price", 45); dbOperate.insert( "book", null, values); } });
public int update (String table, ContentValues values, String whereClause, String[]whereArgs)
Convenience method for updating rows in the database.
Parameters
table | the table to update in |
---|---|
values | a map from column names to new column values. null is a valid value that will be translated to NULL. |
whereClause | the optional WHERE clause to apply when updating. Passing null will update all rows. |
whereArgs | You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. |
Retu rns
- the number of rows affected
//更新数据 Button updateData=(Button) findViewById(R.id. update_data); updateData.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SQLiteDatabase db= dbHelper.getWritableDatabase(); ContentValues values= new ContentValues(); values.put( "price", 10000); db.update( "book", values, "name=?", new String[]{"安卓入门之路" }); } });
public int delete (String table, String whereClause, String[] whereArgs)
Convenience method for deleting rows in the database.
Parameters
table | the table to delete from |
---|---|
whereClause | the optional WHERE clause to apply when deleting. Passing null will delete all rows. |
whereArgs | You may include ?s in the where clause, which will be replaced by the values from whereArgs. The values will be bound as Strings. |
Returns
- the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.
//删除数据 Button deleteData=(Button) findViewById(R.id. delete_data); deleteData.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub SQLiteDatabase db= dbHelper.getWritableDatabase(); //删除页数大于500的记录 db.delete( "book", "pages>?", new String[]{"500" }); } });
查询语句
public Cursor query (String table, String[] columns, String selection, String[]selectionArgs, String groupBy, String having, String orderBy)
Query the given table, returning a Cursor
over
the result set.
Parameters
table | The table name to compile the query against. |
---|---|
columns | A list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn‘t going to be used. |
selection | A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table. |
selectionArgs | You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings. |
groupBy | A filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped. |
having | A filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used. |
orderBy | How to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered. |
Returns
See Also
public void onClick(View v ) { // TODO Auto-generated method stub SQLiteDatabase db= dbHelper.getWritableDatabase(); //查询book表中的所有数据 Cursor cursor= db.query( "book", null, null, null, 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" , "书名是:" +name ); Log. d("MainActivity" , "书的作者是:" +author ); Log. d("MainActivity" ,"书的页数是:" +pages ); Log. d("MainActivity" , "书的价钱是:" +price ); } while( cursor.moveToNext()); } cursor.close(); } });
public abstract int getColumnIndex (String columnName)
Returns the zero-based index for the given column name, or -1 if the column doesn‘t exist. If you expect the column to exist use getColumnIndexOrThrow(String)
instead,
which will make the error more clear.
Parameters
columnName | the name of the target column. |
---|
Returns
- the zero-based column index for the given column name, or -1 if the column name does not exist.
See Also
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。