.rawQuery multiple ? parameter - android

I am trying to use the .rawQuery to return the contents of a column in an SQLite database.
I have a list that is used to query the database and depending on what is clicked depends on what is returned. The problem is that the first item in the list wants to return all results and those below it only certain results.
I am using the following code:
public Cursor getTrailByType(String id) {
String[] args={id};
return(getReadableDatabase()
rawQuery("SELECT _id, NAME FROM trail WHERE TYPE_id=? OR ENT=?",
args));
}
TYPE_id is the specific result to return (if ? is between 2 and 10) and ENT is return all (if ? = 1 ; I have simply added a second column ENT with the number 1 in all rows). So, if id is 1 it returns the ENT criteria but if it is between 2 and 10 it returns the TYPE_id criteria.
The problem is the second ? is not read and a blank list is produced. If I substitue the second ? for an integer then it works but does not populate the specific lists properly.
Can anyone suggest what is wrong with the code?

try this
public Cursor getTrailByType(String id, boolean needAll) {
String[] args = null;
String query = "SELECT _id, NAME FROM trail";
if(!needAll){
query += " WHERE TYPE_id=?";
args = new String[]{id};
}
return (getReadableDatabase().rawQuery(query, args));
}

you can get rid of ENT column and try this ...
// put any id and 1 as ent to get all put id and ent=0 to get specific id
public Cursor getTrailByType(String id, int ent) {
String[] args={id, Integer.toString(ent)};
return(getReadableDatabase().
rawQuery("SELECT _id, NAME FROM trail WHERE TYPE_id=? OR 1=?", args));
}
EDIT: heh need to convert int to string

Related

displaying the value of a particular row

