【问题标题】:How to prevent duplicate rows when I run android program with sqlite使用sqlite运行android程序时如何防止重复行
【发布时间】:2017-01-14 13:46:18
【问题描述】:

您好,我正在为这两个问题苦苦挣扎: i) 我为我的 android 应用程序创建了 sqlite 数据库。并通过 Main Activity 添加行。现在,每当我运行我的程序时,每次都会在数据库中添加相同的行。如何确保只使用所有这些行创建一次数据库。 ii)我将 id(int 类型)设为主键并使其自动递增。我不希望主 ID 自动递增,并且可以为每一行手动设置。我该怎么做?

1. All database related functions have been in this code:
public class DataBaseHandlerActivity extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "shopsManager";

    // Shop table name
    private static final String TABLE_SHOPS = "shops";

    // Shop Table Columns names
    private static final String KEY_ID = "shopid";
    private static final String KEY_NAME = "shopname";
    private static final String KEY_ADDRESS = "shopaddress";
    private static final String KEY_CAT1="category1";
    private static final String KEY_CAT2="category2";
    private static final String KEY_CAT3="category3";
    private static final String KEY_CAT4="category4";
    private static final String KEY_IMAGE="shopimage";

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


    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_SHOPS_TABLE="CREATE TABLE "+TABLE_SHOPS+"("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_NAME+" TEXT,"+
                KEY_IMAGE+" TEXT,"+
                KEY_ADDRESS+" TEXT,"+KEY_CAT1+" TEXT,"+KEY_CAT2+" TEXT,"+KEY_CAT3+" TEXT,"+KEY_CAT4+" TEXT"+
                ")";
        db.execSQL(CREATE_SHOPS_TABLE);

    }

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

        //CREATE TABLE AGAIN
        onCreate(db);


    }


    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    //Add a new shop row
    void addShop(Shop shop){
        SQLiteDatabase db=this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME,shop.getShopName());
        values.put(KEY_IMAGE,shop.getShopImage());
        values.put(KEY_ADDRESS,shop.getShopAddress());
        values.put(KEY_CAT1,shop.getShopCat1());
        values.put(KEY_CAT2,shop.getShopCat2());
        values.put(KEY_CAT3,shop.getShopCat3());
        values.put(KEY_CAT4,shop.getShopCat4());

        //Inserting row
        db.insert(TABLE_SHOPS,null,values);
        db.close(); //Close db connection
    }

    //Get a shop items corresponding to a primary key

    Shop getShop(int id){
        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.query(TABLE_SHOPS,new String[]{KEY_ID,KEY_NAME,KEY_IMAGE,KEY_ADDRESS,KEY_CAT1,KEY_CAT2,KEY_CAT3,KEY_CAT4},
                KEY_ID +"=?",new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
       Shop shop = new Shop(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5),
       cursor.getString(6),cursor.getString(7));
        // return shop
        return shop;
    }

    // Getting All Shops
    public List<Shop> getAllShops() {
        List<Shop> shopList = new ArrayList<Shop>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_SHOPS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Shop shop = new Shop();
                shop.setShopId(Integer.parseInt(cursor.getString(0)));
                shop.setShopName(cursor.getString(1));
                shop.setShopImage(cursor.getString(2));
                shop.setShopAddress(cursor.getString(3));
                shop.setShopCat1(cursor.getString(4));
                shop.setShopCat2(cursor.getString(5));
                shop.setShopCat3(cursor.getString(6));
                shop.setShopCat4(cursor.getString(7));
                // Adding contact to list
                shopList.add(shop);
            } while (cursor.moveToNext());
        }

        // return shop list
        return shopList;
    }

    // Updating single shop
    public int updateShop(Shop shop) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME,shop.getShopName());
        values.put(KEY_IMAGE,shop.getShopImage());
        values.put(KEY_ADDRESS,shop.getShopAddress());
        values.put(KEY_CAT1,shop.getShopCat1());
        values.put(KEY_CAT2,shop.getShopCat2());
        values.put(KEY_CAT3,shop.getShopCat3());
        values.put(KEY_CAT4,shop.getShopCat4());

        // updating row
        return db.update(TABLE_SHOPS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(shop.getShopId()) });
    }

    // Deleting single shop
    public void deleteShop(Shop shop) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_SHOPS, KEY_ID + " = ?",
                new String[] { String.valueOf(shop.getShopId()) });
        db.close();
    }


    // Getting shops Count
    public int getShopsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_SHOPS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        int count=cursor.getCount();
        cursor.close();
        db.close() ;
        // return count
        return count;
    }


}

2。我传递数据以创建表的主要活动:

package com.trillbit.databaseactivity;

import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import java.util.List;

public class MainActivity extends AppCompatActivity {


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

        DataBaseHandlerActivity db=new DataBaseHandlerActivity(this);
/**
 * CRUD Operations
 * */
        // Inserting Shops
        Log.d("Insert: ", "Inserting ..");
        db.addShop(new Shop("Shoppers Stop","shopperstop","1st Floor,Forum Mall","Fashion","Clothes","Home","Shoes"));
        db.addShop(new Shop("LifeStyle", "lifestyle", "2nd Floor, Forum Mall", "Fashion", "Clothes","Home", "Mobile"));
        db.addShop(new Shop("Ezone", "ezone","3rd Floor, Forum Mall","Mobile","Electronics","Apppliances","Home"));
        db.addShop(new Shop("Dominos", "dominos","1st Floor,Forum Mall","Food","Pizza","Cake","Pastery"));

