android实现SharedPreferences的存入与取出的现实效果
首先创建一个项目为SharedPreferenceDemo:
在String.xml下写入如下文本字符:
<resources>
<string name="preferences">应用名称</string>
<string name="name">姓名</string>
<string name="age">年龄</string>
<string name="app_save">保存参数</string>
<string name="app_success">保存成功!</string>
<string name="app_recove">恢复成功!</string>
然后在main.xml下:
<LineLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/app_name">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/age">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/age">
<LineLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content'
android:oritentation="horizontal" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_save"
android:id="@+id/save">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_recove"
android:id="@+id/revoce">
</LineLayout>
</LineLayout>
以上为界面布局,旗下就是对ACTIVITY进行参数保存操作了:
private EditText name;
private EditText age;
........{
name = (EditText)findViewById(R.id.spp_name);
age = (EditText)findViewById(R.id.app_age);
Button saveButton = (Button)findViewById(R.id.app_save);
Button recoveButton = (Button)findViewById(R.id.app_recove);
saveButton.setOnclickListener(new View.OnClickListener(){
public void onClick(View v){
String app_name = name.getText().toString();
String app_age = age.getText().toString();
SharedPreferences preference = getSharedPreferences("person",Context.MODE_PRIVATE);
Editor edit = preference.edit();
edit.putString("name",app_name);
edit.putInt("age",Integer.parse(app_age));
edit.commit();
Toast.makeText(ActionPreferences.this.R.string.success,1).show();
}
});
recoveButton.setOnClickListener(new View.onClickListener(){
public void onClick(View v){
Sharedpreferences preference = getSharedPreferences("person",Context.MODE_PRIVATE);
name.setText(preference.getString("name",""));
age.setText(String.valueOf(preference.getInt("age",20)));
}
});
}
以上为使用SharedPreferences来保存参数与恢复参数的操作.运行即可得到,但是我们要在跨应用的程度下来访问其SharedPreferences的参数时需要把其MODE设置成:Context.MODE_WORLD_READABLE;即可:
如新创建一个项目为other:
新建一个测试类为:PerferencesTest:extends AndroidCaseText
public void test(){
Content context = this.getContext().createPackageContext("com.jsd.action",Context.MODE_WORLD_READABLE);
SharedPreferences preferences = getSharedPreferences("person",Context.MODE_WORLD_READABLE);
String name = prerences.getString("name","");
String age = String.valueOf(prerences.getInt("age",20));
Log.i("PerferencesDemo","name:"+name+"age:"+age);
}
以上就实现了跨应用访问SharedPreferences的参数,其实都很简单几步搞定的问题,自己多耐心点就OK了,今天完毕