SharedPreferences存储
来源:互联网 发布:linux认证工程师 编辑:程序博客网 时间:2024/05/19 13:19
适用于少量数据且数据格式简单的存储情况,都是普通的字符串、标量类型的值等,如应用程序的各种配置信息。对于这种数据,Android提供了SharedPreferences进行保存。
下面是SharedPreferences简单的读写程序。
public class SharedPreferencesTest extends Activity { SharedPreferences sp; SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button read = (Button) findViewById(R.id.read); Button write = (Button) findViewById(R.id.write); read.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //读取时间信息 String result = readData(SharedPreferencesTest.this,"time"); //用Toast显示 Toast.makeText(SharedPreferencesTest.this,result,5000).show(); } }); write.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //设置存入时间的格式 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd "+"hh:mm:ss"); String name = "time"; String value = sdf.format(new Date()); //value值设置为当前时间 writeData(SharedPreferencesTest.this,name,value); Toast.makeText(SharedPreferencesTest.this,"写入time成功",5000).show(); } }); } //写入数据 private void writeData(Context context, String name, String value) { sp = context.getSharedPreferences("lune", MODE_PRIVATE); editor = sp.edit(); //添加一个编辑 editor.putString(name, value); //写入键值对 name-s; editor.commit(); //提交修改 } //读取数据 private String readData(Context context, String name) { sp = context.getSharedPreferences("lune", MODE_PRIVATE); String result = sp.getString(name, null); //第一个参数为key,第二个参数为默认值,若找不到value,则返回默认值 if (result == null) { result = "此数据不存在"; } return result; }}
界面只有两个按钮,下面是main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="写入数据" android:id="@+id/write" android:layout_gravity="center_horizontal" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="读取数据" android:id="@+id/read" android:layout_gravity="center_horizontal" /></LinearLayout>
运行结果如下图:
0 0
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences 存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences 存储
- SharedPreferences存储
- SharedPreferences存储
- SharedPreferences存储
- 【SharedPreferences存储】SharedPreferences存储方式
- 文件存储、SharedPreferences存储
- nand flash驱动的编写
- 微软面试百题002——返回优先级的栈
- 文章标题
- Java Exception 捕获和展示
- hdu 2841 Visible Trees 容斥,分解质因数
- SharedPreferences存储
- Three.js学习笔记---我和小伙伴都惊呆了
- PHP位运算符详解
- 向量基础知识
- HDU 5800 To My Girlfriend (动态规划)
- Ajax 异步加载
- Java Web 代码调试
- css 重置样式表
- Android Studio的国际化