Android上的SQLite DB重新创建记录而不是调用onUpgrade()

时间:2014-02-22 14:53:19

标签: android xml sqlite

我有一些代码,当我运行它时会向我的SQLite数据库添加三条记录,这是使用我的MySQLiteHelper类创建的。问题是,每次运行我的应用程序时,三个样本记录都会再次写入数据库,而不会替换它们的相同副本。因此,如果我运行我的应用程序10次,我的数据库中将有30条记录。

MapActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);

    MySQLiteHelper db = new MySQLiteHelper(this);

    //ADD MAP MARKERS INTO DATABASE (PHASE TWO = FROM CSV FILE)
    db.addMapMarker(new MapMarker("Accommodation", 
                                  "Cardigan Costal Cottages", 
                                  "http://www.cardigan.cc/images/farmhouse/farmhouse.jpg", 
                                  "Four star accommodation!", 
                                  "Ffrwdwenith Isaf, Felinwyny, Cardigan, SA43 1RW",   
                                  "01974 272559", 
                                  "http://www.cardigan.cc", 
                                  52.2437596, -4.0930263));

    db.addMapMarker(new MapMarker("Activity",
                                  "Fforest",
                                  "http://www.coldatnight.co.uk/images/fforestcampcomforts.jpg", 
                                  "Offers a full range of half and full day activity packages.",
                                  "1 Cambrian Quay, Cardigan, SA43 2EZ",
                                  "01239 623633",
                                  "http://www.coldatnight.co.uk",
                                  52.1348785, -4.5411973));

   db.addMapMarker(new MapMarker("Food & drink",
                                  "Naturally Scrumptious",
                                  "http://www.naturallyscrumptious.co.uk/wp/images/3290f700c749.jpg",
                                  "Delicatessen and cafe bar",
                                  "18 Market Street, Aberaeron, SA46 0AS",
                                  "01545 574733",
                                  "http://www.naturallyscrumptious.co.uk",
                                  52.2424517, -4.2599518));

SQLiteHelper.java

