Jafang Jafang - 1 month ago 5
Android Question

How to check database with one field in Android

I want create application, in this application users can insert data.

Users can insert this data : Name - fName - Email - Address .

This application is offline and i use

SQLite Database
for local database.

I want when user inserted data, first of all i check in database, if exist this name in names column or no?!

If exist this name into names columns, show
: this name is exist in names columns, and not save this data (Name - fName - Email - Address) into table.

But if not exist this name into names columns, show
: save into database, and save data (Name - fName - Email - Address) into table.

How can i write this query in my DataBaseHelper class?


You just write your codes, such as below my codes:

/*Insert data into database*/
public void insertFAV(Context context, String title, String image, String content, String date, String author, String category) {

    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();
    // 2. set cursor for read row
    Cursor cursor = db.rawQuery("SELECT * FROM " + FavContract.favInfo.TABLE_NAME + " WHERE " +
            FavContract.favInfo.FAV_TBL_PTitle + " = ?", new String[]{title});
    // 3. is exist
    if (cursor.getCount() > 0) {
        // 4 . show error message
        TastyToast.makeText(context, "Not save", TastyToast.LENGTH_LONG, TastyToast.WARNING);
    } else {
        // 5. create ContentValues to add key "column",value
        ContentValues contentValues = new ContentValues();
        contentValues.put(FavContract.favInfo.FAV_TBL_PTitle, title);
        contentValues.put(FavContract.favInfo.FAV_TBL_PImage, image);
        contentValues.put(FavContract.favInfo.FAV_TBL_PContent, content);
        contentValues.put(FavContract.favInfo.FAV_TBL_PDate, date);
        contentValues.put(FavContract.favInfo.FAV_TBL_PAuthor, author);
        contentValues.put(FavContract.favInfo.FAV_TBL_PCategory, category);
        // 6. insert
        db.insert(FavContract.favInfo.TABLE_NAME, null, contentValues);
        TastyToast.makeText(context, "Save success", TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
    // 7. close