SQlite插入始终出现在相同的索引处

时间:2016-10-17 13:32:04

标签: android android-studio

我正在插入SQLite数据库。插入成功但表格显示有趣的行为。插入始终发生在第一个索引处并删除前一个记录(它显示始终重新创建表并插入记录的行为)。我想要正常插入,即将后续记录插入我的表格。

Here is the relevant code

public class FarmsDbHelper extends SQLiteOpenHelper {
    String JSON_STRING;
    private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    private final static String LOG_TAG = FarmsDbHelper.class.getSimpleName();

    // Database name
    private final static String DB_NAME = FarmsContract.DATABASE_NAME;

    // Database version
    private final static int DB_VERSION = 8;

    // Farmers table
    private final static String FARM_TABLE_NAME = FarmsContract.Farms.TABLE_NAME;
    private final static String FARM_ROW_ID = FarmsContract.Farms.ID;
    private final static String FARM_ROW_FARM_NAME = FarmsContract.Farms.FARM_NAME;
    private final static String FARM_ROW_SIZE_WITH_TOBACCO = FarmsContract.Farms.SIZE_WITH_TOBACCO;
    private final static String FARM_ROW_PLANTING_DATE = FarmsContract.Farms.PLANTING_DATE;
    private final static String FARM_ROW_FARMER_ID = FarmsContract.Farms.FARMER_ID;
    private final static String FARM_ROW_SEASON_ID = FarmsContract.Farms.SEASON_ID;
    private final static String FARM_ROW_IS_SYNCED = FarmsContract.Farms.IS_SYNCED;
    private final static String FARM_ROW_UPDATED_AT = FarmsContract.Farms.UPDATED_AT;
    private final static String FARM_ROW_DELETED = FarmsContract.Farms.DELETED;
    private final static String FARM_ROW_CREATION_DATE = FarmsContract.Farms.CREATION_DATE;


    // SQL statement to create the Version table
    private final static String FARM_TABLE_CREATE =
            "CREATE TABLE " +
                    FARM_TABLE_NAME + " (" +
                    FARM_ROW_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
                    FARM_ROW_FARM_NAME + " TEXT NULL, " +
                    FARM_ROW_SIZE_WITH_TOBACCO + " TEXT NULL, " +
                    FARM_ROW_PLANTING_DATE + " TEXT NULL, " +
                    FARM_ROW_FARMER_ID + " TEXT NULL, " +
                    FARM_ROW_SEASON_ID + " TEXT NULL, " +
                    FARM_ROW_IS_SYNCED + " TEXT NULL, " +
                    FARM_ROW_UPDATED_AT + " TEXT NULL, " +
                    FARM_ROW_DELETED + " TEXT NULL, " +
                    FARM_ROW_CREATION_DATE + " TEXT NULL" + ");";

    public FarmsDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Create Version table
        db.execSQL(FARM_TABLE_CREATE);
        Log.i(LOG_TAG, "Creating table with query: " + FARM_TABLE_CREATE);
        //create an async task here for reading from the remote server on database Farms Contract creation
        new RetrieveFarmsTask().execute();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + FARM_TABLE_NAME);
        onCreate(db);

    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void insertFarms(FarmsBean farmsBean) {

        Log.i(LOG_TAG, "Added a farm - " + farmsBean.toString());

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

        // Create ContentValues to add data
        ContentValues contentValues = new ContentValues();
        contentValues.put(FARM_ROW_ID, farmsBean.getId());
        contentValues.put(FARM_ROW_FARM_NAME, farmsBean.getFarmName());
        contentValues.put(FARM_ROW_SIZE_WITH_TOBACCO, farmsBean.getSizeWithTobacco());
        contentValues.put(FARM_ROW_PLANTING_DATE, farmsBean.getPlantingDate().toString());
        contentValues.put(FARM_ROW_FARMER_ID, farmsBean.getFarmerId());
        contentValues.put(FARM_ROW_SEASON_ID, farmsBean.getSeasonId());
        try{
            contentValues.put(FARM_ROW_IS_SYNCED, farmsBean.isSynced());
            contentValues.put(FARM_ROW_UPDATED_AT, farmsBean.getUpdatedAt().toString());
        }
        catch (Exception ex){
            ex.getMessage();
        }
        contentValues.put(FARM_ROW_DELETED, farmsBean.isDeleted());
        contentValues.put(FARM_ROW_CREATION_DATE, farmsBean.getCreationDate().toString());

        // Insert data to table
        long farmResult = db.insert(FARM_TABLE_NAME, null, contentValues);

        // Remember to close the db
        db.close();
    }
}


