How to pass dynamic values to a Query using SQLITE in Android ? - java

i am trying to pass dynamic id to query every time no of passed id will change sometimes it may be 3 or 2 or etc.My question is how can i pass this id and select values from query.
String[] splits = clickedTopicIdString.split("-");
Log.i("splits",""+splits.length); // length 2 bcoz clickedTopicIdString = 0-1 it may be 0-1-2 etc
if(splits.length > 0)
{
for(int i=0;i<splits.length;i++)
{clickedTopicIdInt = Integer.parseInt(splits[i]);// i want to save values in an array and pass it GetQuestionData(); this method after converting it in integer.....
Log.i("clickedTopicIdInt",""+clickedTopicIdInt);
}
}
clickedTopicIdInt = Integer.parseInt(clickedTopicIdString);
dbhelper = new JamiaBinoriaDBHelper(context);
dbhelper.open();
GetQuestionData();
This function will recieve id dynamically in form of arrays and will apply it here topic_question.topic_id="+topic_id1+" OR topic_question.topic_id="+topic_id2+" and so on how can i do this?
public List<String> GetClickedIdImages(int topic_id)
{ List<String> questionImageNameList = new ArrayList<String>();
String query = "SELECT topic_question.question_image_name FROM topic_question,topic WHERE topic_question.topic_id="+topic_id+" AND topic.id=topic_question.topic_id";
// Cursor cursor = db.rawQuery("SELECT topic_question.question_image_name FROM topic_question,topic WHERE topic_question.topic_id=1 AND topic.id=topic_question.topic_id",null);
Cursor cursor = db.rawQuery(query,null);
Log.i("Cursor Query Print:",""+query);
if(cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Log.d("cursor",""+cursor);
questionImageNameList.add(cursor.getString(0));
Log.i("cursor.getString(2)",""+cursor.getString(0));
cursor.moveToNext();
}
} else {
Log.d("", "Cursor is Null");
Log.d("retrieving all parameters", "count < 0");
}
cursor.close();
return questionImageNameList;
}
can someone please help me in this task ?

If you want to create your select dynamically basing on a list of IDs you shoud this SQL syntax:
SELECT * FROM TABLE WHERE ID IN (id1, id2, ..., idn)
id1,id2 = your ids
http://www.tutorialspoint.com/sqlite/sqlite_where_clause.htm
String numbers = "1-2-3-4-5";
String [] splits = numbers.split("-");
Integer [] realNumbers = new Integer [splits.length];
String sqlSelect = "SELECT * FROM TABLE WHERE ID IN ";
String whereStatement = "(";
for (int i = 0; i<splits.length; i++)
{
realNumbers[i] = Integer.parseInt(splits[i]);
whereStatement += realNumbers[i]+((i == splits.length -1) ? "" :",");
}
whereStatement += ");";
sqlSelect += whereStatement; //your select SELECT * FROM TABLE WHERE ID IN (1,2,3,4,5);

Related

How to control where id is equal to unknown number of variable sql query?

I am looking for something like that:
String ID = ContactsContract.Contacts._ID;
ContentResolver cR = context.getContentResolver();
Cursor cursor = cR.query(mUri, null, ID + " =?", mStringArray, null);
mStringArray is not obvious, and the user will assign its elements. So we don't know what is the length of the array and what elements mStringArray has. I want to query for every values of mStringArray. In that case, i am getting an error which is "IllegalArgumentException: Cannot bind argument at index 2(or 3,4,...) because the index is out of range. The statement has 1 parameters".
I hope i am clear.
Instead of = you should use the operator IN and construct the statement with as many ? placeholders as the items of the array mStringArray:
String ID = ContactsContract.Contacts._ID;
ContentResolver cR = context.getContentResolver();
StringBuilder sb = new StringBuilder();
for (String s : mStringArray ) {
sb.append("?,");
}
String sqlIn = null;
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
sqlIn = ID + " IN (" + sb.toString() + ")";
}
Cursor cursor = cR.query(mUri, null, sqlIn, mStringArray, null);

