登录和注销时如何使用SharedPreferences控制存储用户数据? [英] How to control storing user data using SharedPreferences when logging in and out?

查看:106
本文介绍了登录和注销时如何使用SharedPreferences控制存储用户数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个使用用户名和密码登录的应用程序,然后只要用户未注销-或者没有删除应用程序数据就一直保持登录状态,据我所知最好使用SharedPreferences.如何正确实施?

I'm trying to create an app which uses username and password to login, then stay logged in as long as user didn't logout -or didn't delete app data of course-, and as far as I know that SharedPreferences is the best to do so. How do I implement it correctly?

我尝试创建SharedPreferences对象,然后创建Editor对象,以在启动应用程序时检查是否存储了用于用户名和密码的数据,如果存在,则自动登录.然后,要注销,请单击注销"按钮,然后从SharedPreferences中删除用户名和密码键.但是我不确定,我想我做错了方法,所以该应用程序无法正常工作.

I've tried to create SharedPreferences object then Editor object to check at launching app if there are data stored for username and password, and if so then login automatically. Then for logging out, once is logout button is clicked, username and password keys are deleted from SharedPreferences. But I'm not sure, I guess I've done it in a wrong way so the app doesn't work.

这是我要制作的一个简单示例(假设所有XML文件和ID都正确,因为在添加SharedPreferences之前应用程序运行良好)

Here is a simple example of what I want to make(assume all XML files and IDs are right because the app was working fine before adding SharedPreferences):

LoginActivity.java:

LoginActivity.java:

public class LoginActivity extends AppCompatActivity {
    private Button button_login;
    private EditText editText_username;
    private EditText editText_password;
    private SharedPreferences pref;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        perf = getApplicationContext().getSharedPreferences("user_pref", 0);
        SharedPreferences.Editor editor = perf.edit();
        if(!(sharedPref.getString("username", null)).isEmpty() && !(sharedPref.getString("password", null)).isEmpty()){
            doLogin(sharedPref.getString("username", null), sharedPref.getString("password", null));
        }

        //define editText_username, editText_password and button_login
        button_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(editText_username.getText()) && !TextUtils.isEmpty(editText_password.getText())){
                    doLogin(editText_username.getText().toString().trim(), editText_password.getText().toString().trim());
                }
            }
        });
    }


    public void doLogin(String username, String password) {

        Intent loginIntent = new Intent(LoginActivity.this, HomeActivity.class);
        SharedPreferences.Editor editor = perf.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        startActivity(loginIntent);
                        finish();
    }

}

HomeActivity.java:

HomeActivity.java:

public class HomeActivity extends AppCompatActivity {
    private SharedPreferences perf;
    private Button button_logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        perf = getApplicationContext().getSharedPreferences("user_pref", 0);


        //button_logout define
        button_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = perf.edit();
                editor.remove("username");
                editor.remove("password");
                Intent logoutIntent = new Intent(HomeActivity.this, LoginActivity.this);
                startActivity(logoutIntent);
                finish();
            }
        });
}

我没有任何结果,它崩溃了.所以我不确定我是否做对了.

I don't get any results, it crashes. So I'm not sure if I did it correctly or not.

推荐答案

创建一个AppPreference类:-

create an AppPreference class :-

public class AppPrefrences {

    private static SharedPreferences mPrefs;
    private static SharedPreferences.Editor mPrefsEditor;

    public static boolean isUserLoggedOut(Context ctx) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        return mPrefs.getBoolean("id_logged_in", true);
    }

    public static void setUserLoggedOut(Context ctx, Boolean value) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        mPrefsEditor = mPrefs.edit();
        mPrefsEditor.putBoolean("id_logged_in", value);
        mPrefsEditor.commit();
    }

    public static String getUserName(Context ctx) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        return mPrefs.getString("name", "");
    }

    public static void setUserName(Context ctx, String value) {
        mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
        mPrefsEditor = mPrefs.edit();
        mPrefsEditor.putString("name", value);
        mPrefsEditor.commit();
    }
}

现在在AppPreference Class中设置详细信息:-

and now set details in AppPreference Class:-

AppPreference.setUserLoggedOut(this, false);
AppPreference.setUserName(this, "pass username here");

并获得这样的用户名:-

and get username like this:-

AppPreference.getUserName(this);

或检查用户是否已在初始屏幕上登录:-

or check user is logged or not on splash screen :-

if (isUserLoggedOut(StartActivity.this)) {
                    //user not logged in
                } else {
                   //User is logged in
                }

这篇关于登录和注销时如何使用SharedPreferences控制存储用户数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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