2013年1月28日 星期一

共用資料Shared Preferences

共用資料類別是用來處理基本型別的key-value 成對名稱與資料,該類別建構的物件可以存放Int、float、boolean 及字串型別


取得SharedPreferences類別的方式有:
getSharedPreferences(String name,int mode); 呼叫該方法需傳入兩個參數;第一個參數為自訂的儲存資料檔案名稱,如果指定的檔案不存在,則會在實際進行存取動作時自動建立。第二個參數為指定的操作模式
MODE_PRIVATE 只有呼叫的應用程式可以存取
MODE_WORLD_READABLE(1):允許其他應用程式可以讀取已經建立的檔案
MODE_WORLD_WRITABLE(2):允許其他應用程式可以寫入已經建立的檔案
最後呼叫COMMIT() 方法將資料存放


main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".Main" >

<RelativeLayout
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" >

  <Button
      android:id="@+id/write"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="write"
      />
  <Button
      android:id="@+id/read"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_toRightOf="@id/write"
  android:text="read"
      />   
  </RelativeLayout>
  
   <TextView
       android:id="@+id/tv"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"  
       />

</LinearLayout>





Main.java
package com.example.myiotest1;

import java.io.File;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

private Button write,read;
private TextView tv;
private  SharedPreferences sp;
private  SharedPreferences.Editor editor;
private File sdroot,approot,newfile;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
write=(Button)findViewById(R.id.write);
read=(Button)findViewById(R.id.read);
tv=(TextView)findViewById(R.id.tv);
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp=getSharedPreferences("mydata", MODE_PRIVATE);
editor=sp.edit();
editor.putString("user", "Jacky");
editor.putBoolean("Sound", true);
editor.putInt("Stage", 3);
editor.commit();
}
});

read.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp=getSharedPreferences("mydata", MODE_PRIVATE);
editor=sp.edit();

tv.append(" "+sp.getInt("stage", 0));
tv.append(sp.getBoolean("Sound", true)?"true":"false");
tv.append(sp.getString("user", "who") );

}
});


}

@Override
public 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;
}

}

沒有留言:

張貼留言