尝试添加第二个表时应用程序崩溃

时间:2013-09-13 23:20:28

标签: java android

好的,我现在真的很困惑。我正在尝试为我的程序添加一个新表,但每当我崩溃时,特别是在onCreate方法上崩溃。我无法为我的爱找出原因。有什么建议吗?

这也是我遇到的错误,但我无法在任何地方找到categories.db

引起:android.database.sqlite.SQLiteException:没有这样的表:categories.db(代码1):,同时编译:SELECT * FROM categories.db

private final static int DB_VERSION = 2;

public static String TABLE_NAME = "players";
public static String DB_NAME = "playerslist.db";
public static String SCORE = "score";
public static String ID = "_id";
public static String PLAYER_NAME = "name";

public static String CATEGORY_TABLE_NAME = "categories";
public static String CATEGORY_NAME = "category_name";
public static String CATEGORY_VALUE = "category_value";
public static String CATEGORY_ID = "category_id";
public static String CATEGORY_PLAYER_ID = "category_player_id";

public static String CREATE_PLAYER_TABLE = "CREATE TABLE "+TABLE_NAME+" ("+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+PLAYER_NAME+" TEXT, "+
        SCORE+" TEXT)";
public static String CREATE_CATEGORY_TABLE = "CREATE TABLE "+CATEGORY_TABLE_NAME+"("+CATEGORY_ID+" INTEGER" +
        "PRIMARY KEY AUTOINCREMENT, "+CATEGORY_NAME+" TEXT, "+CATEGORY_VALUE+" INTEGER, "
        +CATEGORY_PLAYER_ID+" INTEGER)";

public SQLHelp(Context context) {
    super(context, DB_NAME, null, 2);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_PLAYER_TABLE);
    db.execSQL(CREATE_CATEGORY_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    for(int i = oldVersion; i < newVersion; i++){
        switch(i){
            case 1:
                db.execSQL(CREATE_CATEGORY_TABLE);
            break;
        }
    }
}

3 个答案:

答案 0 :(得分:0)

更改您的CREATE TABLE字符串以包含IF NOT EXISTS as,
 CREATE TABLE IF NOT EXISTS Table_name(Columns)

答案 1 :(得分:0)

从设备或模拟器中删除您的应用程序,然后再次安装/运行,它应该可以正常工作。

我遇到了同样的问题,我简单地从设备中删除应用程序并且它有效。

答案 2 :(得分:0)

试试这个..

在创建第二个表时,您有“INTEGER”+“PRIMARY KEY AUTOINCREMENT”..

我把它做成了一个。

public static String CREATE_CATEGORY_TABLE = "CREATE TABLE "+CATEGORY_TABLE_NAME+"("+CATEGORY_ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, "+CATEGORY_NAME+" TEXT, "+CATEGORY_VALUE+" INTEGER, "
    +CATEGORY_PLAYER_ID+" INTEGER)";

你应该调用SQLiteOpenHelper

private static class DatabaseHelper extends SQLiteOpenHelper{
    DatabaseHelper(Context context){
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db){
          db.execSQL(CREATE_PLAYER_TABLE);
          db.execSQL(CREATE_CATEGORY_TABLE);
    }
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2{
          db.execSQL("DROP TABLE IF EXISTS " + CREATE_PLAYER_TABLE);
          db.execSQL("DROP TABLE IF EXISTS " + CREATE_CATEGORY_TABLE);
          onCreate(db);
    }