您的位置:首页 > 移动开发 > Android开发

在Android中使用SharedPreferences保存简单的数据

2015-05-08 22:43 453 查看
在Android中保存一些简单的数据,使用SharedPreferences是比较方便的。比如用SharedPreferences保存软件的配置文件等,SharedPreferences实质是把数据写在一个xml文件中。具体实现代码如下; xml布局文件

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<button< span="">
android:id="@+id/btnsave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/save"
android:onClick="SaveBtn"
/>
<button< span="">
android:id="@+id/btnread"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btnsave"
android:text="@string/read"
android:onClick="ReadBtn"
/>

本例中使用在布局文件中指定onClick方法响应点击事件,以下是java代码:
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void SaveBtn(View v){ //保存数据

SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("username", "用户名:55484946");
editor.putString("password", "密码:12345678");
editor.commit();
Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();

}

public void ReadBtn(View v){ //读取数据

SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
String str = sp.getString("username", "用户名不存在");
str += sp.getString("password", null);
Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();

}

}
以上就是SharedPreferences 保存数据的实现。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