I am trying to display value of a particular row in android to check if a particular updation. Can I made it successful or not? But as the return type is cursor I don't know how to fetch it. So pls help me.
public Cursor getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
return res;
}
Try this...
ArrayList<HashMap<String, String>> dataList = new ArrayList<>();
call your method to get data as arraylist of hashmap
dataList.addAll(loginDataBaseAdapter.getData(id));
or
dataList = loginDataBaseAdapter.getData(id);
in db_class
public ArrayList<HashMap<String, String>> getData(String id) {
ArrayList<HashMap<String, String>> returnArray = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
if (res != null && res.getCount() > 0) {
if (res.moveToLast()) {
do {
HashMap<String, String> getdatamap = new HashMap<String, String>();
getdatamap.put("KEY_ONE", res.getString(1));
getdatamap.put("KEY_TWO, res.getString(2));
returnArray.add(getdatamap);
}while (res.moveToPrevious());
}
}
res.close();
return returnArray;
}
Now you can use the values in arraylist to make your view
You can follow the below code:
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
if (res != null) {
res.moveToFirst();
}
String firstColumnValue = res.getString(0);
String secondColumnValue = res.getString(1);
And close the database after retrieving values:
db.close();
If you want to get column value by its name, then use the following code:
String value = res.getColumnIndex("column_name");
Get row value as a String. Then return string value.
public String getData(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from calls where id=" + id + "", null);
if (res.getCount() > 0) {
res.moveToFirst();
String s = res.getString(res.getColumnIndex("id"));
return s;
}
There are two factors that need to be considered when retrieving data from a cursor; which row (position within the cursor) and then column and it's type.
To position the Cursor you use one of the Cursor's move methods. These are :-
move, which moves the cursor relevant to it's current position.
moveToFirst
moveToLast
moveToNext
moveToPosition and
moveToPrevious
All return true if the move could be performed otherwise false.
A cursor can be empty and have no rows, so movetoFirst would return false.
One of the more common usages is :-
while (cursor.moveToNext) {
.... cursor action(s) here.
}
A Cursor will initially be positioned to before the first row i.e. it's position is -1 and can be set using moveToPosition(-1).
The Cursor's getPosition method will retrieve the current position, noting that the first row is position 0.
Column's in rows are accessed according to the offset (which column) and the Cursor's get???? (where ???? represents type) methods are used to retrieve the data from the row/column (there are other get.... methods e.g. getPosition as above). The methods for retrieving the data are:-
getBlob (retrieves a byte array).
getDouble
getFloat
getInt
getLong
getShort
getString
All take a single parameter, an integer that is the column's offset within the cursor (which is not necessarily the offset in the table).
You can use any on any type of data, with the exception of blobs. An attempt to use any, except getBlob, on a BLOB will result in an exception.
However, the results, can vary e.g. if you use get, for example assuming column with offset 0 contains *rumplestilskin then :-
cursor.getString(0) will return rumplestiltskin
cursor.getDouble(0) will return 0 as a double.
cursor.getInt(0) will return 0 as a float.
.....
In short, you should use the appropriate get method, otherwise the results could be confusing.
Hard coding column column offsets, often results in issues therefore it is generally better to use column names in conjunction with the Cursor's getColumnIndex method. This takes a String, the column name, as a parameter and returns the offset of the column.
Applying the above to the question:-
Code that could be useful (i.e. it retrieves data) could be :-
Cursor csr = db.getData(myid);
while (csr.moveToNext) {
long id_of_the_row = csr.getLong(csr.getColumnIndex(yourDatabaseHelperClass.id));
}
Noting:-
if (moveToFirst(myid)) { .... } could be considered more correct but assuming that just a single row exists bot moveToFirst and moveToNext, as coded, produce the same result.
Assuming that the id column is an alias of the rowid, then rowid is stored as a long and should properly be extracted as a long.
yourDatabaseHelperClass.id will not be correct, rather you would replace it with the class that extends SQLiteOpenHelper (the class that contains your getData method), it also assumes that variable id has public access.
Links that may be useful or of interest:-
Cursor
How flexible/restricive are SQLite column types?
(includes examples of how some of the Cursor get???? methods retrieve data)
Are there any methods that assist with resolving common SQLite issues?

Query Database with an array list and get an array list of results back

I have setup an application which currently can lookup an input id with one on the database to then give a single result. E.g. user enters id = 1 , database contains a record with an id of 1 then returns the name or number etc...
Now I want to improve the system slightly by querying my database with an arraylist which contains a range of id's e.g. 3, 456, 731 etc... which I want my database to search for. I have also grouped multiple values to certain id's for example the database might search for an id of 3 it will then find 5 results I want it to return the telephone number of each one of those results into another arraylist which I can print to the logs.
I hope I have explained this enough, but please ask questions if you require more information.
The code below demonstrates the modified version of the query used to gain a single result, but I cannot see what I'm doing wrong to gain multiple results.
Activity....
// New array list which is going to be used to store values from the database
ArrayList<String> contactsList;
// This arrayList has been received from another activity and contains my id's
ArrayList<String> contacts = intent.getStringArrayListExtra("groupCode");
// The database which i'm using
ContactDBHandler contactDBHandler = new ContactDBHandler(getApplicationContext(), null, null, 1);
//getAllValues is used to pass my arraylist id's to the database.
contactsList = contactDBHandler.GetAllValues(contacts);
// Simple log statement to loop and display results
for (int i = 0; i < contactsList.size(); i++){
Log.i("Numbers", contactsList.get(i));
}
ContactDBHandler
Query
// I'm telling it to get the contact number from the contact_list
// when the groupcode matches the code recieved.
public ArrayList<String> GetAllValues(ArrayList groupCode)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
String alarmName = "";
ArrayList<String> list = new ArrayList<>();
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code=?", new String[]{groupCode+ ""});
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}
Thanks
Can you see where I have gone wrong?
Try this:
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (" + TextUtils.join(",", Collections.nCopies(groupCode.size(), "?")) + ")", groupCode.toArray(new String[groupCode.size()]));
Your current code fails to pass the list in the sql-format: = does only support single values, for lists you have to use IN.
Your code would result in a query like this:
SELECT contact_number FROM contact_list WHERE grp_code=["some_id","other_id"]
But what you need (and my code produces) is:
SELECT contact_number FROM contact_list WHERE grp_code IN ('some_id','other_id')
References:
SQL query to find rows with at least one of the specified values
WHERE IN clause in Android sqlite?
IN clause and placeholders
https://developer.android.com/reference/android/text/TextUtils.html#join(java.lang.CharSequence,%20java.lang.Iterable)
You cannot pass an ArrayList to an SQLQuery. To check for multiple values in the same field you have to use the 'in' keyword.
Ex:
SELECT * FROM `table1` where column in ( 'element1', 'element2', 'element3')
In your case,
String str = "";
for(String s: groupCode){
str = str+","+"\'"+s+"\'";
}
//to remove the extra ' in the begining
str = str.substring(1);
return str;
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (?)", new String[]{str});

How to return all data from one column Android SQL

I have an SQLite Database in my application. It has three columns. being _id, TEXT, and Location. If I want to return all the data from, say, the TEXT column should I use cursor.getColumnIndex(2)? I am obviously new to SQLite. And and all help is appreciated. Thanks everyone!
Yes, friend, you are new.
First off, your database doesn't have three columns, but rather, your table does. Databases have tables, tables of columns (fields) and rows (records).
Secondly, TEXT is not a valid name for a column, as it's a datatype. Let's say you called the three columns id, theText, and location -- then if you selected all three columns to be returned, the second one would be accessible through:
cursor.getString(1); // that's the second column returned
or
cursor.getString(cursor.getColumnIndex( "theText" ) );
However, you can have sqlite do most of the work for you by selecting only the column you're interested in, so then you'd cursor.getString(0) as it's the only column returned.
For more pertinent explanations, please post your code in the question.
simply apply the query of getting all contacts and take an array of string type and then add the required record in that array as shown below
I hope this code help u
in DBHelper getting record of particular column :
public ArrayList<String> getAllCotactsEmail() {
ArrayList<String> arrayList=new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts", null );
res.moveToFirst();
if (res != null)
{
while(res.isAfterLast() == false){
arrayList.add(res.getString(res.getColumnIndex(CONTACTS_COLUMN_EMAIL)));
Log.d("emailssinlisttt",arrayList.toString());
res.moveToNext();
}}
return arrayList;
}
retrieve :
email=mydb.getAllCotactsEmail();
Log.d("emaillllll",email.toString());
You need to query your Database to get your data. This query will return a Cursor with the column you specified in the query.
To make query, you need to call query() method from ContentResolver. To get your ContentResolver, you can use getContentResolver() from a Context like Activity :
getContentResolver.query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder);
To understand all parameters, see : ContentResolver
In your case, you want only TEXT column so pass a String array with your TEXT column name for projection parameters.
You want all rows so your selection and selectionArgs parameters must be null.
If you don't care about order, pass null for sortOrder (rows will be sort by ID) :
Cursor c = getContentResolver.query(yourUri, new String[]{"TEXT"}, null, null, null)
This query will return a cursor, to extract your values from the cursor, make a loop like :
if(c.moveToFirst()) {
do {
final String text = c.getString(c.getColumnIndex("TEXT"));
} while (c.moveToNext());
}
Hope this will help you :)

