Krunal Kapadiya
Krunal Kapadiya

Reputation: 3073

Retrive specific data in row from SQLite database

I have following table. I fetched this data from JSON and store it to SQLite table. I want to fetch all data from TABLE_MAC where meal_id = 12.

TABLE_MAC

| _id | meal_id |   name   |
----------------------------
|  1  | 12,16,17| mac veggi|
|  2  | 14,16   | mac allo |
|  3  | 16,12,14| mac egg  |
|  4  | 112,1,14| fries    |

Now, from a database, I want to fetch all data from meal_id = 12. I applied LIKE operator for fetching data from a database, but it adds fries in Android.

Upvotes: 2

Views: 563

Answers (2)

IntelliJ Amiya
IntelliJ Amiya

Reputation: 75778

Call LIKE Operator

 public List<Model> getAllResult(String getId)
    {
        List<Model> resultList = new ArrayList<Model>();
        // Select All Query
       String selectQuery = "SELECT * FROM "+ TABLE_MAC + " WHERE " + KEY_Meal_ID + " LIKE '%"+getId+"%'";

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst())
        {
            do {
                Model sg = new Model();
                sg.set_id((cursor.getString(0)));
                ......             

                resultList.add(sg);
            } while (cursor.moveToNext());

            cursor.close();
            db.close();
        }

        // return list
        return resultList;
    }

Upvotes: 3

Jackyto
Jackyto

Reputation: 1599

Try something like this to query your database

    SQLiteDatabase database = this.getWritableDatabase();
    String[] columns = new String[] {"_id", "meal_id", "name"};
    String TABLE_NAME = "TABLE_MAC";
    Cursor mCursor =
            database.query(true, TABLE_NAME, columns,
                    "meal_id=12", null, null, null, null, null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }

Then you will have to loop through your Cursor to retrieve your data. Having comma separated id's in your meal_id column is not a good idea. You should implement a mapping table or rethink your database to avoid this.

Upvotes: 1

Related Questions