安卓系统默认提供了一下几种数据储存的方式:
使用Shared Preferences
Shared Preferences类主要用于保存键值对的数据类型。我们可以使用它保存一些简单的数据类型。
获得SharedPreferences对象有两种方法:
上面两种方法的分别主要是:
第一种方法可以创建多个文件来保存数据
第二种方法只能创建一个文件保存数据
我们先来创建一个这样的布局:
布局代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="write to file"/>
</LinearLayout>
布局准备好后就可以获取SharedPreferences对象写入数据:
package com.whathecode.storageoptinos;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText namefield = (EditText) findViewById(R.id.username);
final EditText agefield = (EditText) findViewById(R.id.age);
Button btnWrite = (Button) findViewById(R.id.write);
// 获取SharedPreferences对象,文件权限为私有
SharedPreferences spf = getSharedPreferences("record", MODE_PRIVATE);
// 获取编辑器
final SharedPreferences.Editor editor = spf.edit();
btnWrite.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
String username = namefield.getText().toString();
String age = agefield.getText().toString();
editor.putString("username", username);
editor.putString("age", age);
if (editor.commit()) // 当成功写入数据返回true
{
Toast.makeText(getBaseContext(), "文件已写入",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
上面的代码中,我们主要使用SharedPreferences的内部类Editor类
我们主要使用这个类的几个Put*方法
当调用完这些方法后我们就可以使用commit()或者apply()方法开始写数据
需要注意的是,当多个Editor对同一个文件进行写数据的时候,后完成的一个Editor的结果将覆盖前一个的结果
commit和apply方法的区别是:commit写入成功返回true,而apply没有返回值。
当我们不在乎返回值的时候可以调用apply()方法写数据。
运行结果:
数据写入后我们就可以在Eclipse的ddms试图中查看是否有写入成功
数据保存在 /data/data/包名/shared_prefs目录下
原文:http://www.cnblogs.com/ai-developers/p/4244788.html