标签:
Android系统中主要提供了三种方式用于简单的实现数据持久化功能: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 ); } }); }结果如下;
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= 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); }
Convenience method for inserting a row into the database.
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 |
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); } });
Convenience method for updating rows in the database.
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. |
//更新数据 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[]{"安卓入门之路" }); } });
Convenience method for deleting rows in the database.
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. |
//删除数据 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" }); } });
Query the given table, returning a Cursor
over
the result set.
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. |
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(); } });
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.
columnName | the name of the target column. |
---|
安卓数据持久化:文件存储、SharedPreferences存储以及数据库存储
标签:
原文地址:http://blog.csdn.net/hll174/article/details/45750215