How to get SQLite database Column values as List in android

I have three column, first id, second title and third body.
Like this
id title body
1 t1 b1
2 t2 b2
3 t3 b3
So, I want to get title and display in list with listview and if I click t2 title then display body of respective clickable title.
What i did.
DatabaseHelper.java
public Cursor retriveTitle(String [] title) {
Cursor c = null;
c = myDataBase.rawQuery(
"select id,title from book,", title);
return c;
}
Main.java
private void displayTitle() {
try {
myDataBase = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b ", new String[] { "" });
String test=cursor.getString(cursor
.getColumnIndex("title"));
//How to display title of book in listview
}
getting this:
01-18 14:20:03.401: E/AndroidRuntime(6704): Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I am using already database file, according to this blog post: Using your own SQLite database in Android applications
Try out
Cursor cursor = myDataBase.rawQuery("SELECT b.id, b.title FROM book b",null);
curosr.moveToFirst();
String test=cursor.getString(cursor
.getColumnIndex("title"));
I think your query should use a "where" statement
c = myDataBase.rawQuery("select id,title from book where title=?", title);
Of course you want to pass a certain number of arguments
c = myDataBase.rawQuery("select id,title from book where title in (?, ?, ?)", new String[]{title1, title2, title3});
But then if the number of title can vary, you will need to dynamically create a string with enough question marks. See this post
IN clause and placeholders
If you still get en error, maybe providing more log could help. Also if the lo say what line fails, tell which one it is. we can't see line numbers here
Good luck
Here's how it worked out for me. In an other class, I have created a method of List type and added the column id & the name of the item in the list from the sqlite database.
Here's the piece of code to retrieve the column id of the selected item.
public List<String> list;
adapt = new MyAdapter(this, R.layout.list_inner_view, list); //custom adapter
listTask.setAdapter(adapt);
listTask.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
Integer id = list.get(position).getId();
//position is the position of the item in the list.
}
});
Result: the item is at 3rd position in the list. Its database column_id (auto increment) value is 12 because I have deleted previous items. So the result you expect is 12, which is the value of variable id.
If you don't understand this fully, it may be because I haven't posted my entire code. But I'll help you out with your problem.

