简体   繁体   English

如何为数据库中的相似对象执行太多的多功能操作?

[英]How can I do too many multi function for similar objects in database?

My SQLite Database has 5 columns. 我的SQLite数据库有5列。

  1. id ID
  2. words
  3. mean 意思
  4. different mean 不同的均值
  5. color 颜色

First of all , I have a Listview that it is in different activity.And I am loading datas from Main Activity with button.My purpose is ; 首先,我有一个Listview,它处于不同的活动中。并且我正在通过Button从Main Activity加载数据。 I want to add data but When I added the data , İf There is same data(İt is second column(words))in listview. 我想添加数据,但是当我添加数据时,列表视图中有相同的数据(İt是第二列(单词))。 Data delete itself and other same data goes to listview"s top and change its color to different color. 数据删除本身,其他相同的数据到达列表视图的顶部,并将其颜色更改为其他颜色。

This how to see : from 1. anything (white color) 2. something (white color) 3. different (white color) 4. something (white color) 这怎么看:从1.任何东西(白色)2.东西(白色)3.不同(白色)4.东西(白色)

to

  1. something (red color) 东西(红色)
  2. anything (white color) 任何东西(白色)
  3. different (white color) 不同(白色)

My database : 我的数据库:

class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";


private static final String TABLE_NAME = "kartlarim";
private static final String COL1 = "ID";
private static final String COL2 = "name";
private static final String COL3 = "anlam";
private static final String COL4 = "akli_göz";
private static final String COL5 = "boya";

public DatabaseHelper(Context context) {
    super(context, TABLE_NAME, null, 1);
}


@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +  COL2 + " TEXT,"+
            COL3 + " TEXT,"+ COL4  + " TEXT," +COL5 + " TEXT)";
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
    onCreate(db);
}
public boolean addData(String item , String number  , String anlam) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, item);
    contentValues.put(COL3 , number);
    contentValues.put(COL4, anlam);
    contentValues.put(COL5 ,"#419FEE");

    Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);

    long result = db.insert(TABLE_NAME, null, contentValues);

    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

Database update data : 数据库更新数据:

public String update(String table, ContentValues data, String where, String[] whereArgs) {
    SQLiteDatabase db = this.getWritableDatabase();
    //  String where = "id=?";
    //    String[] whereArgs = new String[] {String.valueOf(id)};
    try {
        long returnId = db.update(table, data, where, whereArgs);
        if (returnId > 0) {
            db.close();
            return "Success";
        } else {
            db.close();
            return "fail";
        }
    } catch (Exception e) {
        String error = e.getMessage().toString();
        db.close();
        return error;
    }
}

Delete row : 删除行:

  public void deleteAllName(int id, String name ,String anlam, String akli){
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                + COL1 + " = '" + id   + "' AND "
                + COL2 + " = '" + name + "' AND "
                + COL3 + " = '"+ anlam +"' AND "
                + COL4 + " = '"+ akli + "'";
        Log.d(TAG, "deleteName: query: " + query);
        Log.d(TAG, "deleteName: Deleting " + name + " from database.");
        db.execSQL(query);
    }

My arrays : 我的数组:

  Cursor data = mDatabase.getData();
    while (data.moveToNext()){


        kelimeler_id_array.add(data.getString(0));
        kelimeler_array.add(data.getString(1)) ;
        akli_göz_array.add(data.getString(2));
       kelimelerin_anlamı_array.add(data.getString(3));
        boya_array.add(data.getString(4));

    }

Button statement : 按钮声明:

       String user_words_unknown =  user_unknown_words_edittext.getText().toString();

// simply add to database.
            if (!kelimeler_array.contains(user_words_unknown)){


                mDatabase.addData(user_words_unknown, "","");
            }


    //Here , is my problem
          if (kelimeler_array.contains(user_words_unknown)) {

              mDatabase.addData(user_words_unknown, "","");


          }

If I understand your question correctly your issue is that you do not want to insert(add) a new row if the value in COL2 already exists. 如果我正确理解了您的问题,那么您的问题是,如果COL2的值已经存在,则您不想插入(添加)新行。 That is you effectively want COL2 to be unique . 那就是您实际上希望COL2唯一的

The correct way would be to declare the column as UNIQUE and also as NOT NULL (as you would want to ensure that null a row with null is never inserted). 正确的方法是将列声明为UNIQUE ,也声明为NOT NULL (因为您要确保null永远不会插入具有null的行)。

So instead of :- 所以代替:-

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + 
            TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +  
            COL2 + " TEXT,"+
            COL3 + " TEXT,"+ 
            COL4  + " TEXT," +
            COL5 + " TEXT
            )";
    db.execSQL(createTable);
}

You could have :- 你可以有 :-

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + 
            TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +  
            COL2 + " TEXT UNIQUE NOT NULL," + //<<<< changed
            COL3 + " TEXT,"+ 
            COL4  + " TEXT," +
            COL5 + " TEXT
            )";
    db.execSQL(createTable);
}

The above would then work and not insert duplicates. 以上将工作,并且不会插入重复项。 However, you would get an error logged but without an exception. 但是,您将记录一个错误,但没有例外。 To suppress the output to the log you may want to then use :- 要禁止输出到日志,您可能需要使用:-

public boolean addData(String item , String number  , String anlam) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, item);
    contentValues.put(COL3 , number);
    contentValues.put(COL4, anlam);
    contentValues.put(COL5 ,"#419FEE");

    Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);

    long result = db.insertWithOnConflict(TABLE_NAME, 
        null, 
        contentValues, 
        SQLiteDatabase.CONFLICT_IGNORE
    );

    //if date as inserted incorrectly it will return -1
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}
  • Using insertWithOnConflict as opposed to insert allows a 4th parameter to specify how to handle constraint violations ( UNIQUE and NOT NULL are constraints that the table now has). 使用insertWithOnConflict而不是insert允许第四个参数指定如何处理约束冲突UNIQUENOT NULL是表现在具有的约束 )。 In this case you want to ignore constraint violations . 在这种情况下,您想忽略约束违例

  • Note! 注意! to implement this do one of the following after amending the code :- 要实现此目的,请在修改代码后执行以下操作之一:

    • Increase the version number 增加版本号
    • Delete the App's data 删除应用程序的数据
    • Uninstall the App 卸载应用

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

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