package uk.ac.aber.dwd.util.CeredigionTourism;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper {

    //Database Version
    private static final int DATABASE_VERSION = 2;
    //Database Name
    private static final String DATABASE_NAME = "CatalogueDB";

    //Catalogue records table name
    private static final String TABLE_RECORDS = "records";

    //Catalogue records column names
    private static final String KEY_ID = "id";
    private static final String KEY_GROUP = "category";
    private static final String KEY_NAME = "name";
    private static final String KEY_IMAGE = "image";
    private static final String KEY_DESC = "description";
    private static final String KEY_ADDR = "address";
    private static final String KEY_TELEPHONE = "telephone";
    private static final String KEY_URL = "url";
    private static final String KEY_LAT = "latitude";
    private static final String KEY_LNG = "longitude";

    //Array of Strings used to create database columns
    private static final String[] COLUMNS = {KEY_ID, KEY_GROUP, KEY_NAME, KEY_IMAGE, KEY_DESC, KEY_ADDR, 
                                             KEY_TELEPHONE, KEY_URL, KEY_LAT, KEY_LNG};

    public MySQLiteHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //SQL statement to create records (map markers) table
        String CREATE_RECORDS_TABLE ="CREATE TABLE records (id INTEGER PRIMARY KEY AUTOINCREMENT, " + 
        "category TEXT, " + 
        "name TEXT, " +
        "image TEXT, " +
        "description TEXT, " +
        "address TEXT, " +
        "telephone TEXT, " +
        "url TEXT, " +
        "latitude TEXT, " +
        "longitude TEXT" + ")";

        //Create records (map markers) table
        db.execSQL(CREATE_RECORDS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Drop older records table if existed
        db.execSQL("DROP TABLE IF EXISTS records");

        //create fresh records table
        this.onCreate(db);
    }

    public void addMapMarker(MapMarker marker){

        //1. Get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        //2. Create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_GROUP, marker.getGroup());
        values.put(KEY_NAME, marker.getName());
        values.put(KEY_IMAGE, marker.getImage());
        values.put(KEY_DESC, marker.getDescription());
        values.put(KEY_ADDR, marker.getAddress());
        values.put(KEY_TELEPHONE, marker.getTelephone());
        values.put(KEY_URL, marker.getUrl());
        values.put(KEY_LAT, marker.getLatitude());
        values.put(KEY_LNG, marker.getLongitude());

        //3. Insert
        db.insert(TABLE_RECORDS, null, values);
        db.close();
    }

    public MapMarker getMapMarker(int id){
        //1. Get reference to readable DB
        SQLiteDatabase db = this.getReadableDatabase();

        //2. Build query
        Cursor cursor =
                db.query(TABLE_RECORDS,
                        COLUMNS,
                        " id = ?",
                        new String[] {String.valueOf(id)},
                        null,
                        null,
                        null,
                        null);

        //3. If we got result get the first one
        if(cursor != null) {
            cursor.moveToFirst();
        }

        //4. Build record object, each column iterates the index value. id = 0, group = 1, etc...
        MapMarker marker = new MapMarker();
        marker.setId(Integer.parseInt(cursor.getString(0)));
        marker.setGroup(cursor.getString(1));
        marker.setName(cursor.getString(2));
        marker.setImage(cursor.getString(3));
        marker.setDescription(cursor.getString(4));
        marker.setAddress(cursor.getString(5));
        marker.setTelephone(cursor.getString(6));
        marker.setUrl(cursor.getString(7));
        marker.setLatitude(cursor.getDouble(8));
        marker.setLongitude(cursor.getDouble(9));

        //5. Return marker
        return marker;
    }

    public List<MapMarker> getAllMapMarkers() {
        List<MapMarker> markers = new ArrayList<MapMarker>();

        //1. Build the query
        String query = "SELECT * FROM " + TABLE_RECORDS;

        //2. Get reference to writable DB
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(query, null);

        //3. Go over each row, build marker and add it to list
        MapMarker marker = null;
        if (cursor.moveToFirst()){
            do {
                marker = new MapMarker();
                marker.setId(Integer.parseInt(cursor.getString(0)));
                marker.setGroup(cursor.getString(1));
                marker.setName(cursor.getString(2));
                marker.setImage(cursor.getString(3));
                marker.setDescription(cursor.getString(4));
                marker.setAddress(cursor.getString(5));
                marker.setTelephone(cursor.getString(6));
                marker.setUrl(cursor.getString(7));
                marker.setLatitude(cursor.getDouble(8));
                marker.setLongitude(cursor.getDouble(9));

                //Add marker to markers
                markers.add(marker);

            } while(cursor.moveToNext());
        }

        cursor.close();
        db.close();
        //Return markers
        return markers;
    }

    public int updateMapMarker(MapMarker marker) {
        //1. Get Reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        //2. Create ContentValues to add key "column"/value
        ContentValues values = new ContentValues();
        values.put(KEY_GROUP, marker.getGroup());
        values.put(KEY_NAME, marker.getName());
        values.put(KEY_IMAGE, marker.getImage());
        values.put(KEY_DESC, marker.getDescription());
        values.put(KEY_ADDR, marker.getAddress());
        values.put(KEY_TELEPHONE, marker.getTelephone());
        values.put(KEY_URL, marker.getUrl());
        values.put(KEY_LAT, marker.getLatitude());
        values.put(KEY_LNG, marker.getLongitude());

        //3. Updating row
        int i = db.update(TABLE_RECORDS, values, KEY_ID + " ?", new String[] {String.valueOf(marker.getId()) });

        //4. Close
        db.close();

        return i;
    }

    public void deleteMapMarker(MapMarker marker) {
        //1. Get reference to writable DB
        SQLiteDatabase db = this.getWritableDatabase();

        //2. Delete
        db.delete(TABLE_RECORDS, KEY_ID + " = ?", new String[] {String.valueOf(marker.getId()) });

        //3. Close
        db.close();


    }
}

所以我为SQLiteHelper编写了正确的(我认为!)代码,但每次我的应用程序记录都是重复而不是替换。也许有一种我没有打电话的特殊方法?

1 个答案:

答案 0 :(得分:0)

您可以检查数据库中是否已存在记录,并改为调用updateMapMarker。

您确定每次创建活动时都要创建/更新记录吗?听起来很奇怪......