一.数据存储之SharedPreferences:
Android提供了SharedPreferences对象来帮助我们保存简单的应用程序数据,例如我们调节应用程序的字体大小,这时我们不能因为这样简单的数据而使用数据库,因为有点小题大做的感觉,所以android提供SharedPreferences对象。使用SharedPreferences对象的话,可以通过使用键/值对来保存所需的数据,这些数据将一起被自动保存到一个XML文件中。
使用SharedPreferences保存key-value对的步骤如下:
(1)使用Activity类的getSharedPreferences方法获得SharedPreferences对象,其中存储key-value的文件的名称由getSharedPreferences方法的第一个参数指定。
(2)使用SharedPreferences接口的edit获得SharedPreferences.Editor对象。
(3)通过SharedPreferences.Editor接口的putXxx方法保存key-value对。其中Xxx表示不同的数据类型。例如:字符串类型的value需要用putString方法。
(4)通过SharedPreferences.Editor接口的commit方法保存key-value对。commit方法相当于数据库事务中的提交(commit)操作。
实例演示:
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名" />
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="年龄" />
<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numeric="integer"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存"
android:onClick="OnClick"
/>
</LinearLayout>
主要代码:
public class MainActivity extends Activity {
private EditText e1 ;
private EditText e2 ;
private SharedPreferences spf;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.editText1);
e2 = (EditText)findViewById(R.id.editText2);
spf = this.getSharedPreferences("spf",Context.MODE_PRIVATE);
e1.setText(spf.getString("name", ""));
e2.setText(String.valueOf(spf.getInt("age", 0)));
}
public void OnClick(View v){
String name = e1.getText().toString();
String age = e2.getText().toString();
Editor editor = spf.edit();
editor.putString("name", name);
editor.putInt("age",Integer.valueOf(age));
editor.commit();
Toast.makeText(getApplicationContext(), "保存成功", Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
运行:
输入内容后点击保存按钮:
当我们再重新运行程序(输入框中会显示我们先前存储的数据):
文件的存储路径:
如果想导出spf.xml文件,点击右上角一个硬盘的图片,选择保存路径,就可以了。
查看spf.xml文件: