如何在Android上运行代码在Android中打开?

Mar*_*tin 7 android oncreate

我的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
        }
}
Run Code Online (Sandbox Code Playgroud)

我的想法是,有时可能会MainActivity.onCreate()在之前运行MyApplication.onCreate().可以吗?

She*_*tib 4

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

MainActivity您正在通过' s 布尔值检查onCreate用户是否有帐户application

applicationonCreate()之前执行总是MainActivity这样!不可能出现不同的执行路径,并且由于's没有 's ,所以它是 100% 的保证。onCreate()applicationonCreate()Runnable

请确保您DataBaseUtility没有任何 Runnables。

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

解决方案

MainActivityapplication.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
        }
}
Run Code Online (Sandbox Code Playgroud)

避免数据库异常

我用这个:

REMARK数据库使用更强大的持久状态保存会更好 -ieSharedPreferences

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
    }
}
Run Code Online (Sandbox Code Playgroud)