Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite SELECT Query

Tags:

I have taken String value from a EditText and set it inside SELECT QUERY after WHERE condition

As

TextView tv = (TextView) findViewById(R.id.textView3); EditTextet2 et = (EditText) findViewById(R.id.editText1);  String name = et.getText().toString();  Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = '"+name+"'", null);   c.moveToNext();  tv.setText(c.getString(c.getColumnIndex("email"))); 

But it doesn't work. Any suggestions?

like image 882
Hiran D.A Walawage Avatar asked Feb 14 '12 16:02

Hiran D.A Walawage


People also ask

Can I use SQL in Android Studio?

The Android SDK includes a sqlite3 shell tool that allows you to browse table contents, run SQL commands, and perform other useful functions on SQLite databases.

How save and retrieve data from SQLite database in Android?

We can retrieve anything from database using an object of the Cursor class. We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move the cursor forward and retrieve the data. This method return the total number of columns of the table.

What is cursor in Android with example?

Cursors are what contain the result set of a query made against a database in Android. The Cursor class has an API that allows an app to read (in a type-safe manner) the columns that were returned from the query as well as iterate over the rows of the result set.

How does SQLite work in Android?

SQLite Database is an open-source database provided in Android which is used to store data inside the user's device in the form of a Text file. We can perform so many operations on this data such as adding new data, updating, reading, and deleting this data.


2 Answers

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null); 

Also use c.moveToFirst() like @thinksteep mentioned.

like image 138
zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz Avatar answered Oct 29 '22 19:10

zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase(); Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null); if (c.moveToFirst()){     do {         // Passing values          String column1 = c.getString(0);         String column2 = c.getString(1);         String column3 = c.getString(2);          // Do something Here with values     } while(c.moveToNext()); } c.close(); db.close(); 
like image 37
Vladimir Monsanto Avatar answered Oct 29 '22 19:10

Vladimir Monsanto