保持我的会话活跃Android应用程序

时间:2016-02-03 17:38:36

标签: java android

我正在创建一个Android应用,我无法弄清楚为什么我的会话不会保持活跃状态​​!

我创建了一个登录布局,当我成功获得连接时,我的userLocalStore为true!因此,当我回到此应用程序的主页并再次按下登录按钮时,我希望它只显示我的帐户详细信息。

以下是我使用的代码:

case R.id.accLogin:
    if (userLocalStore.getUserLoggedIn() == false){
        startActivity(new Intent(this, Compte.class));
    } else {
        startActivity(new Intent(this, Login.class));
    }

但它不起作用!有没有" Cookie"对于Android应用程序?

这是我的userLocalStore代码:

public class UserLocalStore {

public static final String SP_NAME ="userDetails";
SharedPreferences userLocalDatabase;

public UserLocalStore(Context context)
{
    userLocalDatabase = context.getSharedPreferences(SP_NAME, 0);
}

public void storeUserData(User user)
{
    SharedPreferences.Editor spEditor = userLocalDatabase.edit();
    spEditor.putString("name", user.name);
    spEditor.putString("surname", user.surname);
    spEditor.putString("username", user.username);
    spEditor.putString("password", user.password);
    spEditor.putInt("age", user.age);
    spEditor.commit();
}

public User getLoggedInUser() {
    String name = userLocalDatabase.getString("name", "");
    int age = userLocalDatabase.getInt("age", -1);
    String username = userLocalDatabase.getString("username", "");
    String password = userLocalDatabase.getString("password", "");
    String surname = userLocalDatabase.getString("surname", "");

    User storedUser = new User(name, age, username, password, surname);
    return storedUser;
}

public void setUserLoggedIn(boolean loggedIn)
{
    SharedPreferences.Editor spEditor = userLocalDatabase.edit();
    spEditor.putBoolean("LoggedIn", loggedIn);
    spEditor.commit();
}

public boolean getUserLoggedIn()
{
    if (userLocalDatabase.getBoolean("LoggedIn", false))
    {
        return false;
    }else
    {
        return true;
    }
}

public void clearUserData()
{
    SharedPreferences.Editor spEditor = userLocalDatabase.edit();
    spEditor.clear();
    spEditor.commit();
}

}

我刚发现错误!只需改变

public boolean getUserLoggedIn() { if (userLocalDatabase.getBoolean("LoggedIn", false)) { return false; }else { return true; } }

public boolean getUserLoggedIn()
{
    if (userLocalDatabase.getBoolean("LoggedIn", false))
    {
        return true;
    }else
    {
        return false;
    }
}

坦克寻求帮助!

1 个答案:

答案 0 :(得分:0)

是的,您可以使用SharedPreferences来模拟Cookie。您可以通过文件名创建一个可以访问整个应用程序(所有活动)的文件。

SharedPreferences prefs = getSharedPreferences("a filename", Context.MODE_PRIVATE);
// writing
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("cookie", "value");
editor.commit();
// reading
String cookie = sharedPref.getString("cookie", "defaultValue");