SharedPreferences,以避免首次登录后登录屏幕

时间:2016-05-21 11:39:04

标签: android sharedpreferences autologin

我正在尝试使用SharedPreferences跳过登录活动:如果登录已经完成,则SharedPreferences将存储用户名,登录将在不通过登录活动的情况下第二次进行。

CallbackManager mcallbackManager;
private SharedPreferences mPreferences;
private String your_user_name;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mPreferences = getSharedPreferences("User", MODE_PRIVATE);
    SharedPreferences.Editor editor = mPreferences.edit();
    editor.putString("username", your_user_name);
    editor.commit();

    if (mPreferences.contains("username")) {
        Intent intent = new Intent(MainActivity.this, getMyLocation.class);
        startActivity(intent);
    }else {

        FacebookSdk.sdkInitialize(this.getApplicationContext());
        setContentView(R.layout.activity_main);

        mcallbackManager = CallbackManager.Factory.create();


        LoginManager.getInstance().registerCallback(mcallbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        Intent intent = new Intent(MainActivity.this, getMyLocation.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onCancel() {

                    }

                    @Override
                    public void onError(FacebookException exception) {
                        // App code
                    }
                });

        }
}

我使用了上面的代码,但它似乎没有按预期工作。
运行时应用程序没有崩溃,并且logcat中没有显示任何内容。

我不知道我犯了什么错误。

1 个答案:

答案 0 :(得分:1)

不要将字符串与用户名进行比较,只需设置一个布尔值

登录成功结果使该值为true。

sharePrefObje.putBoolean("isLoginKey",true);
你的启动画面上的

就像这样检查

 if (getSharedPreferences("PREFERENCENAME",0).getBoolean("isLoginKey",false)){
                Intent i = new Intent(SplashActivity.this, MainActivity.class);
                startActivity(i);
                finish();
            }else{
                Intent i = new Intent(SplashActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
            }
相关问题