简体   繁体   中英

Android adding new field to all records in an sqlite database

I've created an app that uses sqlite databases to save users' entries (name and phone number). After publishing the first version of this app, I decided to release version 2 and add another field to the database (Age). Unfortunately, people have already installed the app and have each made their own entries (Could be hundreds of entries for all I know). And now when I run the newer version, it crashes because the older entries don't have an "Age" field and cannot load the records. What I basically want is to have a piece of code run when a user updates, that will add the value 0 under the field "Age" for all the records that the user has already created.

I've used this link , which says to use this code ALTER TABLE mytable ADD COLUMN mycolumn TEXT to add a new column to the database.

And I've used this link , which says that I have to remove the where clause from database.update("contacts", addContactsAge, "_id=" + id, null); so that it updates all the records.

I've applied all these but when I launch the new version, it crashes straight away.

Here is my full updated code:

public class DatabaseConnector {

private static final String DATABASE_NAME = "UserContacts";
private SQLiteDatabase database;
private DatabaseOpenHelper databaseOpenHelper;

public DatabaseConnector(Context context) {

    databaseOpenHelper = new DatabaseOpenHelper(context, DATABASE_NAME,
            null, 2);
}

public void open() throws SQLException {

    database = databaseOpenHelper.getWritableDatabase();
}

public void close() {
    if (database != null)
        database.close();
}

public void insertContact(String name, String phone, String age) {
    ContentValues newContact = new ContentValues();
    newContact.put("name", name);
    newContact.put("phone", phone);
    newContact.put("age", age);

    open();
    database.insert("contacts", null, newContact);
    close();
}

public void updateContact(long id, String name, String phone, String age) {
    ContentValues editContact = new ContentValues();
    editContact.put("name", name);
    editContact.put("phone", phone);
    editContact.put("age", age);

    open();
    database.update("contacts", editContact, "_id=" + id, null);
    close();
}

public void setContactsAge() {
    ContentValues addContactsAge = new ContentValues();
    addContactsAge.put("age", "0");

    open();
    database.update("contacts", addContactsAge, null, null);
    close();
}

public Cursor getAllContacts() {
    return database.query("contacts",
            new String[] { "_id", "name" }, null, null, null, null,
            "name");
}

public Cursor getOneContact(long id) {
    return database.query("contacts", null, "_id=" + id, null, null, null,
            null);
}

public void deleteContact(long id) {
    open();
    database.delete("contacts", "_id=" + id, null);
    close();
}

private class DatabaseOpenHelper extends SQLiteOpenHelper {

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

    @Override
    public void onCreate(SQLiteDatabase db) {

        String createQuery = "CREATE TABLE contacts"
                + "(_id integer primary key autoincrement,"
                + "name TEXT, phone TEXT, age TEXT);";

        db.execSQL(createQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == 1 && newVersion == 2)
        database.execSQL("ALTER TABLE contacts ADD COLUMN age TEXT");
    }
}
}  

MainActivity.java:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SharedPreferences preferences = PreferenceManager
            .getDefaultSharedPreferences(MainActivity.this);
    SharedPreferences.Editor editor = preferences.edit();
    int i = preferences.getInt("numberoflaunches", 1);

    if (i < 2) {
        DatabaseConnector databaseConnector = new DatabaseConnector(MainActivity.this);
        databaseConnector.setContactsAge();
        i++;
        editor.putInt("numberoflaunches", i);
        editor.commit();
    }
}
}  

Like I said this code isn't working for me, and I don't know what the problem is. Any help would be greatly appreciated.

I've changed the database version to 2, but without any luck. I also tried removing the if (oldVersion == 1 && newVersion == 2) .

Remove the line

if (oldVersion == 1 && newVersion == 2)'

in onUpgrade method, android automatically detects a new version, all you have to do is increment the version in DatabaseOpenHelper call whenever you making changes to db, when that is done the old table is dropped and new one is created.

change your db version in DatabaseConnector class

public DatabaseConnector(Context context) {

databaseOpenHelper = new DatabaseOpenHelper(context, DATABASE_NAME,
        null, 2);

}

whenever you need to update your database in android app you need to increase your db version it will call onUpgrade method where you can update your db.

You can try this also, push app with pre-installed db. Create database with db version and save it in assets folder. Whenever app runs compare versions of assets's db & app's db. if asset's db version is higher than app's db then this means you need to update database. Directly copy asset db into folder structor and sends delta call to fetch data.

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