Android學習之路之資料的使用(一)
今天是Android學習第四天,上午簡單的學習了資料的儲存與使用,在這裡把上午的總結一下
資料存放區分為四大類:
* 檔案
* Sharedpreference(參數)
* SQLite資料庫
* 內容提供者(Content provide)
先來看看前兩種方法,檔案 和 Sharedpreference
1、 檔案
這裡的檔案和Java裡的檔案時一模一樣的,具體的就不在介紹,看過程
首先在主介面上定義兩個按鈕,一個是“寫檔案”一個是“讀檔案”,先寫後讀
對寫檔案添加監聽事件
writefile.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String content="張三 20 male";//FileOutputStream fos = new FileOutputStream("test.txt");FileOutputStream fos=null;try {fos = MainActivity.this.openFileOutput("data.txt", Context.MODE_PRIVATE);fos.write(content.getBytes());} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(fos!=null){try {fos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}});再對讀檔案添加監聽事件
readfile.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {FileInputStream in=null;try {in = MainActivity.this.openFileInput("data.txt");byte[] bytes = new byte[1024];int length=0;StringBuffer content = new StringBuffer();while((length=in.read(bytes))!=-1){content.append(new String(bytes,0,length));}Toast.makeText(MainActivity.this, content.toString(), Toast.LENGTH_SHORT).show();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(in!=null){try {in.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}});程式跑起來,先點擊寫檔案,這個時候項目的包下就會多出一個data.txt檔案,那麼不僅要問,這個檔案怎麼才能看到呢!
我們用Eclipse開發的,那就在這個工具裡看
vc7Sw8e1xLD8PC9wPgo8cD48aW1nIHNyYz0="http://www.2cto.com/uploadfile/Collfiles/20140918/2014091809041578.png" alt="\">
如,files下的data.txt就是我們剛剛寫的檔案,右上方的圈中可以講檔案匯出到電腦上,然後你可以查看裡面的內容,這裡不再示範
點擊讀檔案的時候,就會顯示寫入的字串
2、SharedPreferences
這是Android裡封裝好的一個包,好處就在於,方便,存取一些資料書寫很方便,提取也是如此
同樣在主介面畫兩個按鈕讀與寫
分別添加監聽事件
spwritefile.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 擷取SharedPreferences對象SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);//擷取編輯器Editor ed = sp.edit();//添加資料ed.putString("name", "張三");ed.putInt("age", 20);//提交ed.commit();}});spreadfile.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 擷取SharedPreferences對象SharedPreferences sp = getSharedPreferences("data", Context.MODE_PRIVATE);String name = sp.getString("name", "燙");int age = sp.getInt("age", 0);;Toast.makeText(MainActivity.this, name+"---"+age, Toast.LENGTH_SHORT).show();}});我們可以發現,寫資料的時候,先擷取SharedPreferences對象,然後擷取編輯器,然後直接putString就行了,最後別忘了commit提交,否則就像文字檔沒有儲存一樣!!
讀檔案的時候,get就行了,這個可以看一下倒出來的檔案
張三
這個檔案自動產生是xml檔案,裡面就是Map,Key與Value
!!!!!!