》1,getSharedPreferences("info", Context.MODE_PRIVATE);不管那個一個類保存的數據,在其他的類中,都能獲取到
》 2,getPreferences(Context.MODE_PRIVATE); 哪一個類 保存的數據 只能被本類獲取出來
aplay() : 異步處理
commit: 有返回值
Java代碼
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Switch;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void OnclickBtn(View v){
switch (v.getId()) {
case R.id.btn_save://保存數據
/**
* 參數1:保存數據文件的名稱
*
* 參數2:數據的標記
*
* MODE_PRIVATE:數據只能被本應用程序讀和寫
* MODE_APPEND:新內容能追加到原內容之後
* MODE_WORLD_READABLE:能被其他程序讀 但不能寫
* MODE_WORLD_WRITEABLE:能被其他程序讀和寫
*
*
* <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<float name="floatType" value="1.0" />
<int name="intType" value="34" />
<string name="stringType">你好</string>
<boolean name="booleanType" value="true" />
<long name="longType" value="123" />
</map>
*
* 保存的路徑:data/data/程序包名/shard_prefs/參數1.xml
*
*/
// SharedPreferences preferences = getSharedPreferences("info", Context.MODE_PRIVATE);
SharedPreferences preferences = getPreferences(Context.MODE_PRIVATE);
//獲取編輯者對象
Editor editor = preferences.edit();
editor.putBoolean("booleanType", true);
editor.putFloat("floatType", 1.0f);
editor.putInt("intType", 34);
editor.putLong("longType", 123l);
editor.putString("stringType", "你好");
//要提交數據
editor.commit();
break;
case R.id.btn_get://獲取數據
//SharedPreferences preferences2 = getSharedPreferences("info", Context.MODE_PRIVATE);
SharedPreferences preferences2 = getPreferences(Context.MODE_PRIVATE);
boolean b1 = preferences2.getBoolean("booleanType", false);
int int1 =preferences2.getInt("intType", -1);
String str = preferences2.getString("stringType", "defauls");
String str1 = preferences2.getString("stringType1", "defauls");
Log.i("==SharedPreferences==", b1+" "+int1+" "+str+" "+str1);
break;
default:
break;
}
}
}