        // Reading all shops
        Log.d("Reading: ", "Reading all shops..");
        List<Shop> shops = db.getAllShops();
        for (Shop shop : shops) {
            String log = "Id: " + shop.getShopId() + " ,Name: " + shop.getShopName() + " ,Image: " + shop.getShopImage()
                    + ",Address: " + shop.getShopAddress() + ",Categort1: " + shop.getShopCat1() + ", Category2: " + shop.getShopCat2()
                    + ",Category3: " + shop.getShopCat3() + ",Catgeory4: " + shop.getShopCat4();
            // Writing Shops to log
            Log.d("Name: ", log);
        }


    }
}

3.logcat中的输出:

D/Name:: Id: 5 ,Name: Shoppers Stop ,Image: shopperstop,Address: 1st Floor,Forunm Mall,Categort1: Fashion, Category2: Clothes,Category3: Home,Catgeory4: Shoes
01-14 16:07:49.687 7993-7993/com.trillbit.databaseactivity D/Name:: Id: 6 ,Name: LifeStyle ,Image: lifestyle,Address: 2nd Floor, Forum Mall,Categort1: Fashion, Category2: Clothes,Category3: Home,Catgeory4: Mobile
01-14 16:07:49.687 7993-7993/com.trillbit.databaseactivity D/Name:: Id: 7 ,Name: Ezone ,Image: ezone,Address: 3rd Floor, Forum Mall,Categort1: Mobile, Category2: Electronics,Category3: Apppliances,Catgeory4: Home
01-14 16:07:49.687 7993-7993/com.trillbit.databaseactivity D/Name:: Id: 8 ,Name: Dominos ,Image: dominos,Address: 1st Floor,Forum Mall,Categort1: Food, Category2: Pizza,Category3: Cake,Catgeory4: Pastery
01-14 16:07:49.687 7993-7993/com.trillbit.databaseactivity D/Name:: Id: 9 ,Name: Shoppers Stop ,Image: shopperstop,Address: 1st Floor,Forum Mall,Categort1: Fashion, Category2: Clothes,Category3: Home,Catgeory4: Shoes
01-14 16:07:49.687 7993-7993/com.trillbit.databaseactivity D/Name:: Id: 10 ,Name: LifeStyle ,Image: lifestyle,Address: 2nd Floor, Forum Mall,Categort1: Fashion, Category2: Clothes,Category3: Home,Catgeory4: Mobile
01-14 16:07:49.687 7993-7993/com.trillbit.databaseactivity D/Name:: Id: 11 ,Name: Ezone ,Image: ezone,Address: 3rd Floor, Forum Mall,Categort1: Mobile, Category2: Electronics,Category3: Apppliances,Catgeory4: Home
01-14 16:07:49.687 7993-7993/com.trillbit.databaseactivity D/Name:: Id: 12 ,Name: Dominos ,Image: dominos,Address: 1st Floor,Forum Mall,Categort1: Food, Category2: Pizza,Category3: Cake,Catgeory4: Pastery

【问题讨论】:

标签: java android database sqlite


【解决方案1】:

您每次创建 Activity 时都会添加这些行。

使用 SharedPreferences 标记一个布尔值,表明您的应用已启动一次

【讨论】:

  • 感谢您的回复..你能告诉我如何做到这一点以及我将把它放在我的主要活动中的什么地方
【解决方案2】:

在数据库表定义中创建一个 UNIQUE CONSTRAINT。

它会自动防止重复条目。

代替

插入 ...

插入或忽略...

这意味着如果您违反约束,SQLite 不会返回错误代码,而是返回 SQLITE_OK,就好像命令成功一样。

【讨论】:

  • 这是一个解决方案,但我认为您误解了问题
【解决方案3】:

为了其他人的利益,我正在写我如何使用 cricket-007 建议的共享偏好来解决问题。在主活动开始时,在应用程序安装并首次运行时创建数据库。

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if(!prefs.getBoolean("firstTime", false)) {
            // run your one time code
            // Inserting Shops

            Log.d("Insert: ", "Inserting ..");
            db.addShop(new Shop("01","Shoppers Stop","shopperstop","1st Floor,Forum Mall","Fashion","Clothes","Home","Shoes"));
            db.addShop(new Shop("02","LifeStyle", "lifestyle", "2nd Floor, Forum Mall", "Fashion", "Clothes","Home", "Mobile"));
            db.addShop(new Shop("03","Ezone", "ezone","3rd Floor, Forum Mall","Mobile","Electronics","Apppliances","Home"));
            db.addShop(new Shop("04","Dominos", "dominos","1st Floor,Forum Mall","Food","Pizza","Cake","Pastery"));
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("firstTime", true);
            editor.commit();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2021-07-23
    • 2018-11-11
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    相关资源
    最近更新 更多