Delete entire row from SQLite android using two given column data

I want to delete a specific row in SQLITE data in android.Now, I already try only using only one column data like primary key but now I want to delete an entire row using a column key and column name .How will I do this?help me
Below is the syntax I made to delete, but their nothing happen?
DatabaseHandler.java
public Cursor delete(String id, String name){
SQLiteDatabase data=this.getWritableDatabase();
String selectQuery = "DELETE FROM Criteria WHERE criteria_eventpk ="+"'"+id+"' AND criteria_eventpk ="+"'"+name+"'" ;
Cursor idupdate = data.rawQuery(selectQuery, null);
data.close();
return idupdate;
I use rawQuery because I try db.delete but only one data is only allowed.So I try rawQuery .
Next, the codes in the button delete in my MainActivity
evcri_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
db.delete(evpk.getText().toString(), cripk.getText().toString());
}
});
I think I made a wrong choice to choose cursor, Can anyone help me?I guess a custom query is needed but I need your help.Help me..
I try this ,but still it doesn't work.In their any wrong code I use?
public void delete(Criteria cri, Criteria pk){
SQLiteDatabase data=this.getWritableDatabase();
data.delete(TABLE_CRITERIA,"criteria_name=? AND criteria_eventpk=?", new String[]{String.valueOf(cri.get_criname()),String.valueOf(pk.get_eventpk())});
data.close();
In my delete button
db.delete(evpk.getText().toString(), cripk.getText().toString());
But when I try this code below, it works but only the id is given,I want the given are id and name..
data.delete(TABLE_CRITERIA,"criteria_name=?, new String[]{String.valueOf(cri.get_criname())});
I use rawQuery because I try db.delete but only one data is only allowed.So I try rawQuery .
This information is not correct. The db.delete method allows multiple parameters:
public int delete(String id, String name){
SQLiteDatabase data = this.getWritableDatabase();
String table = "Criteria";
String whereClause = "criteria_eventpk=? AND criteria_eventpk =?" ;
String whereArgs[] = new String[] {id, name};
int count = data.delete(table, whereClause, whereArgs);
data.close();
return count;
}
Try this - I put the single quotes inside the double quotes and it always works for me
String selectQuery = "DELETE FROM Criteria WHERE criteria_eventpk ='"+id+"' AND criteria_eventpk ='"+name+"'" ;
Your statement is of the form:
DELETE FROM Criteria WHERE criteria_eventpk = /id/ AND criteria_eventpk = /name/
So criteria_eventpk has to equal both the value of id and the value of name. That will only be the case where id and name are the same which I imagine is not usually going to be the case?
Did you want to delete where criteria_eventpk is equal to either id or name? If so change the AND to OR. Or do you mean to check two different columns in the row? In which case one of the criteria_eventpk's needs changing.

Categories

Resources