zoukankan      html  css  js  c++  java
  • Android SharedPreferences一般的读写 的用法。

    Android SharedPreferences一般用于轻量级的数据存储,比如用户名和密码等。

     1 package com.lixu.testsharepreferences;
     2 
     3 import android.app.Activity;
     4 import android.content.Context;
     5 import android.content.SharedPreferences;
     6 import android.content.SharedPreferences.Editor;
     7 import android.os.Bundle;
     8 import android.widget.Toast;
     9 
    10 public class MainActivity extends Activity {
    11 
    12     private static final String USER_NAME = "username";
    13     private static final String USER_PWS = "userpws";
    14     private String NAME = "name";
    15 
    16     @Override
    17     protected void onCreate(Bundle savedInstanceState) {
    18         super.onCreate(savedInstanceState);
    19         setContentView(R.layout.activity_main);
    20         writeSharedPreferences();
    21         readSharedPreferences();
    22 
    23     }
    24 
    25     // Context.MODE_PRIVATE 这个是设置访问权限 意思是只有本app可以读写里面的数据
    26     // 如果SharedPreferences里面没有写入数据 就返回"无值";
    27     private void readSharedPreferences() {
    28         SharedPreferences sp = this.getSharedPreferences(NAME, Context.MODE_PRIVATE);
    29 
    30         String str1 = sp.getString(USER_NAME, "无值");
    31         String str2 = sp.getString(USER_PWS, "无值");
    32 
    33         Toast.makeText(getApplicationContext(), "用户名是:" + str1, 1).show();
    34 
    35         Toast.makeText(getApplicationContext(), "用户密码是:" + str2, 1).show();
    36 
    37     }
    38 
    39     private void writeSharedPreferences() {
    40         SharedPreferences sp = this.getSharedPreferences(NAME, Context.MODE_PRIVATE);
    41 
    42         Editor edt = sp.edit();
    43         edt.putString(USER_NAME, "lixu");
    44         edt.putString(USER_PWS, "123456789");
    45         // 提交
    46         edt.commit();
    47 
    48     }
    49 
    50 }

    运行效果:

  • 相关阅读:
    处理emacs-org模式TODO的一个脚本
    MYSQL 数据类型
    Redis命令学习-Transaction(事务)
    成都青羊考场科目二考试分享
    地图入门_坐标系统
    microsoft SQL server,错误2
    搭建个人博客 方式2 使用jekyll
    WIN10 10招
    java正則表達式总结
    图解hdu5301Buildings
  • 原文地址:https://www.cnblogs.com/labixiaoxin/p/4979910.html
Copyright © 2011-2022 走看看