简体   繁体   中英

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

My SQLite Database has 5 columns.

  1. 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 ; I want to add data but When I added the data , İf There is same data(İt is second column(words))in listview. 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)

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. That is you effectively want COL2 to be unique .

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).

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). 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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