user5211136
user5211136

Reputation:

can i dynamically add new column to sqlite table by calling a method from another class?

I have a table in database, each record of this table needs to store multiple Strings, i dont know how many Strings because its decided at runtime.

I want to add image uri's in database table dynamically, user dynamically add images in my app as many as he want so i need to save uri of them, what is the right approach to do it?

I am trying something like this by follow this Insert new column into table in sqlite ?

String ColumnName=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/" + "image1.jpg");

addNewColumn(ColumnName);

i used below method for this (not worked):-

First i am adding new column in table :-

public Cursor addColumn(String name){
    db=dbhelper.getWritableDatabase();
    return  db.rawQuery("alter table info add column " + name + " text", null);
}

Then insert uri into this

public Boolean setUri(String columnName,String uri) {
    ContentValues cv= new ContentValues();
    cv.put(columnName,uri);
    SQLiteDatabase db =dbhelper.getWritableDatabase();
    long id=db.insert("info",null,cv);
    if(id>-1)
        return true;
    else
        return false;
}

is the above approach correct?

also i searched and fine below code :-

private static final String ALTER = "ALTER TABLE user_table ADD user_street1 TEXT";

     @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        db.execSQL(ALTER);
    }

can i call onUpgrade() method dynamically and add new column or any other way to do it..?

Thanks in advance :)

Upvotes: 3

Views: 2504

Answers (1)

Karakuri
Karakuri

Reputation: 38605

It's very bad to have an arbitrary number of columns in a table. You should instead use a second table with a foreign key referencing the ID of a row in the first table.

table user
_id     username    ...
------------------------
1       abc
2       xyz

table photoInfo
userId      photoUri
-------------------------------
1           /path/to/image1.jpg
1           /path/to/image2.jpg
2           /path/to/image3.jpg
1           /path/to/image4.jpg

To show photos for a particular user, use a JOIN.

Upvotes: 1

Related Questions