简体   繁体   English

Android将新字段添加到sqlite数据库中的所有记录

[英]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). 我创建了一个使用sqlite数据库保存用户条目(名称和电话号码)的应用。 After publishing the first version of this app, I decided to release version 2 and add another field to the database (Age). 发布该应用程序的第一个版本后,我决定发布版本2,并将另一个字段添加到数据库(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. 现在,当我运行较新的版本时,它崩溃了,因为较旧的条目没有“ Age”字段,并且无法加载记录。 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. 我基本上想要的是在用户更新时运行一段代码,这将为用户已经创建的所有记录在“年龄”字段下添加值0。

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. 我使用了此链接该链接表示要使用此代码ALTER TABLE mytable ADD COLUMN mycolumn TEXT向数据库添加新列。

And I've used this link , which says that I have to remove the where clause from database.update("contacts", addContactsAge, "_id=" + id, null); 而且我使用了此链接 ,它说我必须从database.update("contacts", addContactsAge, "_id=" + id, null);删除where子句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: 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. 我已将数据库版本更改为2,但是没有任何运气。 I also tried removing the if (oldVersion == 1 && newVersion == 2) . 我还尝试删除了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. onUpgrade方法中,android自动检测到一个新版本,您要做的就是每当对db进行更改时,在DatabaseOpenHelper调用中增加该版本,完成后将旧表删除并创建一个新表。

change your db version in DatabaseConnector class 在DatabaseConnector类中更改数据库版本

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. 每当您需要在android应用中更新数据库时,都需要增加数据库版本,它将调用onUpgrade方法,您可以在其中更新数据库。

You can try this also, push app with pre-installed db. 您也可以尝试此操作,通过预装的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. 直接将资产db复制到文件夹构造函数中,并发送增量调用以获取数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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