android最好的方法来保存设备上非常小的数据

问题描述 投票:1回答:2

在我的应用程序启动活动中,我需要在每次启动应用程序时检查三件事

  1. 应用版本
  2. 是用户登录
  3. 是用户帐户创建

我正在使用Firebase进行数据库,因此每次使用启动应用程序时我都会在Datachange上检查数据库,然后根据返回结果和案例区域将用户发送到活动,如下所示:

//check if newer version is available (Step 1)
if (appVersionMatch) {
    CheckLogin();
} else {
    //Take user to appstore for app update
}


// (Step 2)
public void CheckLogin() {
    if (userLogin) {
        CheckUserExist()
    } else {
        //Show user Login activity
    }
}


// (Step 3)
public void CheckUserExist() {
    if (user.exist()) {
        //Go To main Activity
    } else {
        //Go To Register activity
    }
}

这个流程工作正常,但总是需要一些时间来检查所有这三件事..我在想是否可以保存首次登录和帐户创建信息,所以不需要再次检查,以便用户可以去主要活动更快我尝试用以下操作,但没有按预期工作:

 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
                    editor = pref.edit();
                    boolean isLoogenIn = pref.getBoolean("userLoginCheck", false);
java android firebase
2个回答
1
投票

这是我用SharedPreferences做的方式。

首先创建一个单独的类(我用它来保存其他信息,如url,常量等)。在那里创建一个SharedPreferences

public class project_constants {
private static String PREF_NAME = "project_pref";

private static SharedPreferences getPrefs(Context context) {
    return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
}

public static boolean getUserLogin(Context context) {
    return getPrefs(context).getBoolean("login", false);
}

public static void setUserLogin(Context context, boolean input) {
    SharedPreferences.Editor editor = getPrefs(context).edit();
    editor.putBoolean("login", input);
    editor.apply();
}

现在当用户登录时,你应该使用project_constants.setuserLogin(getApplicationContext,True);

现在,当您想要检查用户是否已登录时,您可以使用project_constants.getuserLogin(getApplicationContext);,如果这是真的,则用户已登录,否则为no。


1
投票

当firebase中的数据准备就绪时,您应该首次将数据保存在SharedPreference中:

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
editor = pref.edit();
editor.putBoolean("userLoginCheck", false);
editor.commit();

然后,您可以通过以下方式获取下次的首选项值:

 boolean isLoogenIn = pref.getBoolean("userLoginCheck", true);
© www.soinside.com 2019 - 2024. All rights reserved.