当前位置: 代码迷 >> 综合 >> SharedPreferences 用法
  详细解决方案

SharedPreferences 用法

热度:66   发布时间:2024-02-11 00:02:47.0
    /*** 保存用户信息*/private void saveUserInfo(){SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);SharedPreferences.Editor editor = userInfo.edit();//获取Editor//得到Editor后,写入需要保存的数据editor.putString("username", "一只猫的涵养");editor.putInt("age", 20);editor.commit();//提交修改Log.i(TAG, "保存用户信息成功");}/*** 读取用户信息*/private void getUserInfo(){SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);String username = userInfo.getString("username", null);//读取usernameint age = userInfo.getInt("age", 0);//读取ageLog.i(TAG, "读取用户信息");Log.i(TAG, "username:" + username + ", age:" + age);}/*** 移除年龄信数据*/private void removeUserInfo(){SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);SharedPreferences.Editor editor = userInfo.edit();//获取Editoreditor.remove("age");editor.commit();Log.i(TAG, "移除年龄数据");}/*** 清空数据*/private void clearUserInfo(){SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);SharedPreferences.Editor editor = userInfo.edit();//获取Editoreditor.clear();editor.commit();Log.i(TAG, "清空数据");}

 

  相关解决方案