android开发中SharedPreferences用法详解(含源代码和运行结果截图)
来源:互联网 发布:大地真央 知乎 编辑:程序博客网 时间:2024/05/01 19:00
在Android应用程序开发中,经常需要保存一些类似于配置信息的简单类型数据,比如游戏玩家的积分、是否开启音效等。SharedPreferences类为我们保存、读取这些数据提供了便利。
SharedPreferences接口提供以下常用方法来访问SharedPreferences对象中的key-value对:
boolean contains(String key):判断SharedPreferences对象是否包含键值为key的数据。
boolean getXxx(String key, xxx defaultValue):获取SharedPreferences对象中指定key对应的value。如果该key不存在,返回默认值defaultValue。xxx可以是boolean、float、int、String、long等基本类型。
调用SharedPreferences的edit()方法可以获得Editor对象,通过Editor对象来向SharedPreferences对象中写入数据,有以下常用方法:
SharedPreferences prefs;
Editor editor = prefs.edit();
editor.clear():清空数据
editor.putXxx(String key, xxx value):向SharedPreferences对象中存入指定key对应的数据,xxx可以是boolean、float、int、String、long等基本类型。
editor.remove(String key):删除key对应的数据
editor.apply():保存更改,用于Android 2.3以上版本,异步写入,线程安全。
editor.commit():保存更改,同步写入,它会阻塞调用线程,写入成功返回true,写入失败返回false。
SharedPreferences是一个接口,只能通过Context提供的getSharedPreferences(String name, int mode)方法来获取实例。mode参数支持以下几个值:
Context.MODE_PRIVATE:只能被本应用程序读写。
Context.MODE_WORLD_READABLE:能被其他应用程序只读。
Context.MODE_WORLD_WRITEABLE:能被其他应用程序读、写。
SharedPreferences保存的数据在程序重启后仍然有效,所以可以用来保存用户设置的一些数据。
下面来看我的一个demo,在一个activity中点“设置”按钮跳转到另一个activity中,设置相关选项后,重启应用程序,则可以在activity中看到上次设置的结果。
主activity布局xml代码:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/setButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="设置" android:textSize="20dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/engineLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="识别引擎:" android:textSize="20dp"/> <TextView android:id="@+id/engineTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <TextView android:id="@+id/languageLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="识别语言:" android:textSize="20dp"/> <TextView android:id="@+id/languageTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="20dp"/> </LinearLayout> </LinearLayout></span>
主activity的java代码:
<span style="font-size:18px;">package my.set;import my.set.R;import android.app.Activity;import android.content.Intent;import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class TestActivity extends Activity{TextView engineView;TextView languageView;Button setButton;SharedPreferences sharedPreferences;class buttonListener implements OnClickListener {public void onClick(View view) {Intent intent = new Intent(TestActivity.this, SetActivity.class);startActivity(intent);}}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);engineView = (TextView)findViewById(R.id.engineTextView);languageView = (TextView)findViewById(R.id.languageTextView);setButton = (Button)findViewById(R.id.setButton);sharedPreferences = getSharedPreferences("set", MODE_PRIVATE);String engineString = sharedPreferences.getString(SetActivity.PREF_OCR_ENGINE, "");String languageString = sharedPreferences.getString(SetActivity.PREF_RECOGNIZED_LANGUAGE, "");setButton.setOnClickListener(new buttonListener());engineView.setText(engineString);languageView.setText(languageString); }}</span>设置界面的xml布局代码:
<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/engine_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/engine_text_view" android:textSize="20dp"/> <RadioGroup android:id="@+id/engine_radio_group" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/tesseract_radio_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tesseract_radio_button" android:textSize="20dp"/> <RadioButton android:id="@+id/tesseract_and_cube_radio_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/tesseract_and_cube_radio_button" android:textSize="20dp"/> </RadioGroup> <TextView android:id="@+id/language_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/language_text_view" android:textSize="20dp"/> <RadioGroup android:id="@+id/language_radio_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <RadioButton android:id="@+id/Chinese_radio_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/Chinese_radio_button" android:textSize="20dp"/> <RadioButton android:id="@+id/Engilsh_radio_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/English_radio_button" android:textSize="20dp"/> </RadioGroup> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"> <Button android:id="@+id/okButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/ok" android:textSize="20dp"/> <Button android:id="@+id/cancelButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/cancel" android:textSize="20dp"/> </LinearLayout></LinearLayout></span>
设置界面的java代码:
<span style="font-size:18px;">package my.set;import android.app.Activity;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.RadioButton;import android.widget.RadioGroup;import my.set.R;public class SetActivity extends Activity {//定义识别引擎的单选按钮RadioButton tesseractRadioButton;RadioButton tessAndCubeRadioButton;//定义识别语言的单选按钮RadioButton chineseRadioButton;RadioButton englishRadioButton;RadioGroup engineGroup;RadioGroup languageGroup;Button okButton;Button cancelButton;public static final String PREF_OCR_ENGINE = "PREF_OCR_ENGINE";public static final String PREF_RECOGNIZED_LANGUAGE = "PREF_RECOGNIZED_LANGUAGE";SharedPreferences prefs;private String choosedEngine = "";private String choosedLanguage = "";@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.set);tesseractRadioButton = (RadioButton)findViewById(R.id.tesseract_radio_button);tessAndCubeRadioButton = (RadioButton)findViewById(R.id.tesseract_and_cube_radio_button);chineseRadioButton = (RadioButton)findViewById(R.id.Chinese_radio_button);englishRadioButton = (RadioButton)findViewById(R.id.Engilsh_radio_button);engineGroup = (RadioGroup)findViewById(R.id.engine_radio_group);languageGroup = (RadioGroup)findViewById(R.id.language_radio_group);okButton = (Button)findViewById(R.id.okButton);cancelButton = (Button)findViewById(R.id.cancelButton);prefs = getSharedPreferences("set", MODE_PRIVATE);//添加事件监听器engineGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubif (checkedId == R.id.tesseract_radio_button) {choosedEngine = tesseractRadioButton.getText().toString();} else {choosedEngine = tessAndCubeRadioButton.getText().toString();}}});languageGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(RadioGroup group, int checkedId) {// TODO Auto-generated method stubif (checkedId == R.id.Chinese_radio_button) {choosedLanguage = chineseRadioButton.getText().toString();} else {choosedLanguage = englishRadioButton.getText().toString();}}});okButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubsavePreferences();finish();}});cancelButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubfinish();}});}private void savePreferences() {Editor editor = prefs.edit();editor.putString(PREF_OCR_ENGINE, choosedEngine);editor.putString(PREF_RECOGNIZED_LANGUAGE, choosedLanguage);editor.commit();}}</span>下面是效果图:
第一次启动后界面:
设置界面:
点击保存按钮后,重启应用程序,则看到上次设置结果如下图:
打开DDMS的File Explorer,SharedPreferences数据保存在/data/data/<package name>/shared_prefs文件夹下,如下图:
导出这个xml文件,打开如下图:
- android开发中SharedPreferences用法详解(含源代码和运行结果截图)
- android中RadioGroup、RadioButton、Spinner、EditText用法详解(含示例截图和源代码)
- android中SharedPreferences用法详解
- android中sharedPreferences的用法详解
- Android中SharedPreferences用法
- Android中SharedPreferences用法
- Android中SharedPreferences用法
- Android开发中相当便捷的JSON反序列化实现(含源代码) 连带有handler和进度条功能
- Common Dbutils组件用法详解(含源代码)(转)
- Android 中SharedPreferences详解
- Android中SharedPreferences(共享参数)用法
- Android中SharedPreferences的用法(一)
- Android中SharedPreferences的用法(二)
- Common Dbutils组件用法详解(含源代码)
- android中SharedPreferences的用法
- Android中sharedPreferences的用法
- android中sharedPreferences的用法
- android中sharedPreferences的用法
- TCP协议---连接的状态
- 【web++_第三阶_SpringMVC附录】其他资源临时存
- 第十四周项目三 多科成绩单(3)
- 11月总结
- android --小球跟随手指滑动
- android开发中SharedPreferences用法详解(含源代码和运行结果截图)
- asp.net NHibernate Spring.net 框架搭建(开源)
- 32位汇编语言学习笔记(10)--分析for循环的汇编代码
- PHP导出CSV文件
- 网络 两边通信 net io SetverSocket Socket DataInputStream OutputStream getInputStream getOutputStream
- hdu 5119 Happy Matt Friends
- Servlet 中文乱码问题及解决方案剖析
- 从这里起航!
- IOS开发---C语言-㉔递归函数