<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/textView" /> </LinearLayout>
package cn.com.sharedPreferencesTest;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class SharedPreferencesActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
saveSharedPreferences();
readSharedPreferences();
}
/**
* @description 创建并保存一些设置信息
*/
private void saveSharedPreferences(){
/*
* getSharedPreferences(String name,int mode)方法是在Context中定义的抽象方法,在ContextWrapper中进行了具体实现,
* 该方法会根据用户传递的名称和写入类型创建一个SharedPreferences对象进行返回。
* 在Activity中,还有一个方法可以回去SharedPreferences对象,这个方法就是SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
* 改方法在Activity中定义并实现,这里没有name参数是因为该方法默认将当前Activity的类名作为name属性(这里的类名并不包含包路径哦)
* */
SharedPreferences sharedPreferences = getSharedPreferences("preferences", MODE_PRIVATE);
//存储数据
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", "蔡依林");
editor.putInt("age", 31);
Boolean b = editor.commit();
if(b){
Log.i("通知:", "保存成功!");
}else{
Log.i("通知", "保存失败!");
}
}
/**
* @author chenzheng_java
* @description 读取我们添加到SharedPreference对象中的数据
* @since 2011/03/05
*/
private void readSharedPreferences(){
String result = "美女信息:/n" ;
SharedPreferences sharedPreferences = this.getSharedPreferences("preferences", MODE_PRIVATE);
result+=" 姓名 "+sharedPreferences.getString("name", "暂时没有人");
result+=" 年龄"+sharedPreferences.getInt("age", -1);
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(result);
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有