简体   繁体   中英

Create a table with add new column button in kotlin

I want to create a table in which i want to add button, whenever i click on that a new column should be added in the existing table with new column name in kotlin. Please help me if any body has any suggestions.

I have not tried it yet, but I know that you can do this using Migration in Room. This is a sample code:

static final Migration MIGRATION_1_2 = new Migration(2, 3) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        try {

            database.execSQL("ALTER TABLE ImageData "
                    + "ADD COLUMN folderPosition INTEGER default null");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
};

Below is the complete class:

public class DatabaseClient {

private Context mCtx;
private static DatabaseClient mInstance;

//our app database object
private AppDatabase appDatabase;

private DatabaseClient(Context mCtx) {
    this.mCtx = mCtx;

    //creating the app database with Room database builder
    //MyToDos is the name of the database

    //appDatabase = Room.databaseBuilder(mCtx, AppDatabase.class, "dbname.sqlite").addMigrations(MIGRATION_1_2).build();
    appDatabase = Room.databaseBuilder(mCtx, AppDatabase.class, "dbname.sqlite").build();
}


/*static final Migration MIGRATION_1_2 = new Migration(2, 3) {
    @Override
    public void migrate(SupportSQLiteDatabase database) {
        try {

            database.execSQL("ALTER TABLE ImageData "
                    + "ADD COLUMN folderPosition INTEGER default null");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
};*/

public static synchronized DatabaseClient getInstance(Context mCtx) {
    if (mInstance == null) {
        mInstance = new DatabaseClient(mCtx);
    }
    return mInstance;
}

public AppDatabase getAppDatabase() {
    return appDatabase;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM