Question:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.predmet_zapis);
dbHelper = new DBHelper(this);
ed1 = (EditText) findViewById(R.id.et_predmet);
bt1 = (Button) findViewById(R.id.but1);
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bd = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
String chisl1 = ed1.getText().toString();
cv.put("chisl", chisl1);
long rowID = bd.insert("mypoints", null, cv);
Log.d("LOG_TAG", "row inserted, ID = " + rowID);
dbHelper.close();
}
});
}
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
// конструктор суперкласса
super(context, "myDB", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// создаем таблицу с полями
Log.d("123","cоздана БД");
db.execSQL("create table mypoints ("
+ "id integer primary key autoincrement,"
+ "chisl text"+");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
I'm trying to create a database, but it's not being created. Writes "no such table: mypoints".
I deleted the application from the phone, reinstalled it – it worked, but after I decided to change the name of the table, it stopped working with the same error, why is that?
Answer:
onCreate
is called when there is no database. When updating the application, the database already exists and onCreate
is not called, therefore a new table is not created.
If you decide to change the structure of the database, then you need to increase the database version number in the parent constructor call:
super(context, "myDB", null, 2);
And add logic to the onUpgrade
function: what to do to bring the old database to the new structure:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion < 2) {
db.execSQL("alter table mytable rename to mypoints;");
}
}