retrieve specific values from SQLite database - android

I am a beginner in Android. I created a database with unique id, name, email etc. I want to retrieve the specific data from the database using the unique id. I don't know what to do. I read the previous answers but didn't get any idea from that.

At first you should read SQL Database
Below code is DEMO
public String getSpecificResult(int getID) // you should pass getID from your Class
{
SQLiteDatabase db = this.getWritableDatabase();
String get_Status = "0";
String selectQuery = "SELECT your_coloum_ FROM "+ TABLE_NAME + " WHERE " + YOUR_UNIQUE_KEY + " = '"+ getID +"'";
Cursor c = db.rawQuery(selectQuery, null);
if (c != null && c.moveToFirst()) {
get_Status = c.getString(0); // Return 1 selected result
}
db.close();
return get_Status;
}

Try this..
pass ur unique_id to get the contents.. alter names according to your table.
public Cursor getContact(long rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_NUMBER}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}

Related

search sqlite with multiple columns

Hi every one I'm trying to search my sqlite data base which has 4 columns but the app crashes and the log error is :-
Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I'm wondering if there is a method to search sqlite data base with multiple columns and with single columns.
The code for the cursor is :-
cursor = mReadableDB.query(WORD_LIST_TABLE, columns, where, whereArgs, null, null, null);
DataBase Code is :
public Cursor search(String searchString) {
String[] columns = new String[]{KEY_WORD};
String where = KEY_WORD + " LIKE ?";
searchString = "%" + searchString + "%";
String[] whereArgs = new String[]{searchString};
Cursor cursor = null;
if (mReadableDB == null) {
mReadableDB = getReadableDatabase();
}
cursor = mReadableDB.query(WORD_LIST_TABLE, columns, where, whereArgs, null, null, null);
return cursor;
}
and the search class is :
public void showResult(View view) {
String word = editText_search.getText().toString();
textView.setText("Result for " + word + ":\n\n");
Cursor cursor = mDataBase.search(word);
cursor.moveToFirst();
if (cursor != null & cursor.getCount() > 0) {
int index;
String result;
do {
index = cursor.getColumnIndex(mDataBase.KEY_WORD);
result = cursor.getString(index);
textView.append(result + "\n");
} while (cursor.moveToNext());
cursor.close();
} else {
textView.append("no result");
}
}
Your cursor does not return anything. this is how I usually use database in android: by using .rawQuery(); and SQLite.
e.g.
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM tasks WHERE id = " + id, null);
And you can also check if the cursor is empty or not by calling cursor.moveToFirst();.
If cursor was empty, the method returns false. else it returns true.
After checking that, you can go to the row that you want by using cursor.move(rowNumber); and get the value of the column you want with get methods e.g. cursor.getString(1);

Error in database class in data fetching query

