如何使用getShared preferences在安卓如何使用、getShared、preferences

2023-09-12 00:28:09 作者:北回归线上的约定√

我在,我要实现一个登录活动的应用程序。我有以下组件:

的EditText的用户名 的EditText密码 按钮登录 按钮取消

我想我的应用程序记住用户的登录信息,一旦用户登录,直至用户将preSS的注销按钮。我不使用preferences在我的XML。

我如何获得getShared preferences(字符串名称,诠释模式),在我的应用程序工作?

解决方案

 共享preferences为userDetails = context.getShared preferences(的UserDetails,MODE_PRIVATE);
编辑器编辑= userDetails.edit();
edit.clear();
edit.putString(用户名,txtUname.getText()的toString()修剪());
edit.putString(密码,txtPass.getText()的toString()修剪());
edit.commit();
Toast.makeText(背景下,登录信息将被保存。,3000).show();
 

修改

这种方式可以获取preference

 共享preferences为userDetails = context.getShared preferences(的UserDetails,MODE_PRIVATE);
字符串的uname = userDetails.getString(用户名,);
字符串传递= userDetails.getString(密码,);
 

android用共享参数,Android学习指南之十八 共享参数类SharedPreferences的使用

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

EditText username EditText password Button Login Button Cancel

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.

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

解决方案

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString("username", txtUname.getText().toString().trim());
edit.putString("password", txtPass.getText().toString().trim());
edit.commit();
Toast.makeText(context, "Login details are saved..", 3000).show();

EDIT

this way you can fetch preference

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);
String Uname = userDetails.getString("username", "");
String pass = userDetails.getString("password", "");