为什么在重命名字段DB_NAME或DB_TABLE时程序会崩溃?

时间:2014-09-16 11:51:44

标签: java android sqlite adapter rename

请帮忙!

public class DB {


 private static final String DB_NAME = "mydb";
  private static final int DB_VERSION = 1;
  private static final String DB_TABLE = "mytab";

  public static final String COLUMN_ID = "_id";
  public static final String COLUMN_IMG = "img";
  public static final String COLUMN_TXT = "txt";

  private static final String DB_CREATE = 
    "create table " + DB_TABLE + "(" +
      COLUMN_ID + " integer primary key autoincrement, " +
      COLUMN_IMG + " integer, " +
      COLUMN_TXT + " text" +
    ");";

  private final Context mCtx;


  private DBHelper mDBHelper;
  private SQLiteDatabase mDB;

  public DB(Context ctx) {
    mCtx = ctx;
  }

  // открыть подключение
  public void open() {
    mDBHelper = new DBHelper(mCtx, DB_NAME, null, DB_VERSION);
    mDB = mDBHelper.getWritableDatabase();
  }

  // закрыть подключение
  public void close() {
    if (mDBHelper!=null) mDBHelper.close();
  }

  // получить все данные из таблицы DB_TABLE
  public Cursor getAllData() {
    return mDB.query(DB_TABLE, null, null, null, null, null, null);
  }

  // добавить запись в DB_TABLE
  public void addRec(String txt, int img) {
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_TXT, txt);
    cv.put(COLUMN_IMG, img);
    mDB.insert(DB_TABLE, null, cv);
  }



  // класс по созданию и управлению БД
  private class DBHelper extends SQLiteOpenHelper {

    public DBHelper(Context context, String name, CursorFactory factory,
        int version) {
      super(context, name, factory, version);
    }

    // создаем и заполняем БД
    @Override
    public void onCreate(SQLiteDatabase db) {
      db.execSQL(DB_CREATE);

      ContentValues cv = new ContentValues();
      for (int i = 1; i < 5; i++) {
        cv.put(COLUMN_TXT, "sometext " + i);
        cv.put(COLUMN_IMG, R.drawable.ic_launcher);
        db.insert(DB_TABLE, null, cv);
      }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
  }
}

如果在初始化时重命名字段DB_NAME或DB_TABLE,则会出现错误。如果我不触摸名字 - 一切都很好,但我需要改变它们。试图改变模拟器 - 没有帮助。

1 个答案:

答案 0 :(得分:0)

您必须升级数据库的版本,因此在其上增加一个,如果要保存数据库的先前信息,请在onUpgrade中实现:

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
     //implement your logic of saving your infos here
}

如果您不介意清理数据库,请执行以下操作:

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS '" + DATABASE_TABLE+"'");
        onCreate(db);
    }