数据存储有好几种方式:shared preferences 主要用来存储简单的安全性要求不高的信息。
1. 提供基本数据类型的存储---简单
2.对应xml存储的键值对,没有安全性控制。
android为我们封装了一个访问xml文档的接口。
Retrieve a SharedPreferences
object for accessing preferences that are private to this activity. This simply calls the underlyinggetSharedPreferences(String, int)
method by passing in this activity's class name as the preferences name.
加入activity类名以后调用getSharedPreferences(String, int)方法。
用处经常用来存储android程序中的设置信息等简单的数据信息。
demo:存储简单的设置信息例子
package com.example.sharedp;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
public class MainActivity extends Activity {
private SharedPreferences settings = null;
//声音设置,是否静音,默认为静音
private boolean isMute = true;
private CheckBox chbSysSound = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = this.getPreferences(Activity.MODE_PRIVATE);
this.chbSysSound = (CheckBox) findViewById(R.id.chbSysSound);
isMute = settings.getBoolean(Setting.SETTING_SOUND, false);
this.chbSysSound.setChecked(isMute);
this.chbSysSound.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(chbSysSound.isChecked()){
displayToast("静音了.");
isMute = true;
}
else{
displayToast("声音开启.");
isMute = false;
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void displayToast(String message){
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
}
public boolean onKeyDown(int keyCode,KeyEvent event){
if(keyCode == KeyEvent.KEYCODE_BACK){
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(Setting.SETTING_SOUND, isMute);
editor.commit();
}
return super.onKeyDown(keyCode, event);
}
}
package com.example.sharedp;
/**
* 设置信息公共类
* */
public class Setting {
public static final String SETTING_SOUND = "setting_sound";
}
<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" >
<CheckBox
android:id="@+id/chbSysSound"
android:checked="false"
android:text="@string/settings_sound"
android:layout_height="wrap_content"
android:layout_width="fill_parent"/>
</LinearLayout>