如何在android中使用getSharedPreferences [英] how to use getSharedPreferences in android

查看:80
本文介绍了如何在android中使用getSharedPreferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我必须在其中实施登录"活动.我有这些组件:

I have an application in which I have to implement a "Login" activity. I have these components:

  1. EditText 用户名
  2. EditText 密码
  3. 按钮登录
  4. 按钮取消

我希望我的应用程序在用户登录后记住用户的登录详细信息,直到用户按下注销"按钮.我没有在我的 xml 中使用首选项.

I want that my application to remember the login details of the user once the user has logged in until the user would press the "log out" button. I'm not using preferences in my xml.

如何让 getSharedPreferences(String name, int mode) 在我的应用程序中工作?

How do I get the getSharedPreferences(String name, int mode) to work in my application?

推荐答案

首先使用

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

现在保存 SharedPreferences 中的值

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

以上几行将用户名和密码写入首选项

Above lines will write username and password to preference

现在要从首选项中检索保存的值,您可以按照以下代码行

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(注意:不建议在应用程序中保存密码.您应该在保存或跳过保存密码之前对密码进行加密)

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

这篇关于如何在android中使用getSharedPreferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