我在這里只列出我熟悉常用的四種:1.Sharepreferences衣形;2,內(nèi)部儲存姿鸿;3谆吴,外部儲存4.數(shù)據(jù)庫儲存倒源。還有其他的自己感興趣在研究
1.Sharepreferences
? ? ? ? ? ? 存儲數(shù)據(jù)是以xml文件形式存儲,文件存放在/data/data//shared_prefs目錄下纪铺。
? ? ? 步驟:
? ? ? ? ? ? ? ?1)獲取SharedPreferences對象
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?shareprefere? sp=getSharedPreferences(name,mode);
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?第一個參數(shù):”Name:用于指定SharedPreferences文件的名稱
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 第二個參數(shù):mode指定操作模式相速。
? ? ? ? ? ? ? 2)獲取編輯器對象:
? ? ? ? ? ? ? ? ? ? ? ? ? Editor editor=sp.edit();
? ? ? ? ? ? ? ?3) ? 向SharedPreferences.Editor對象中添加數(shù)據(jù)。添加一個字符串則使用putString()方法
? ? ? ? ? ? ? ?4)調(diào)用commit()方法將添加的數(shù)據(jù)提交鲜锚,從而完成數(shù)據(jù)存儲操作
那我們?nèi)绾潍@取呢突诬?
一般得話我們在activity銷毀之前進(jìn)行儲存:也就是在onOause()方法儲存,在onCreate()方法任叻薄:sp.getString()旺隙;
2:內(nèi)部儲存:也就是保存到手機(jī)文件中
存:FileOutPutString? ? fs= openFileOutput(name,mode)第一個參數(shù)就是文件名字;第二個參數(shù)文件的操作 ? ? ? ? ? ?模式骏令;因為返回的是FileOutPutString的對象蔬捷,所以我們就是可以將其寫入文件中fs.write(" data");最 ? ? ? ? ? ? 后關(guān)閉流;
壤拼:通過openFileinPut(“data”)周拐;獲取到FileInputString對象最后fi.read();最后關(guān)閉流,防止內(nèi)存溢出
3:外部儲存:也就是SD卡儲存:
? ? ? ?步驟:
? ? ? ? ? ?1)先判斷SD卡是否掛載: ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? ? ? ? ? ? ? if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))凰兑;?
? ? ? ? ? ?2)然后在sd卡更目錄創(chuàng)建一個文件保存數(shù)據(jù)
? ? ? ? ? ? ? ? ? ? ? ? ? ? 先獲取SDcard路徑:Filesd ?SDRoot?=Environment.getExternalStorageDirectory();
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?在創(chuàng)建文件:new File(SDRoot妥粟,“file.yext”)獲取到file對象
? ? ? ? ? ? ? 3)就可以向文件中寫入保存的數(shù)據(jù):
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Bufferwriter bw=new Buferwriter(new Filewrite(file));
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bw.write();寫入數(shù)據(jù)
取出來的話和文件保存取文件是一樣的吏够。
4:數(shù)據(jù)庫(前提對sql語言了解)
這個比較麻煩一點:
步奏:1)先創(chuàng)建一個數(shù)據(jù)庫操作類繼承SQLiteopenHelper類勾给;重寫你面的倆個方法onCreate()和onUpgreat()
public class WordHelper?extends SQLiteOpenHelper{
publicvoidonCreate(SQLiteDatabasedb){
db.execSQL("自己創(chuàng)建的數(shù)據(jù)庫表");//用到創(chuàng)建數(shù)據(jù)的操作
}}
2)在MainActivity中實列化幫助類
helpere =new WordHelper(this,"word.db",null,1);第二個參數(shù)是數(shù)據(jù)庫的名稱,最后一個是版本號
3)然后在保存之前獲取數(shù)據(jù)庫的連接:
SQLiteDatabase db = this.getWritableDatabase();
創(chuàng)建ContenViews 通過put保存數(shù)據(jù)庫
ContentValues values = new ContentValues();
values.put(KEY, “data””);