SQLite, return data as an array

I have an SQLite Database in my android application with the following structure:
public void onCreate(SQLiteDatabase db) {
String CREATE_LISTS_TABLE = "CREATE TABLE " + TABLE_LISTS +
"("+
_ID + " INTEGER PRIMARY KEY , " +
NOTE + " TEXT" +
")";
db.execSQL(CREATE_LISTS_TABLE);
}
And this works, in that I can insert data into it without a problem. However I need to store the notes inside an array. I currently have the following query:
public List<String> getAllNotes() {
List<String> notes = new ArrayList<>();
String GET_ALL_NOTES = "SELECT * FROM " + TABLE_LISTS;
SQLiteDatabase db = getReadableDatabase();
if(db!=null)
{
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
cursor.moveToFirst();
while(!cursor.isAfterLast())
{
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex("notes"))));
cursor.moveToNext();
}
cursor.close();
}
db.close();
return notes;
}
However, this gives the following error:
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
I was wondering how to fix this, I have read the android developer stuff but I can't seem to get anything to work.
Thanks in advance
Check the value of "NOTE", and use it in:
notes.add(String.valueOf(cursor.getInt(cursor.getColumnIndex(NOTE))));
I think a best way to make the call should be something like this:
// Check the cursor
if(cursor != null) {
if (cursor.moveToFirst()) {
// Variables to be used
String note;
// Col position
int colNote = cursor.getColumnIndex(NOTE);
do {
// Get the information
note = cursor.getString(colNote);
// Add the note
notes.add(note);
} while (cursor.moveToNext());
}
// Close the cursor
cursor.close();
}
Because you are fetching only integer and string from database, instead of using ArrayList , you can try using HashMap. So you can get the value by just giving the key. Below simple code will work for ArrayList too with minor changes..
Try this
HashMap<Integer,String> notes = new HashMap<Integer,String>() ;
Cursor cursor = db.rawQuery(GET_ALL_NOTES, null);
while (cursor.moveToNext())
{
int i = cursor.getInt(0);
String s = cursor.getString(1);
notes.put (i,s) ;
}
cursor.close();

How can I implement a String variable instead of 'Landschaft'?

I have created a SpinnerActivity, which looks like following:
http://img4.fotos-hochladen.net/uploads/bildschirmfotovse8j4po1t.png
Now for example if I select 'Landschaft' (in English: landscape) I want to search in the DatabaseHandler.java for a location which is in the category 'Landschaft' (landscape)
Therefore I have written the following method in DatabaseHandler.java:
In this method, I have just written Kategorie = Landscape.
However I want, that the selected SpinnerArray (Landschaft, Brücken...etc.) in my Spinner would be inserted in my DatabaseHandler instead of "Landschaft", how can I do that?
public List<Position> getAllPositionsWithCategory() {
List<Position> positionList = new ArrayList<Position>();
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = 'Landschaft'";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Position position = new Position();
position.setID(Integer.parseInt(cursor.getString(0)));
position.setName(cursor.getString(1));
position.setKategorie(cursor.getString(2));
position.setLaenge(cursor.getFloat(3));
position.setBreite(cursor.getFloat(4));
// Adding position to list
positionList.add(position);
} while (cursor.moveToNext());
}
}
Simply replace the the fixed String with ? in your query, and pass the value to be inserted in the second argument of db.rawQuery().
The following might work for your case:
String selectQuery = "SELECT * FROM " + TABLE_POSITIONS
+ " WHERE Kategorie = ?";
// ...
Cursor cursor = db.rawQuery(selectQuery, new String[] { "Landschaft" });
You can now replace your String "Landschaft" with a variable of your choice.
See also: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#rawQuery(java.lang.String,%20java.lang.String[])

Android SQLite: CursorIndexOutOfBoundsException when retrieving a row from a table?

