moveToFirst does not work - android

I am using moveToFirst and it works very well. But this sql query doesnt work. I don't know why. I didn't receive any error.
My query
String sqlKomut = "SELECT SHareket.*,CHareket.[Meblag],Cari.AnlikBakiye FROM CHareket , SHareket,Cari WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '"+cari.getCariID()+"' AND SHareket.[Seri]='"+hareket.getSeri()+"' AND SHareket.[Sira]='"+hareket.getSira()+"'AND SHareket.[Tip]='"+hareket.getTip()+"' AND SHareket.[Cins]='"+hareket.getCins()+"' ORDER BY SHareket.[Satir]";
and I get my cursor getValue here:
Cursor cursor = db.rawQuery(sqlKomut, null);
if(cursor !=null){
if(cursor.moveToFirst()){
do {
eleman.setStrEleman(cursor.getString(cursor.getColumnIndex("Seri")));
eleman.setIntEleman1(cursor.getInt(cursor.getColumnIndex("Sira")));
eleman.setIntEleman2(cursor.getInt(cursor.getColumnIndex("CariID")));
eleman.setIntEleman10(cursor.getInt(cursor.getColumnIndex("Cins")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Tip")));
eleman.setIntEleman11(cursor.getInt(cursor.getColumnIndex("Satir")));
eklenenfaturalar.add(eleman);
} while (cursor.moveToNext());
}
}

WHERE CHareket.[CariID]=SHareket.[CariID]=Cari.[CariID]= '...'
You cannot do multiple comparisons in a single expression like that.
(The comparison returns a boolean value, 0 or 1; any more comparisons will then use this boolean instead of an ID value, e.g., you end up with something like 1=Cari.CariID.)
To use multiple comparisons, connect them with AND (as you already did with the other ones):
WHERE CHareket.[CariID]=SHareket.[CariID]
AND SHareket.[CariID]=Cari.[CariID]
AND Cari.[CariID]='...'
...

Related

More elegant way than using rawQuery for single results?

To get multiple results of a query I use Cursor c = mydatabase.rawQuery("command", null); and then while (c.moveToNext()) { ... }. Works as advertised.
But if I just want to have one result as in SELECT rowSomething FROM table WHERE [row] = 'Test' and I know that it will be one result, a string, can I do something like
String result = mydatabase.StringQuery("Command");?
Yes, for example with DatabaseUtils#stringForQuery().

How to make SQLite select query faster

Hello I am pretty new with SQLite and I am trying to deal with some database manipulation in my project.
I have a table with almost 4000 rows and this is the format of every row:
problem_id (string)
problem_no (string)
problem_title (string)
dacu (int)
I need to query a bunch of problem_no based on the problem_id. The quantity of query is almost 1000 at a time. So I wrote a query code like this:
Set<Integer> getProblemsTitle(HashSet<String> problemsIDs) {
SQLiteDatabase db = this.getReadableDatabase();
HashSet<Integer> problemNo = new HashSet<Integer>();
Cursor cursor = null;
for (Iterator<String> iterator = problemsIDs.iterator(); iterator.hasNext();) {
cursor = db.query(CommonUtils.PROBLEM_TABLE, new String[] {
CommonUtils.KEY_PROBLEM_NO },
CommonUtils.KEY_PROBLEM_ID + "=?",
new String[] { iterator.next() }, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
problemNo.add(cursor.getInt(0));
}
cursor.close();
}
db.close();
Set<Integer> set = new TreeSet<Integer>(problemNo);
return set;
}
I know this is not a optimized snippet. And I need to optimize it a lot to reduce the execution time of the query. I did it inside AsyncTask but it is taking too much time.
How can I do this efficiently with faster performance?
You might want to consider taking this out of the database. If you just grabbed all the problems, you could add them all in code. Running one SELECT with 4000 results is still going to be much faster than a thousand SELECT statements.
The approach would be to grab them all, but sorted(ORDER BY problem_id). You could then just check each item in problemIDs against it, and add when you get a match.
You could also use the IN operator as Mathew suggests, but I don't know how efficient that will be with 1000 items in the set.
Don't iterate over a collection of IDs, but use the IN operator in a WHERE condition.
SELECT * FROM Table WHERE problem_id IN (1,2,3,4,5)
This will return all the records in the set. Whereas you are querying them one at a time.
You could try compiling a query, and maybe you can try to load the database into memory before reading.
Create an index on the problem_id column.

Reading a value from a database

I have a database in my app with several columns of which 3 are: _id name selected.
Now, I want to read a single selected value from a row with the name being a string I get from some code. What would be the best way to do this?
Thanks
P.S. I am getting that value to check if it's 0 or 1 (only two possible values), so I want to ask how to make a kind of an if statement in the return field? I have seen some people do it with something resembling this: return true ? ... false
EDIT:
Okay, this is my code atm, haven't checked it yet since I need to do some other things to get it all up, but I think there may be a better way to do this.
public boolean isBandSelected(String name) {
// TODO Auto-generated method stub
Cursor cursor = mDb.query("bands", new String[] { "selected" }, "name="
+ name, null, null, null, null);
int index = cursor.getColumnIndex("selected");
String selected = cursor.getString(index);
return selected == "1";
}
You can use regular expression to match rows whose name field being string. Many databases can support regular expression.
The ternary operator(? :) can be used to make return statement like this.
return value == 0 ? false : true
But it depends on what kind of data type you what to return. Code above returns boolean data type.
The last line of your code above will always return false. This is because the == operator compares the reference of the two objects. you can use:
return "1".equals(selected);

Android do while loop

Hi This my second question here.
I have the following table
|-----|-------|------|------|
|._id.|..INFO.|.DONE.|.LAST.|
|..1..|...A...|...N..|......|
|..2..|...B...|...Y..|..L...|<--- cursor.moveToPosition((int)_id-1);
|..3..|...C...|...Y..|......|
|..4..|...D...|...Y..|......|
|..5..|...E...|...N..|......|
|..6..|...F...|...N..|......|
|-----|-------|------|------|
I use the code:
cursor = db.query(TABLE_NAME, new String[]{INFO,DONE,LAST},null,null,null,null,null);
cursor.moveToPosition((int)_id-1);
String Yval = cursor.getString(cursor.getColumnIndex(DONE));
do
{
cursor.moveToNext();
Yval= cursor.getString(cursor.getColumnIndex(DONE));
}
while (Yval=="Y");
s = Yval;
I initially point the cursor to the LAST row I accessed, then I make a loop to go through the values in the DONE column, not stopping if there are Y's in the row of the column. When an N appears in the loop, the loop should stop.
But it doesn't work.
Yval never equals "Y". So the cursor does one 'moveToNext' and then exits the loop, because it doesn't read Yval as a "Y".
(I also changed everything to integers. 1 for N, and 0 for Y, but it still didn't work)
So what am I doing wrong here?
So you have to use equals() method if you want to compare Strings
while (Yval.equals("Y"));
You should know that:
== tests for reference equality.
equals tests for value equality.
So you want to test if Yval String has Y value so you have to use equals() method.
You approach doesn't work bacause:
String data = "lorem";
data == "lorem" ==> FALSE
data.equals("lorem") == TRUE
Also make sure that your Cursor has valid row so you need to add to condition also cursor.moveToNext() so
cursor.moveToNext() && (Yval.equals("Y")
also you need to treat cursor.moveToPosition((int)_id-1) so add it to condition.
I recommend changing a few things:
if(cursor.moveToPosition((int) _id - 1)) {
int doneIndex = cursor.getColumnIndex(DONE);
String Yval;
do {
Yval = cursor.getString(doneIndex);
} while(Yval.equals("Y") && cursor.moveToNext());
}
You should check if a row exists at position _id - 1 since the SQLite _id is a unique id, not the position of a row in a Cursor.
You only need to fetch the index of the DONE column once, simply store it in a local variable.
As deceiver mentioned, String are tested with equals() and similar methods.
You need consider what happens if all of the rows are "DONE", then you must stop trying to read the Cursor before an out of bounds exception is thrown.

What to do with Cursor after a SQLite query?

This is my first time using a database and I'm not really sure how this works. I made the database and made a query that returns a cursor and... now what? What is a cursor, really? Can I just use that to navigate through my data or do I have to put it in an ArrayList or ListActivity or what?
You need to iterate the cursor to get your results.
Use cursor.moveToFirst() and/or cursor.moveToNext() (with a while loop). Then you can use the getX() method, like cursor.getInt() or cursor.getString().
For example, ir your are expecting one result from your query:
if (cursor.moveToFirst()) {
String name = cursor.getString(cursor.getColumnIndex('NAME'));
int age = cursor.getInt(cursor.getColumnIndex('AGE'));
} else {
// oops nothing found!
}
First call cursor.moveToFirst(). Each time you call cursor.moveToNext() it will move to the next row. Make sure when you are done with your cursor you call cursor.deactivate() or you will get errors in your log cat.
Iterate over the returned Cursor instance
public List<Object[]> cursorToTableRows(Cursor cursor) {
List<Object[]> result = new ArrayList<Object[]>(cursor.getCount());
cursor.move(0);
cursor.moveToNext();
while (cursor.isAfterLast() == false) {
Object[] tableRow = new Object[cursor.getColumnCount()];
for(int i=0; i<cursor.getColumnNames().length; i++) {
int columnIndex = cursor.getColumnIndex(cursor.getColumnName(i));
String columnValue = cursor.getString(columnIndex);
tableRow[i] = columnValue;
}
result.add(tableRow);
cursor.moveToNext();
}
cursor.close();
return result;
}
Then create the desired objects.
public List<Vehicle> getVehicles() {
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Cursor cursor = null;
List<Object[]> objects = cursorToTableRows(cursor);
for(Object[] row : objects) {
int i=0;
Vehicle vehicle = new Vehicle(row[i++].toString(), row[i++].toString()));
vehicles.add(vehicle)
}
return vehicles;
}
from Developer.android: This interface provides random read-write access to the result set returned by a database query.
In other words: query returns you a set of data represented by a cursor. First you need to make sure you got a valid cursor (not null) and then try to move it to desired position in the data set (use moveToXXX methods). In order to obtain data pointed by cursor use getXXX methods. When done using it make sure to call close to release resources.
According to this link it looks like you can iterate through the query return using something like:
cursor.next();
And grab the data at the location you are looking for using:
cursor.getString(0)
After you successfully have your Cursor setup, you would typically want to display that to a view in some form.
Have a look at the following answer for a detailed, but simple example of using a Cursor Adapter to pair up your newly-minted Cursor with your desired XML View:
https://stackoverflow.com/a/20532937/293280

Categories

Resources