I am developing a app in android and here i want to fetch data from table according to rowId and subjectId but I am getting this error,
The method query(boolean, String, String[], String, String[], String, String, String, String) in the type SQLiteDatabase is not applicable for the arguments
(boolean, String, String[], String, String, null, null, null, null)
And the here's that query,
public Cursor getText(long rowId, long subId) throws SQLException
{
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_id, KEY_ques,KEY_correctans,KEY_wrongans1,KEY_wrongans2,KEY_wrongans3,KEY_subject,KEY_subjectid }, KEY_id + "="
+ rowId, KEY_subjectid + "=" + subId,null,null, null,null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
I want to fetch table data as where subId = KEY_subjectid and rowId = KEY_id
If any thing is not clear in this question please ask me. And if its clear please help me..
Thanks in Advance.
Change the query to following:
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_id, KEY_ques,KEY_correctans,KEY_wrongans1,KEY_wrongans2,KEY_wrongans3,KEY_subject,KEY_subjectid }, KEY_id + "="
+ rowId + " AND " + KEY_subjectid + "=" + subId,null, null,null, null,null);
The 5-th parameter needs to be a String array, not a string the way you have. The 4-th parameter is the WHERE SQLite clause.
Do this way
public Cursor getText(long rowId, long subId) throws SQLException
{
Cursor mCursor = db.rawQuery("select * from "+DATABASE_TABLE+" where KEY_subjectid="+subId+" and KEY_id="+rowId+"",null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}

multiple where clause failed - assigning same string for different column values

In my code there is a function to retrieve rows in which countdesc= inputText and countdate= datevalue. But both countdesc and countdate are getting assigned as EditText .the logcat is given here.please help me find the error.
public Cursor fetchEventByName(String inputText,String datevalue ) throws SQLException {
SQLiteDatabase db = this.getReadableDatabase();
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = db.query(DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_DESC, KEY_DATE, KEY_EVENT },
null, null, null, null, null);
}
else {
mCursor= db.rawQuery("select * from <countable> where countdesc='" + inputText + "' and countdate='" + datevalue+ "'", null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
logcat
08-16 06:28:11.730: E/AndroidRuntime(2673): java.lang.RuntimeException: Unable to start activity ComponentInfo{example.events1/example.events1.Getclicker}: android.database.sqlite.SQLiteException: near "<": syntax error (code 1): , while compiling: select * from <countable> where countdesc='Yalahanka' and countdate='Yalahanka'
Try the below code:
SQLiteDatabase db=openOrCreateDatabase("MYDB", MODE_PRIVATE, null);
String table="myTbl";
String whereClause = "Number = ? AND Name = ?";
String[] whereArgs = new String[] { strNum };
whereArgs[1] = new String[] { strNname };
db.delete(table, whereClause, whereArgs);
db.close();
In the above code, i'm deleting entries with multiple where clause.
Replace your code line in if else loop with this
mCursor= db.rawQuery("select * from countable where countdesc='" + inputText + "' and countdate='" + datevalue+ "'", null);

Will this update my sqlite database correctly using android.sqlite

I have been struggling to get data from my sqlite database for the last 4 days because for some reason the queries I am using do not work. Here is my function:
public void updateBadgesRecord(int rowId, String id, String name, String description, String image_url, String club_id, String created_at)
{
Log.i("image_url in updateBadgesRecord", image_url);
ContentValues args = new ContentValues();
if(id != null){
args.put(KEY_BADGES_ID, id);
}
if(name != null){
args.put(KEY_BADGES_NAME, name);
}
if(description != null){
args.put(KEY_BADGES_DESCRIPTION, description);
}
if(image_url != null){
args.put(KEY_BADGES_IMAGEURL, image_url);
}
if(club_id != null){
args.put(KEY_BADGES_CLUBID, club_id);
}
if(created_at != null){
args.put(KEY_BADGES_CREATEDAT, created_at);
}
//return db.update(DATABASE_TABLE_BADGES, args, KEY_ROWID + "=" + rowId, null) > 0;
db.update(DATABASE_TABLE_BADGES, args, KEY_ROWID + "= ?", new String[]{String.valueOf(rowId)});
}
Running this method appears to produce no errors.
But when I try and get all the data from this table:
public Cursor getBadgeRecord(int rowId) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE_BADGES, new String[] {KEY_ROWID,
KEY_BADGES_ID, KEY_BADGES_NAME, KEY_BADGES_DESCRIPTION, KEY_BADGES_IMAGEURL, KEY_BADGES_CLUBID, KEY_BADGES_CREATEDAT},
KEY_ROWID + "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
int columnIndex = mCursor.getColumnIndex("image_url");
Log.i("mCursor", columnIndex+"<--- column index" + " | row id"+ rowId);
return mCursor;
}
I get a Cursor record count of 0. What could be causing this? I have tried various different queries that should work so I am now at the point of giving up and not storing data with an sqlite database. Please help me.
db.update(...) only updates existing rows. You probably want to do db.insert(...) link

sqlite selection error

I got this code in one of my methods. It should check if the string is already in the database and if it is the db entry gets updated. If it is not there I catch the exception and just create the entry.
String s="hallo";
try {
Cursor c1 = dba.fetchSubject(s);
dba.updateSubject(c1.getLong(c1.getColumnIndex(DbAdapter.KEY_ROWID)), s, t, r);
} catch (SQLException e){
dba.createSubject(s, t, r);
}
The problem is fetchSubject allway throws an Exception.
I use a similar method to get a db entry by a rowId instead of a String, which is working:
public Cursor fetchSubject(long rowId) throws SQLException {
Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_ROWID
+ "=" + rowId, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
The method called on top:
public Cursor fetchSubject(String subject) throws SQLException {
Cursor mCursor = database.query(true, DATABASE_TABLE2, new String[] {
KEY_ROWID, KEY_SUBJECT, KEY_TEACHER, KEY_ROOM}, KEY_SUBJECT
+ "=" + subject, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
The error:
sqlite returned: error code = 1, msg = no such column: hallo
I don't know where my error is. Isn't it possible to use a string at the selection parameter?
Try adding single quotes around hallo
String s = "'hallo'";
Essentially what you're doing is telling your query: select blah blah blah from TABLE where subject = hallo. Since hallo isn't surrounded by quotes, it is trying to find a variable / column with that name. When we surround it with quotes, we are saying that we are looking for the string within these quotes, rather than a variable.
Think of it like normal programming..
String s = hallo;
is completely different than
String s = "hallo";

Categories

Resources