I keep getting android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 exception when trying to get a single row from a Sqlite table using a ID value.
Why do you think this happens? What is wrong with my code?
public Product getProduct(DBOps dop, String productId) {
Product p = new Product();
String sqlQuery = "SELECT " + TableInfo.PID + " FROM "
+ TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'";
SQLiteDatabase SQ = dop.getReadableDatabase();
Cursor CR = SQ.rawQuery(sqlQuery, null);
try
{
if(CR.getCount() > 0)
{
while (!CR.isAfterLast()) {
p.PID = CR.getString(0);
p.NAME = CR.getString(1);
p.SIZE = CR.getString(2);
p.COLORS = CR.getString(3);
p.DESC = CR.getString(4);
p.PRICE= CR.getString(5);
p.OUTLETS = CR.getString(6);
p.FABRIC = CR.getString(7);
p.QUANTITY = CR.getString(8);
p.CATEGORY = CR.getString(9);
p.RATING = CR.getString(10);
CR.moveToNext();
}
}
else
{
CR.close();
}
}
catch(Exception ex)
{
Log.e("DBOps Error", "Look at DBOps Class's getProduct Method");
Log.e("DBOps Error", ex.toString());
}
return p;
}
android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 1
Because you are currently selecting only one column from table which is TableInfo.PID but trying to retrieve more then one column from cursor.
So change select query by specify all columns in select query or use * FROM get all columns:
String sqlQuery = "SELECT * FROM "
+ TableInfo.TABLE_NAME +" WHERE pid="+"'"+productId+"'";
Use Like This
if(cursor.getCount()>0)
{
if(cursor.moveToFirst())
{ do
{
//your code
}
while(cursor.moveToNext());
cursor.close();
}
}
Hope it will helps u
You need to call cursor.moveToFirst() before using the cursor. This moves it to row 0. Make sure to check the return value- if it returns false then it could not move to row 0 for some reason (generally it means 0 rows returned).

how to fetch a row using id sqlite?

This is a simple one! yet, I am missing something. Please help me out.
Here, I am trying to fetch values by id, but not able to do so. It is returning same values even after changing id's value.
db = openOrCreateDatabase("DBSOURCE", 0, null);
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE ID="+id+"", null);
cursorc.moveToFirst();
int NameID = cursorc.getColumnIndex("Name");
int mobilenumberID = cursorc.getColumnIndex("MoblieNumber");
edName.setText(cursorc.getString(NameID));
edMobNum.setText(cursorc.getString(mobilenumberID));
cursorc.close();
db.close();
1-
or better to use parametrized statement
String query = "SELECT COUNT(*) FROM " + tableName + " WHERE columnName = ?";
cursor = db.rawQuery(query, new String[] {comment});
2 - use if with conditon c.moveToFirst() or c.getCount() >0 or (!c.isAfterLast())
if (c.moveToFirst()){
do{
//if you not need the loop you can remove that
id = c.getInt(c.getColumnIndex("_id"));
}
while(cursor.moveToNext());
}c.close();
Is the id column title actually "ID"? Or is that a variable that is set to "_id" (the usual column name for the primary key in an Android database)?
If the latter, your query is not right, because you are using "ID" as the literal column name. Try changing it to this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE " + ID + " = " + id, null);
or even this:
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE _id = " + id, null);
try using
Cursor cursorc = db.rawQuery("select * from list where ID = ?", new String[] {id+""});
try with this way
Suppose long id=5;
String[] col=new String[]{KEY_ROWID,KEY_NAME,KEY_ADDRESS}; // your column which data u want to retrive if id is same
Cursor c=db.query(DATABASE_TABLE, col, KEY_ROWID+"="+id,null, null, null, null);
if(c!=null){
c.moveToFirst();
// get data here which u want accroding to ur requirement
}
try this
Cursor cursorc = db.rawQuery("SELECT * FROM LIST WHERE ID='"+id+"'", null);

Categories