7

我的 Android 应用程序需要用户创建一个帐户才能使用该应用程序。帐户信息存储在 SQLite 数据库中。当应用程序启动时,我检查用户是否有帐户,如果没有,我会为用户显示注册活动。

现在我收到用户的报告,即使他们已经创建了一个帐户,他们有时也会参加注册活动。当他们关闭应用程序并再次重新打开它时,就会发生这种情况。

这是我正在使用的代码,我需要弄清楚问题可能是什么:

//MyApplication.java
public class MyApplication extends Application {
    private DataBaseUtility dbu;
    public boolean hasAccount;  

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

        //Init sqlite database
        this.dbu = new DataBaseUtility(this);

        //This loads the account data from the database and returns true if the user has already created an account
        this.hasAccount = loadAccount();
    }

    public boolean loadAccount() {
        boolean loadedData = false;

        String query = "SELECT data FROM tblaccount WHERE tblaccount.deleted=0";
        Cursor cursor = this.dbu.getCursor(query);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                loadedData = true;
            }
            cursor.close();
        }

        return loadedData;
    }
}

//MainActivity.java
public class MainActivity extends TabActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        MyApplication application = (MyApplication)getApplication();
        if (!application.hasAccount) {
            //Take the user to the sign up activity
        }
}

我的想法是,也许有时会MainActivity.onCreate()MyApplication.onCreate(). 可以这样吗?

4

1 回答 1

3

application'sonCreate中,您正在检查用户是否有帐户并设置布尔值。

如果用户通过' 布尔值有帐户,则您正在检查MainActivity' s。onCreateapplication

applicationonCreate()执行之前MainActivityonCreate()总是如此!不可能出现不同的执行路径,因为application'sonCreate()没有 aRunnable它是 100% 保证的。

请确保您DataBaseUtility没有任何 Runnables。

无论如何,仍然有几种方法可以重现错误!我现在不会说这些,但是当你看到它们时你可以知道它们:

解决方案

MainActivity注册成功忘记更新application.hasAccount了~

public class MainActivity extends TabActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        MyApplication application = (MyApplication)getApplication();
        if (!application.hasAccount) {
            //Take the user to the sign up activity
            //if(successful) application.hasAccount = true
        }
}

避免数据库异常

我用这个:

备注为数据库使用更强大的持久状态保存会更好 - 即SharedPreferences

boolean isOpened = false;
//When I need to open
if(!isOpened){
    //open
    isOpened = true;
}
//When I need to close
if(isOpened){
    //close
    isOpened = false;
}

onDestroy() {  //every onDestroy
    if(isOpened){
        //close
    }
}
于 2011-08-03T08:57:42.617 回答