Android数据存储的三种方式-SharedPrefrences,File,SQLite
1,使用SharedPrefrences
用于簡單少量的數據,數據的格式簡單:都是普通的字符串,標量類型的值等,比如各種配置信息等等
SharedPrefrences與Editor簡介:
創建SharedPreferences實例,通過Context.getSharedPreferences(String name,int mode);方法來獲取SharedPreferences的實例
mode的值:
*Context.MODE_PRIVATE;該SharedPreferences數據只能被本應用程序調讀,寫
* Context.MODE_WORLD_READABLE;該SharedPreferences數據能被其他程序讀,但是不能寫
* Context.MODE_WORLD_WRITEABLE;該SharedPreferences數據能被其他程序讀,寫
?SharedPreferences保存的數據主要是類似于配置信息格式的數據,因此他保存的數據主要是簡單類型的key-value對
* SharedPreferences接口主要負責讀取應用程序的Preferences數據,提供如下常用的方法訪問key-value對
* boolean contains(String key);判斷是否包含key的數據
* abstract Map<String,?> getAll();獲取全部鍵值對
* boolean getXxx(String key,xxx,defValue);獲取指定的key對應的value值,如果key不存在,返回默認defvalue,xxx可以是Boolean,float,int,long,String等各種基本類型的值
SharedPreferences接口本身并沒有提供寫入數據的能力,而是通過 SharedPreferences的內部接口Editor寫入數據,SharedPreferences調用edit()方法即可獲得它所對應的Editor對象
Editor提供了如下方法:
* SharedPreferences.Editor clear();清空所有數據
* SharedPreferences.Editor putXxx(String key,xxx value);存入指定key對應的數據,xxx可以是Boolean,float,int,long,String等各種基本類型的值
* SharedPreferences.Editor remove(String key);刪除指定key的數據
* Boolean commit();當Editor編輯完成之后,調用該方法提交修改
例子:一個按鈕寫數據,一個按鈕讀數據
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/root"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><Buttonandroid:id="@+id/button1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Write_SharedPreference" /><Buttonandroid:id="@+id/button2"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Read_SharedPreference" /></LinearLayout>
MainActivity.java
package com.hust.sharedpreferences;import java.text.SimpleDateFormat; import java.util.Date; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; /** 創建SharedPreferences實例,通過Context.getSharedPreferences(String name,int mode);方法來獲取SharedPreferences的實例* mode的值:* Context.MODE_PRIVATE;該SharedPreferences數據只能被本應用程序調讀,寫* Context.MODE_WORLD_READABLE;該SharedPreferences數據能被其他程序讀,但是不能寫* Context.MODE_WORLD_WRITEABLE;該SharedPreferences數據能被其他程序讀,寫* * * SharedPreferences保存的數據主要是類似于配置信息格式的數據,因此他保存的數據主要是簡單類型的key-value對* * SharedPreferences接口主要負責讀取應用程序的Preferences數據,提供如下常用的方法訪問key-value對* boolean contains(String key);判斷是否包含key的數據* abstract Map<String,?> getAll();獲取全部鍵值對* boolean getXxx(String key,xxx,defValue);獲取指定的key對應的value值,如果key不存在,返回默認defvalue,xxx可以是Boolean,float,int,long,String等各種基本類型的值* * SharedPreferences接口本身并沒有提供寫入數據的能力,而是通過 SharedPreferences的內部接口Editor寫入數據,SharedPreferences調用edit()方法即可互毆它所對應的Editor對象* Editor提供了如下方法:* SharedPreferences.Editor clear();清空所有數據* SharedPreferences.Editor putXxx(String key,xxx value);存入指定key對應的數據,xxx可以是Boolean,float,int,long,String等各種基本類型的值* SharedPreferences.Editor remove(String key);刪除指定key的數據* Boolean commit();當Editor編輯完成之后,調用該方法提交修改* * */public class MainActivity extends Activity {//SharedPreferences preferences;SharedPreferences.Editor editor;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//實例化SharedPreferences對象,讀數據preferences=getSharedPreferences("test",Context.MODE_WORLD_READABLE);//實例化Editor對象,寫數據editor=preferences.edit();Button read=(Button) findViewById(R.id.button2);Button write=(Button) findViewById(R.id.button1);read.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString time=preferences.getString("time", null); int rnd=preferences.getInt("rnd", 0);String result=time==null?"您暫時還未寫入數據":"寫入時間:"+time+"\n上次生成的數據數是:"+rnd;Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();}});write.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubSimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日"+"hh:mm:ss");editor.putString("time", sdf.format(new Date()));editor.putInt("rnd", (int)(Math.random()*1000));editor.commit();}});}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);} } SharedPrefrences文件的存儲位置:
test.xml
二,使用File存儲
Context 提供了兩種方法來打開本應用程序的數據文件夾里的文件IO流
1,FileInputStream openFileInput(String filename);打開應用程序的數據文件夾下(文件在DDMS>File Explor>data>data>包名>files>filename)的filename文件對應的輸入流
2, FileOutputStream openFileOutput(String name,int mode);打開應用程序的數據文件夾下name文件對應的輸出流
第二個參數:
* MODE_PRIVATE;該文件只能被當前程序讀寫,且每次寫入前,以前寫的內容會清空,不追加
* MODE_APPEND: 追加的方式打開該文件,應用程序可以向該文件中追加內容
* MODE_WORLD_READABLE:該文件的內容可以被其他程序讀取
* MODE_WORLD_WRITEABLE:該文件的內容可以被其他程序讀,寫
package com.hust.filetest;import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream;import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;/** Context 提供了兩種方法來打開本應用程序的數據文件夾里的文件IO流* 1,FileInputStream openFileInput(String filename);打開應用程序的數據文件夾下(文件在DDMS>File Explor>data>data>包名>files>filename)的filename文件對應的輸入流* 2, FileOutputStream openFileOutput(String name,int mode);打開應用程序的數據文件夾下name文件對應的輸出流* * 第二個參數:* MODE_PRIVATE;該文件只能被當前程序讀寫,且每次寫入前,以前寫的內容會清空,不追加* MODE_APPEND: 追加的方式打開該文件,應用程序可以向該文件中追加內容* MODE_WORLD_READABLE:該文件的內容可以被其他程序讀取* MODE_WORLD_WRITEABLE:該文件的內容可以被其他程序讀,寫* * */ public class MainActivity extends Activity {final String FILE_NAME="filetest";//文件名@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button write=(Button) findViewById(R.id.button1);Button read=(Button) findViewById(R.id.button2);final EditText edit1=(EditText) findViewById(R.id.editText1);final EditText edit2=(EditText) findViewById(R.id.editText2);write.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stub//寫入數據writedata(edit1.getText().toString());edit1.setText("");Toast.makeText(MainActivity.this, "寫入成功!", Toast.LENGTH_LONG).show();}});read.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString ss;try {//讀數據ss = readdata();edit2.setText(ss);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }});} //讀數據protected String readdata() throws IOException {// TODO Auto-generated method stubtry {//打開文件輸入流FileInputStream fis=openFileInput(FILE_NAME);//緩存byte[] buffer=new byte[1024];int hasread=0;StringBuilder sb=new StringBuilder("");//循環讀入緩存大小的數據,并存放在緩存數組中while((hasread=fis.read(buffer))>0){sb.append(new String(buffer,0,hasread));}fis.close();return sb.toString();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return null;} //寫數據protected void writedata(String content) {// TODO Auto-generated method stubtry {//打開文件輸出流,以追加的方式FileOutputStream fos=openFileOutput(FILE_NAME,MODE_APPEND);//把輸出流包裝成PrintStreamPrintStream ps=new PrintStream(fos);//輸出文件內容ps.print(content);ps.close();} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.int id = item.getItemId();if (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);} } 三,使用SQLite數據庫
SQLite數據是Android集成的一個輕量級的數據庫,不想Oracle,MySQL那樣的數據庫,SQLite只是一個文件,創建或打開一個SQLite數據庫時,只是打開一個文件準備讀寫
SQLiteDatabase類的靜態方法來打開一個對應的數據庫:
public static SQLiteDatabase openDatabase(String path, CursorFactory factory, int flags),打開path文件所代表的SQLite數據庫
public static SQLiteDatabase openOrCreateDatabase(File file, CursorFactory factory)
打開或創建file文件代表的數據庫
public static SQLiteDatabase openOrCreateDatabase(String path, CursorFactory factory);打開或創建path文件代表的數據庫
調用SQLiteDatabase類的如下方法操作數據庫:
1,執行SQL語句
execSQL(String sql)
execSQL(String sql, Object[] bindArgs)。執行帶占位符的SQL語句
2,執行帶占位符的SQL查詢
Cursor rawQuery(String sql, String[] selectionArgs)
3,特定的方法操作SQLite數據庫(就是把SQl語句整理成參數)
update(String table, ContentValues values, String whereClause, String[] whereArgs)
insert(String table, String nullColumnHack, ContentValues values)
delete(String table, String whereClause, String[] whereArgs)
Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy)
Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy, String limit)
Cursor對象:
move(int offset);將指針向上或向下指到指定的行數
boolean moveToFirst();指針移動到第一行
boolean moveToLast();
boolean moveToNext();
boolean moveToPosition(int position);
boolean moveToPrevious();
String?getColumnName(int columnIndex);由列的索引獲得列名
String[] getColumnNames();獲得所有列名
String getString(int columnIndex);索引獲得值
int getColumnIndex(String columnName);由列名獲得索引
使用SQL語句操作Sqlite數據庫
package com.hust.sqlitedb;import android.app.Activity; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter;public class MainActivity extends Activity {SQLiteDatabase db;Button btn;ListView listview;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//創建或打開數據庫(需要使用絕對路徑)db=SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/mydb.db3", null); Log.v("Dir", getFilesDir().toString());//getFilesDir().toString()的值是/data/data/com.hust.sqlitedb/fileslistview =(ListView) findViewById(R.id.listView1);btn=(Button) findViewById(R.id.button1);btn.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString title=((EditText) findViewById(R.id.editText1)).getText().toString();String content=((EditText) findViewById(R.id.editText2)).getText().toString();try{inertData(db,title,content);//插入數據表Cursor cursor=db.rawQuery("select * from info", null);//查詢數據表 ShowInList(cursor);//在ListView中顯示cursor表}catch(SQLiteException se){//數據庫對象執行SQL語句,創建表db.execSQL("create table info(_id integer primary key autoincrement," +"news_title varchar(20)," +"news_content varchar(255))");inertData(db,title,content);Cursor cursor=db.rawQuery("select * from info", null); ShowInList(cursor);} }});}protected void ShowInList(Cursor cursor) {// TODO Auto-generated method stub//SimpleCursorAdapter的用法:1,Context,2,每一行的布局文件,3,數據源cursor。4.字符串數組表示表的列名,像SimpleAdapter表示Map中的key值,5,顯示的組件IdSimpleCursorAdapter ad=new SimpleCursorAdapter(this, R.layout.line, cursor, new String[]{"news_title","news_content"}, new int[]{R.id.textView1,R.id.textView2});//設置Adapterlistview.setAdapter(ad);}protected void inertData(SQLiteDatabase db2, String title, String content) {// TODO Auto-generated method stub//獨具庫對象執行SQL語句,帶占位符的語句db2.execSQL("insert into info values(null,?,?)",new String[]{title,content} );}//對出程序是關掉數據庫@Overrideprotected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();if(db!=null&&db.isOpen()){db.close();}} 使用SQLiteDatabase進行數據庫操作的步驟:
1,獲取SQLiteDatabase對象,代表與數據庫連接
2,調用SQLiteDatabase的方法執行SQL語句
3,操作SQL語句的執行結果,比如用SimpleCusorAdapter封裝Cursor
4,關閉SQLiteDatabase,回收資源
SQLiteOpenHelper類:管理數據庫的工具類
實際中很少用SQLiteDatabase的靜態方法打開數據庫,一般是繼承SQLiteOpenHelper開發子類,并通過該子類的getReadableDatabase()和getWritableDatabase()方法打開數據庫
public SQLiteDatabase getReadableDatabase();以讀寫的方式打開數據庫對應的SQLiteDatabase 對象,就是獲取數據庫對象
public SQLiteDatabase getWritableDatabase();以寫的方式打開數據庫對應的SQLiteDatabase 對象,就是獲取數據庫對象
void onCreate(SQLiteDatabase db);當第一次創建數據庫時回調該方法
void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);當數據庫版本有更新是回調該方法
DBHelper.java
package com.hust.sqliteopenhelper;import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper;public class DBHelper extends SQLiteOpenHelper {//繼承SQLiteOpenHelper//建表的SQl語句String SQL="create table dict(id integer primary key autoincrement," +"news_word varchar(20)," +"news_detail varchar(100))";public DBHelper(Context context, String name, CursorFactory factory,int version) {//name是數據庫文件名super(context, name, factory, version);// TODO Auto-generated constructor stub} //如果數據庫不存在時就自動生成一個數據庫,并調用onCreate方法,可以添加一些對數據庫的初始操作,比如建表。添加初始記錄數據@Overridepublic void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stubdb.execSQL(SQL);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {// TODO Auto-generated method stubSystem.out.println("--onUpdate Called--"+oldVersion+"-->"+newVersion);}} MainActivity.java
package com.hust.sqliteopenhelper;import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast;public class MainActivity extends Activity {DBHelper dbhelper;Button write;Button search;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);write=(Button) findViewById(R.id.button1);search=(Button) findViewById(R.id.button2);dbhelper=new DBHelper(this, "Dict.db3", null, 1);//第二個參數是數據庫名 write.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubEditText editword=(EditText)findViewById(R.id.editText1);EditText editdetail=(EditText)findViewById(R.id.editText2);String word=editword.getText().toString();String detail=editdetail.getText().toString();SQLiteDatabase db=dbhelper.getReadableDatabase(); //獲得可讀寫的數據庫,如果沒有自動創建一個數據庫 db.execSQL("insert into dict values(null,?,?)",new String[]{word,detail});//數據庫執行插入sql語句editword.setText("");editdetail.setText("");Toast.makeText(MainActivity.this, "添加到數據庫成功!", Toast.LENGTH_LONG).show();} });search.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {// TODO Auto-generated method stubSQLiteDatabase db=dbhelper.getReadableDatabase();String key=((EditText)findViewById(R.id.editText3)).getText().toString();//數據庫對象執行占位符查詢sql語句Cursor cursor=db.rawQuery("select * from dict where news_word like ?",new String[]{"%"+key+"%"});//創建顯式Intent對象Intent intent=new Intent(MainActivity.this,ResultActivity.class);Bundle bundle=new Bundle();bundle.putSerializable("data", Cursor_To_List(cursor));//把Cursor轉換成ArrayList對象intent.putExtras(bundle);//Intent攜帶Bundle對象//開啟intent對應的ActivitystartActivity(intent); }});}protected ArrayList<Map<String,String>> Cursor_To_List(Cursor cursor) {// TODO Auto-generated method stubArrayList<Map<String,String>> list=new ArrayList<Map<String,String>>();while(cursor.moveToNext()){//游標移到下一行//獲取每個記錄的字段值String word=cursor.getString(1);String detail=cursor.getString(2);//放進一個Map中Map<String,String> map=new HashMap<String,String>();map.put("word", word);map.put("detail", detail);list.add(map);//map放進list中}return list;} <?xml version="1.0" encoding="utf-8"?> <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content" ><TableRowandroid:id="@+id/tableRow1"android:layout_width="fill_parent"android:layout_height="wrap_content" ><TextViewandroid:id="@+id/text1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="Word :"android:textSize="25dp" /><EditTextandroid:id="@+id/editText1"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10" ></EditText></TableRow><TableRowandroid:id="@+id/tableRow2"android:layout_width="fill_parent"android:layout_height="wrap_content" ><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Detail:"android:textSize="25dp" /><EditTextandroid:id="@+id/editText2"android:layout_width="fill_parent"android:layout_height="wrap_content"android:ems="10" ></EditText></TableRow><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Add_To_Dict" /><EditTextandroid:id="@+id/editText3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:ems="10" ></EditText><Buttonandroid:id="@+id/button2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Seach_From_Dict" /></TableLayout>
ResultActivity.java
package com.hust.sqliteopenhelper;import java.util.ArrayList; import java.util.List; import java.util.Map;import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ListView; import android.widget.SimpleAdapter;public class ResultActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_result);//獲得ListView組件ListView listview=(ListView) findViewById(R.id.listView1);//獲得Intent對象Intent intent=getIntent();ArrayList<Map<String,String>> list=(ArrayList<Map<String, String>>) intent.getSerializableExtra("data");//simpleadapter對象SimpleAdapter sa=new SimpleAdapter(this,list,R.layout.line,new String[]{"word","detail"},new int[]{R.id.text1,R.id.text2});//設置adapterlistview.setAdapter(sa);}
總結
以上是生活随笔為你收集整理的Android数据存储的三种方式-SharedPrefrences,File,SQLite的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用Action,Data属性启动系统A
- 下一篇: Android中ContentProvi