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

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

  1. xmlns:tools="http://schemas.android.com/tools"
  2. android:layout_width="match_parent"
  3. android:layout_height="match_parent"
  4. android:paddingBottom="@dimen/activity_vertical_margin"
  5. android:paddingLeft="@dimen/activity_horizontal_margin"
  6. android:paddingRight="@dimen/activity_horizontal_margin"
  7. android:paddingTop="@dimen/activity_vertical_margin"
  8. tools:context=".MainActivity" >
  9. <button< span="">
  10. android:id="@+id/btnsave"
  11. android:layout_width="wrap_content"
  12. android:layout_height="wrap_content"
  13. android:text="@string/save"
  14. android:onClick="SaveBtn"
  15. />
  16. <button< span="">
  17. android:id="@+id/btnread"
  18. android:layout_width="wrap_content"
  19. android:layout_height="wrap_content"
  20. android:layout_below="@+id/btnsave"
  21. android:text="@string/read"
  22. android:onClick="ReadBtn"
  23. />
本例中使用在布局文件中指定onClick方法响应点击事件,以下是java代码:
  1. import android.os.Bundle;
  2. import android.view.View;
  3. import android.widget.Toast;
  4. import android.app.Activity;
  5. import android.content.Context;
  6. import android.content.SharedPreferences;
  7. import android.content.SharedPreferences.Editor;
  8. public class MainActivity extends Activity{
  9. @Override
  10. protected void onCreate(Bundle savedInstanceState) {
  11. super.onCreate(savedInstanceState);
  12. setContentView(R.layout.activity_main);
  13. }
  14. public void SaveBtn(View v){ //保存数据
  15. SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
  16. Editor editor = sp.edit();
  17. editor.putString("username", "用户名:55484946");
  18. editor.putString("password", "密码:12345678");
  19. editor.commit();
  20. Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
  21. }
  22. public void ReadBtn(View v){ //读取数据
  23. SharedPreferences sp = this.getSharedPreferences("config", Context.MODE_PRIVATE);
  24. String str = sp.getString("username", "用户名不存在");
  25. str += sp.getString("password", null);
  26. Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();
  27. }
  28. }
以上就是SharedPreferences 保存数据的实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值