【问题标题】:Session is returning null exception on DB upgrade会话在数据库升级时返回空异常
【发布时间】:2014-04-20 23:55:54
【问题描述】:

我是 android 的新手。我在会话中保持登录用户的数据,并在应用程序启动时将它们从登录屏幕重定向到 MainActivity。我在登录活动的 onCreate 方法中使用了类似的东西:

if(session.isLoggedIn()) {
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        }

用户保持登录状态,直到单击注销并运行session.logoutUser();,它的工作方式如下:

public void logoutUser(){
    // Clearing all data from Shared Preferences
    editor.clear();
    editor.commit();

    // After logout redirect user to Login Activity
    Intent i = new Intent(_context, LoginActivity.class);
    // Closing all the Activities
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Add new Flag to start new Activity
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    // Staring Login Activity
    _context.startActivity(i);
}

问题是,当我在 MySQLiteHelper 类中进行数据库升级时,session.isLoggedIn() 仍然返回 true。所以 LoginActivity 一直在尝试重定向用户,并且应用程序在 MainActivity 中给出了nullpointerexception

在重定向到MainActivity之前,我需要在LoginActivity中检查数据库是否升级,或者在onUpgrade()方法中运行session.logoutUser()。感谢您的帮助。

【问题讨论】:

    标签: android database sqlite session


    【解决方案1】:

    我在 MySQLiteHelper.java 类中定义了一个公共布尔变量,例如

    public boolean db_upgrade = false;

    并更改了 onUpgrade() 方法,如:

    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older tables if existed
        db.execSQL("DROP TABLE IF EXISTS Players");
        db.execSQL("DROP TABLE IF EXISTS Foods");
        // create fresh tables
        this.onCreate(db);
        if(oldVersion != newVersion) {
            db_upgrade = true;
        }
    }
    

    所以我可以通过对 LoginActivity 稍作更改来检查数据库是否升级:

        if (!MySQLiteHelper.db_upgrade) { // if db is not upgraded
            if (session.isLoggedIn()) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
                finish();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2017-06-13
      • 1970-01-01
      • 2018-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      相关资源
      最近更新 更多