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?
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.
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();
Try using the following statement:
Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE name = ?", new String[] {name});
Android requires that WHERE clauses compare to a ?, and you then specify an equal number of ? in the second parameter of the query (where you currently have null).
And as Nambari mentioned, you should use c.moveToFirst() rather than c.moveToNext()
Also, could there be quotations in name? That could screw things up as well.
Here is the below code.
String areaTyp = "SELECT " +AREA_TYPE + " FROM "
+ AREA_TYPE_TABLE + " where `" + TYPE + "`="
+ id;
where id is the condition on which result will be displayed.
public User searchUser(String name) {
User u = new User();
SQLiteDatabase db = this.getWritableDatabase(); //get the database that was created in this instance
Cursor c = db.rawQuery("select * from " + TABLE_NAME_User+" where username =?", new String[]{name});
if (c.moveToLast()) {
u.setUsername(c.getString(1));
u.setEmail(c.getString(1));
u.setImgUrl(c.getString(2));
u.setScoreEng(c.getString(3));
u.setScoreFr(c.getString(4));
u.setScoreSpan(c.getString(5));
u.setScoreGer(c.getString(6));
u.setLevelFr(c.getString(7));
u.setLevelEng(c.getString(8));
u.setLevelSpan(c.getString(9));
u.setLevelGer(c.getString(10));
return u;
}else {
Log.e("error not found", "user can't be found or database empty");
return u;
}
}
this is my code to select one user and one only
so you initiate an empty object of your class then
you call your writable Database
use a cursor in case there many and you need one
here you have a choice Use : 1-
if (c.moveToLast()) { } //it return the last element in that cursor
or Use : 2-
if(c.moveToFirst()) { } //return the first object in the cursor
and don't forget in case the database is empty you'll have to deal with that in my case i just return an empty object
Good Luck
Detailed answer:
String[] selectionArgs = new String[]{name};
Cursor c = db.rawQuery(
"SELECT * FROM " + tabl1 +
" WHERE " + name + " = ? ", selectionArgs
);
selectionArgs : this takes the 'name' you desire to compare with, as argrument.
Here note "A Cursor object, which is positioned before the first entry of the table you refer to".
So,to move to first entry :
c.moveToFirst();
getColumnIndex(String ColumnName) : this returns the zero-based column index for the given column name.
tv.setText(c.getString(c.getColumnIndex("email")));
In case, you want to go searching through multiple rows for a given name under 'name' column then use loop as below:
if (cursor.moveToFirst()){
do{
////go traversing through loops
}while(cursor.moveToNext());
}
This should solve the problem.
Related
I'm trying Official Documentation for Android this article. Creating Database, Table and inserting data is working fine. But I'm unable to get data from database. Here is the piece of code to retrieve data from table.
public Person searchDataInDB(String personCellString) {
SQLiteDatabase db = getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PersonTable.COLUMN_NAME_ID,
PersonTable.COLUMN_NAME_NAME,
PersonTable.COLUMN_NAME_CELL_NO,
PersonTable.COLUMN_NAME_ADDRESS
};
// Filter results WHERE "cell#" = 'Person Cell #'
String selection = SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO + " = ?";
String[] selectionArgs = {"'" + personCellString + "'"};
// How you want the results sorted in the resulting Cursor
// String sortOrder = SQLiteDBHelper.PersonTable.COLUMN_NAME_ID + " DESC";
Cursor cursor = db.query(
SQLiteDBHelper.PersonTable.TABLE_NAME, // The table to query
null, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
String [] names = cursor.getColumnNames();
Log.e("SQLiteDB", "cursorCount = " + cursor.getCount() + ", cursorColumnCount = " + cursor.getColumnCount() + ", Column = " + names[0]);
Person person = null;
while (cursor.moveToNext()) {
int id = (int) cursor.getLong(
cursor.getColumnIndexOrThrow(PersonTable.COLUMN_NAME_ID));
Log.e("SQLiteDB", "moveToNext id = " + id);
String name = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_NAME));
Log.e("SQLiteDB", "moveToNext name = " + name);
String cellNo = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_CELL_NO));
Log.e("SQLiteDB", "moveToNext cell = " + cellNo);
String address = cursor.getString(
cursor.getColumnIndexOrThrow(SQLiteDBHelper.PersonTable.COLUMN_NAME_ADDRESS));
Log.e("SQLiteDB", "moveToNext address = " + address);
person = new Person(id, name, cellNo, address);
}
cursor.close();
return person;
}
It seems like my app does not enter in while loop i.e. while(cursor.moveToNext() So this method always returns initial value of person which is null. As a result, the first condition is always true from below code
Person person = dbHelper.searchDataInDB(personCellString);
if (person == null) {
Toast.makeText(mContext, "no such record exists in database!", Toast.LENGTH_LONG).show();
} else {
String personDetails = "Name = " + person.getName()
+ "Cell Number = " + person.getCellNumber()
+ "Address = " + person.getAddress();
personDetailsTV.setText(personDetails);
}
I'm using DB Browser for SQLite so I can see the records are successfully adding in the database.
What should I do with the above code to make it work?
What you are doing with this:
String[] selectionArgs = {"'" + personCellString + "'"};
is searching for the string value of personCellString enclosed inside single quotes and not for the actual value of the string personCellString.
Remove the single quotes:
String[] selectionArgs = {personCellString};
You don't have to worry about the string representation of personCellString in the final sql statement that will be constructed and executed which will contain them without explicitly setting them.
So I have a method that allows me to get the id of a certain item by using a name i already have in an SQL Database. How would I go about getting the entire row of information and storing each item in its own variable.
Method that only works with ID
public Cursor getID(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT " + COL1 + " FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
And the method that gets the query and stores the result
Cursor data = mydb2.getID(name);
int itemId= -1;
while(data.moveToNext()){
itemId = data.getInt(0);
}
Using this method below how would i store all of the data in its own variable using this (or any other way to get data of entire row).
public Cursor rowData(String name){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
String query = " SELECT * FROM " + TABLE_NAME + " WHERE " + COL2 + " = '" + name + "'";
Cursor data = sqLiteDatabase.rawQuery(query, null);
return data;
}
I know this might be a dumb question, and I have tried looking at other questions, I have gotten this far I just don't know what to do next (I'm very new to Sq Lite databases and Android development)
You'd use something like :-
Cursor csr = instance_of_yourdbhelper.rowData();
while(csr.moveToNext()) {
long thisItemId = csr.getLong(csr.getColumnIndex(yourdbhelper.COL_1));
String thisName = csr.getString(csr.getColumnIndex(yourdbhelper.COL_2));
// etc for other columns
}
Notes
yourdbhelper is the class for your DatabaseHelper which is the class that extends SQLiteOpenHelper (the assumption is that the above methods are from such a class, as this is a common usage of SQLite)
instance_of_yourdbhelper is the instance of the DatabaseHelper class i.e. you may have yourdbhelper dbhlpr = new yourdbhelper(parameters);, in which case dbhlpr is the instance.
This just overwrites the same variables (thisItemId and thisName) for each row in the cursor, although there is perhaps the likliehood that the rowData method only returns one row.
You will likely encounter fewer errors using the getColumnIndex method as it returns the offset according to the column name. Miscalculated offsets is a frequent cause of problems.
You may wish to handle a no rows returned situation in which case you can use cursor.getCount(), which will return the number of rows in the cursor.
I couldn't give a good title to the problem I'm having, but basically I have two columns Name and MaxNum string and int respectively!
I need int method that makes a query which retrieves the MaxNum for specific Name that I give in parameter!
.. so if I have this data
ID | Name | MaxNum
0 | Mike | 50
1 | John | 40
2 | Jess | 30
..when I put Jess in as parameter it will return 30 !
My method so far.. but I can't use it since it doesn't return int value !
public void maxFromName(String name){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE " +COLUMN_NAME+ "=" + name ;
db.execSQL(query);
}
You have to get the result using
Cursor
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE " +COLUMN_NAME+ "=" + name ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
return c.getInt(c.getColumnIndex("MaxNum"));
Update
Since you are facing the problem, I suggest you use the below query:
String query = Select MaxNum from azkar WHERE Name ='Jess';
after this use my code from Cursor c line, this will work.
Use rawQuery for getting data from SQLite. And from the cursor get integer value using getInt function.
Change your maxFromName function with the following.
public int maxFromName(String name){
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE " +COLUMN_NAME+ "= '" + name +"'" ;
Cursor c = db.rawQuery(query, null);
if(c.getCount()!=0){
c.moveToFirst();
return c.getInt(c.getColumnIndex("MaxNum"))
}
return 0;
}
In the API it says the following in the description of execSQL():
Execute a single SQL statement that is NOT a SELECT or any other SQL
statement that returns data.
Use a query method that returns a Cursor type in order to retrieve results
The easiest way to get a single value from a database is with the stringForQuery() or longForQuery() helper functions:
public long maxFromName(String name) {
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT "+COLUMN_MAX+" FROM "+TABLE_AZKAR+" WHERE "+COLUMN_NAME+" = ?";
return DatabaseUtils.longForQuery(db, query, new String[]{ name });
}
(To prevent string formatting problems and SQL injection attacks, always use parameters instead of inserting string values directly into the query.)
You can use rawQuery
public ArrayList<String> maxFromName(String name){
ArrayList<String> maxNums = new ArrayList<>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT " + COLUMN_MAX + " FROM "+ TABLE_AZKAR+" WHERE "
+COLUMN_NAME+ "=" + name ;
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
do { // if that kind of rows are more then one, this metod get all of them
maxNums.add(c.getInt(c.getColumnIndex("MaxNum")));
}
return maxNums;
}
I have the following code
public int getIngCount(String id,String ingrediant) {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS2 + " WHERE id = "+id+ " AND ingrediant = "+ingrediant;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
// return count
return cursor.getCount();
}
But when there is no records satisfying the condition, it causing an exception (no such column) instead of returning 0.
pls help me to find a solution. Thanks in advance.
ingrediant should be treated as a string literal and not as an identifier such as a column name. In SQL you use single quotes for string literals. It's a better idea to use ? placeholders for binding literal values, though:
String countQuery = "SELECT * FROM " + TABLE_CONTACTS2 + " WHERE id = "+id+ " AND ingrediant = ?";
Cursor cursor = db.rawQuery(countQuery, new String[] { ingrediant });
Also, don't call any cursor methods after closing it.
I have table ( id , text) and I need to swap two values in columns like this:
Before.
1 one.
2 two.
3 three.
After ( 1 and 3 swap)
1 three
2 two
3 one
To update each row, you need something like this:
void updateMyTableText (MyTableRow row)
{
ContentValues values = new ContentValues();
values.put ("text", MyTableRow.text);
String where = "id = ?";
String[] whereArgs = new String[1];
whereArgs[0] = Long.toString (row.id);
getDb().update ("MyTable", values, where, whereArgs);
}
where MyTableRow is
class MyTableRow
{
long id;
String text;
}
You'll also need some queries to get the "text" for rows 1 and 3.
Here's one way to do a query:
long getId (String text)
{
// do the query
String query = "select id from MyTable where text = ? ";
String[] args = new String[1];
args[0] = text;
Cursor cursor = getDb().rawQuery (query, args);
if (cursor == null)
throw new IllegalStateException ("cursor is null");
try
{
// get the results
if (!cursor.moveToNext())
return -1; // row not found
long id = cursor.getLong (0);
return id;
}
finally
{
cursor.close();
}
}
Are you trying to change the values in the rows themselves? Most databases systems don't let you arbitrarily swap values since there is an assumption that they are permanently associated. You could issue UPDATE commands to permanently modify the values, but doing this temporarily will probably be an issue handled once the data is returned.
UPDATE table_name
SET text=three
WHERE id=1;
UPDATE table_name
SET text=one
WHERE id=3;
// Assuming id1 < id2
void swap(id1,id2)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
// First get the 2 rows
Cursor res = db.rawQuery("SELECT COLUMN_NAME FROM "+ TABLE_NAME +" WHERE ID IN ("+id1+","+id2+") ORDER BY ID ASC",null);
res.moveToFirst();
CV.put("COLUMN_NAME",res.getString(0));
//Update 1st row with 2nd item
db.update(TABLE_NAME,CV,"ID = ?",new String[]{id2+""});
res.moveToNext();
CV.put("COLUMN_NAME",res.getString(0));
//Update 2nd row with 1st item
db.update(TABLE_NAME,CV,"ID = ?",new String[]{id1+""});
}
Hope it helps!!