Check if record exist in the database android

后端 未结 3 435
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 03:53

I want to check if records exist in the SQLite database, here\'s what I have done so far. when I search for a already existing records im getting value from EditText in list.

相关标签:
3条回答
  • 2021-01-23 04:18

    I use this code in my application and it works perfact...

    LoginActivity.java
    
    DatabaseHelper dbHelper = new DatabaseHelper(getApplicationContext());
    String email_id = email.getText().toString();
    boolean dbHelper.isExist(email_id);
    
    // if record is exist then it will return true otherwise this method returns false
    


    Using rawQuery

     public boolean isExist(String strEmailAdd) {
            db = this.getReadableDatabase();
            cur = db.rawQuery("SELECT * FROM " + USER_TABLE + " WHERE email_id = '" + strEmailAdd + "'", null);
            boolean exist = (cur.getCount() > 0);
            cur.close();
            db.close();
            return exist;
    
        }
    

    Using db.query

    public boolean isExist(String strEmailAdd){
    
            String whereClause = "email_id = ?";
            String[] whereArgs = new String[]{strEmailAdd};
    
            db = database.getWritableDatabase();
            cur = db.query(USER_TABLE, null, whereClause, whereArgs, null, null, null);
            boolean exist = (cur.getCount() > 0);
            cur.close();
            db.close();
            return exist;
    }
    
    0 讨论(0)
  • 2021-01-23 04:27

    Select a single row from your table, is you get results = it exists, else it doesn't.

    public boolean doesStationExist(String name){
        final String query = "SELECT stationName FROM review WHERE stationId='"+name+"' LIMIT 1";
        try (SQLiteDatabase database = getReadableDatabase();
             Cursor c = database.rawQuery(query, null)) {
            return c.moveToFirst();
        }
    }
    

    By the way, the cursor returned from rawQuery is never null.

    Edit:

    The updated code will close the database and the cursor once the try block finishes. This is called try-with-resources.

    0 讨论(0)
  • 2021-01-23 04:27

    DatabaseManager.java

    public Cursor checkFavourites()
    {
    
        String query="select * from "+DATABASE_TABLE;
        Cursor cursor=db.rawQuery(query,null);
    
        return cursor;
    }
    

    MainActivity.java

    public void favourite_Click(View view){
        Cursor cursor=dbManager.checkFavourites();
        if (cursor.getCount()>0)
        {
            Toast.makeText(MainActivity.this, "Favourites", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(MainActivity.this,"Nothing in favourites yet", Toast.LENGTH_SHORT).show();
        }
    }
    
    0 讨论(0)
提交回复
热议问题