当前位置: 代码迷 >> Android >> Android数据归档SharedPreferences(1)
  详细解决方案

Android数据归档SharedPreferences(1)

热度:67   发布时间:2016-04-28 01:34:14.0
Android数据存档SharedPreferences(1)

App运行中,需要配置很多的参数信息,这些参数信息保存在哪里呢?

  • SharedPreferences 配置信息存储

这个接口保存只是一些基本数据类型,例如String,int,float,boolean,long因此接下来的实例我们就围绕这几个数据类型展开。

首先SharedPreferences 里面存储的形式相当于map的键值,都有对应的相应的key,利用key方法我们可以取出对应的数据类型。同时利用edit写入数据。

public class MainActivity extends Activity {	private static final String FILENAME="ee"; 	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		//指定操作的文件名称		SharedPreferences share=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);		//编辑文件		SharedPreferences.Editor edit=share.edit();		edit.putString("name", "张依依");//保存字符串类		edit.putInt("age", 21);//保存int类		edit.commit();//利用commit进行提交	}

?

注意:这里数据一定要用commit进行提交,否则不会被保存

这样程序运行之后,数据又保存到了哪里?保存到了ee.xml文件里,那这个文件又去哪里找呢

其实保存在了DDMS文件中,想要寻找的话,打开windows-open perspective-other 打开DDMS

再打开file explore

data-data-你的包名称下的shared_prefs


可以用DDMS的put a file from the device

导出ee.xml,然后用记事本打开效果如图:



?
?

上面讲了如何写入,现在重要的是如何读出:

为了显示我们首先配置布局文件:

?

<TextView        android:id="@+id/name"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textSize="22px" />    <TextView        android:id="@+id/age"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:textSize="22px" />

?

?在定义Activity文件:

在原有基础上加上读功能

?

?

?

?

?

?

?

private static final String FILENAME="ee"; 	private TextView name=null;	private TextView age=null;	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		//指定操作的文件名称		SharedPreferences share=super.getSharedPreferences(FILENAME, Activity.MODE_PRIVATE);		//编辑文件		SharedPreferences.Editor edit=share.edit();		edit.putString("name", "张依依");//保存字符串类		edit.putInt("age", 21);//保存int类		edit.commit();//利用commit进行提交		this.name=(TextView)super.findViewById(R.id.name);		this.age=(TextView)super.findViewById(R.id.age);		this.name.setText("作者:"+share.getString("name", "没有作者信息"));		this.age.setText("年龄:"+share.getInt("age", 0));			}

?

?实现效果如下:

?



?

?

  相关解决方案