Here is my contract class

package netcen.client.co.ke.SQLiteDatabase;

import android.provider.BaseColumns;

/**
 * Created by CIO on 9/27/2016.
 */
public class FarmsContract implements BaseColumns {
    public static final String DATABASE_NAME = "uap.db";

    /**
     * Define the Farms table
     */
    public static final class Farms {

        // Define table name
        public static final String TABLE_NAME = "farms";

        // Define table columns
        public static final String ID = BaseColumns._ID;
        public static final String FARM_NAME = "farm_name";
        public static final String SIZE_WITH_TOBACCO = "size_with_tobacco";
        public static final String PLANTING_DATE = "planting_date";
        public static final String FARMER_ID = "farmer_id";
        public static final String SEASON_ID = "season_id";
        public static final String IS_SYNCED = "is_synced";
        public static final String UPDATED_AT = "updated_at";
        public static final String DELETED = "deleted";
        public static final String CREATION_DATE = "creation_date";

        // Define projection for customer table
        public static final String[] PROJECTION = new String[]{
                /*0*/ FarmsContract.Farms.ID,
                /*1*/ FarmsContract.Farms.FARM_NAME,
                /*2*/ FarmsContract.Farms.SIZE_WITH_TOBACCO,
                /*3*/ FarmsContract.Farms.PLANTING_DATE,
                /*4*/ FarmsContract.Farms.FARMER_ID,
                /*5*/ FarmsContract.Farms.SEASON_ID,
                /*6*/ FarmsContract.Farms.IS_SYNCED,
                /*7*/ FarmsContract.Farms.UPDATED_AT,
                /*8*/ FarmsContract.Farms.DELETED,
                /*9*/ FarmsContract.Farms.CREATION_DATE
        };
    }
}


Here's where I call the insertion method

            FarmsBean farmsBean = new FarmsBean();
            farm_id = new IdGenerator().generatePin();
            farmsBean.setId(farm_id);
            farmsBean.setFarmName(captured_farmName);
            farmsBean.setSizeWithTobacco(parseInt(captured_farmSize));
            try {
                       farmsBean.setPlantingDate(dateFormatter.parse(captured_date));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            farmsBean.setFarmerId(parseInt(cur_farmer_id));
            farmsBean.setSeasonId(parseInt(cur_season_id));
            farmsBean.setDeleted(false);
            farmsBean.setCreationDate(new Date());


            if(farmsBean!=null){
                farmsDbHelper.insertFarms(farmsBean);
            }

2 个答案:

答案 0 :(得分:1)

这是因为您也设置了FARM_ROW_ID。插入新记录时不应设置此值。让它为每次插入自动递增

答案 1 :(得分:1)

Opiatefuchs是正确答案的一部分谢谢。创建表,如果不是存在。每次我使用this.getWritableDatabase()来检索SQLiteDatabase实例时,都会重新创建表。再次感谢您的帮助。 -

从此链接https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html#getWritableDatabase%28%29

getWritableDatabase

在API级别1中添加 SQLiteDatabase getWritableDatabase() 创建和/或打开将用于读写的数据库。第一次调用它时,将打开数据库并调用onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase,int,int)和/或onOpen(SQLiteDatabase)。

每当我调用getWritableDatabase()时,我都在调用onUpgrade,而onUpgrade又会丢弃表。评论丢弃表行是解决方案。