Ozuf Ozuf - 2 months ago 9
Android Question

How to search for a string in an SQLite database

I am new to SQLite in Android. I have successfully created the database with this schema:

public final class BookDbSchema {

private BookDbSchema() {
}

public static final class BookEntry implements BaseColumns{
public static final String NAME = "bookItems";

public static final String ID = "id";
public static final String URL = "url";
public static final String TITLE = "title";
}
}


The problem I am having is searching the database for a particular string.

I want to search the id column if 1993 exists. Please how do I do that?

I have read the documentation but I don’t know where to input "1993" for in the query method.

Answer

i belive you are looking for this

 Context context;
    BookDbSchema mDbHelper;

    public BookDbSchema (Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }
    ...

    ArrayList<String> urls = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();

    mDbHelper = new BookDbSchema(context);
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String[] projection = {
            FeedEntry.ID,
            FeedEntry.URL,
            FeedEntry.TITLE
    };

    String selection = FeedEntry.ID + " LIKE ? "; //WHERE
    String[] selectionArgs = {"1993"};   //VALUE

    Cursor c = db.query(
            FeedEntry.NAME,  // Your Table Name
            projection,
            selection,
            selectionArgs,
            null,
            null,
            null
    );


    if(c.getCount() != 0) {
        c.moveToFirst();
        for(int i = 0; i<c.getCount(); i++) {
            urls.add(c.getString(c.getColumnIndex(FeedEntry.URL)));
            titles.add(c.getString(c.getColumnIndex(FeedEntry.TITLE)));
            c.moveToNext();
        }
    }else{
        //Nothing found
    }


    c.close();
    db.close();

    String firstUrl = urls.get(0);   //Returns the first url found
    String firstTitle = titles.get(0);
    int urlSize = urls.size(); // returns the count of urls found