简体   繁体   English

Android Sharedpreference 检查用户是否已经登录

[英]Android Sharedpreference Check if the user already logged in or not

I want to check if the user is logged in or not by checking if Their ID is null or not.我想通过检查他们的 ID 是否为null来检查用户是否已登录。 if the ID is null then start loginActivity , if not then carry on.如果 ID 是null则启动loginActivity ,否则继续。

I make a separate class for my sharedpreference and have imported it, declared it.我为我的 sharedpreference 制作了一个单独的 class 并导入了它,声明了它。 however the program returned Nullpointer Error when I run it.但是,当我运行它时,程序返回了 Nullpointer 错误。 My intention was exactly to check whether the string id is null or not.我的意图是检查字符串id是否为 null。

FYI: at the moment, there is no user logged in, so the App should run the LoginActivity becauase getMyID() should return null and therefore run the condition仅供参考:目前,没有用户登录,所以应用程序应该运行 LoginActivity 因为 getMyID() 应该返回 null 并因此运行条件

Please tell me where did I make mistake and how should I do it instead请告诉我我在哪里犯了错误,我应该怎么做

my setter and getter for ID in sharedpreference:我在 sharedpreference 中的 ID 设置器和获取器:

public void setMyID(String myID) {
    editor.putString(MYUSERID, myID);
    editor.commit();
}

public String getMyID() {
    return pref_global.getString(MYUSERID, null);
}

This is my mainactivity file这是我的主要活动文件

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Selamat Datang");

myContext = this;
mAuth = FirebaseAuth.getInstance();
mFirebaseAnalytics = FirebaseAnalytics.getInstance(myContext);

checkLoginState();

}

public void checkLoginState(){
    if(prefManager.getMyID() == null ){
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
}

I think default value parameter of getString(MYUSERID, "default value") is non null type, you just need to set it to another non null string.我认为getString(MYUSERID, "default value")的默认值参数是非 null 类型,您只需将其设置为另一个非 null 字符串。 Hope it help.希望它有所帮助。

When pulling data from sharedPreferences, you can try entering "" instead of entering the default value as null.从 sharedPreferences 中拉取数据时,可以尝试输入“”,而不是输入默认值 null。 I am sharing the sample code below;我在下面分享示例代码;

public String getMyID() {
   return pref_global.getString(MYUSERID, "");
}


public void checkLoginState(){
if(prefManager.getMyID() == ""){
    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    finish();
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM