i want to get the first 60 rows, than the next 60....
This is my Cursor
final Cursor cursor = myDbSales.searchNamemagic(name, startLong, endLong, limita, limitb);
public Cursor searchNamemagic(String search_str, String startdate, String enddate, String limita , String limitb) {
try {
int firstSpace = search_str.indexOf(" "); // detect the first space character
firstName = search_str.substring(0, firstSpace); // get everything upto the first space character
lastName = search_str.substring(firstSpace).trim(); // get everything after the first space, trimming the spaces off
}catch (Exception c){}
String query = "SELECT * , strftime('%d.%m.%Y %H:%M', datetime(timeStamp, 'unixepoch', 'localtime')) as timecrazy , tastepreis/(tax+100.0)*tax as'"+TAXSUMSEARCHNAME+"', '"+currency+"' as '"+ DOLLA_SIGN+"' FROM salesTable where timeStamp BETWEEN '"+startdate+"' AND '"+enddate+"' AND (sellid LIKE '%"+search_str+"%' OR tastemodel LIKE '%"+search_str+"%' OR bezeichnung LIKE '%"+search_str+"%' OR sellid LIKE '%"+lastName+" "+firstName +"%' ) ORDER BY timeStamp DESC limit '"+limita+"', '"+limitb+"' " ;
Cursor mCursor = dbSales.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
And this is my method
method(name,imyourlist1,"0","60" );
method(name,imyourlist2, "60","120" );
method(name,imyourlist3, "120","180");
method(name,imyourlist4, "180","240");
method(name,imyourlist5, "240","300");
v(name,imyourlist6, "300","360");
method(name,imyourlist7, "360","420");
method(name,imyourlist8, "420","480");
method(name,imyourlist9 ,"480","540");
method(name,imyourlist10 ,"540","600" );
private void method (String name ,ListView imyourlist2, String limita, String limitb){
final Cursor cursor = myDbSales.searchNamemagic(name, startLong, endLong, limita, limitb)
imyourlist1 is correct with 60 Rows but the next ones get more.
For example first one = 0-60 next one 60-more than 120
Is maybe my limit wrong?
You can use this script
SELECT * FROM tableName LIMIT 60 OFFSET 0
Next 60
SELECT * FROM tableName LIMIT 60 OFFSET 1
Page Number is int
SELECT * FROM tableName LIMIT 60 OFFSET Number
Related
I tried to calculate a report and displays the result in the texview "edt1". But it's not displayed.
there is mydatabasehelper :
public void calculrapport(Argent a)
{
db = this.getWritableDatabase();
String query = "select sum(Entree) from Argent where date between \"datedebut\" and \"datefin\" ;";
Cursor cursor = db.rawQuery(query , null) ;
int count = cursor.getCount();
}
There is my class Rapport.java :
public void onOKClick ( View v ) {
if (v.getId() == R.id.okrapport) {
EditText datedebut = (EditText) findViewById(R.id.datedebut);
EditText datefin = (EditText) findViewById(R.id.datefin);
String strdatedebut = datedebut.getText().toString();
String strdatefin = datefin.getText().toString();
Argent a = new Argent();
helper.calculrapport(a);
edt1.setText( );
}
}
Thanks in advance.
Assuming that the query works as expected (especially considering that variables used have the appropriate scope, which would appear unlikely perhaps try using select sum(Entree) from Argent to test without the complications of wheteher or not the datedebut and datefin variables can resolve and if so resolve to usable values) then you need to :-
Extract the appropriate value and return the value from the method and then use the returned value to set the text in the TextView.
To return the value the method should not be void, but have an appropriate return type (String will be used for the example),
so instead of public void calculrapport(Argent a), use public String calculrapport(Argent a) (thus the method will be required to return a string)
To extract the value the cursor needs to be moved to the appropriate row (there should only be the one row as the sum function is an aggregate function and there is only the one group (aggregate functions work on gropus) i.e. all rows)
As such the method could be :-
public String calculrapport(Argent a)
{
String rv = "0"; //<<<< used to return 0 if no rows are selected by the query
db = this.getWritableDatabase();
String query = "select sum(Entree) from Argent where date between \"datedebut\" and \"datefin\" ;";
Cursor cursor = db.rawQuery(query , null) ;
if (cursor.moveToFirst()) {
rv = cursor.getString(0); //<<<< get the value from the 1st (only) column
}
cursor.close(); //<<<< Cursors should always be closed when done with
return rv;
}
To set the TextView with the returned value instead of using :-
helper.calculrapport(a);
edt1.setText( );
Use :-
edt1.setText(helper.calculrapport(a));
Or :-
String sum = helper.calculrapport(a);
edt1.setText(sum);
Additional re comment:-
The problem is located in the SQlite query (select sum(Entree) from
Argent where date between \"datedebut\" and \"datefin\" ;) exactly
when we call "datedebut" and "datefin" taht located in the class
rapport.java
Then String query = "select sum(Entree) from Argent where date between \"datedebut\" and \"datefin\" ;";
resolves to :-
select sum(Entree) from Argent where date between "datedebut" and "datefin" ;
I believe, assuming that datedebut and datefin are string variables, and that they are in a valid SQLite date format e.g. they could be 2018-01-01 and 2018-02-01 (and that values in the date column are formatted as a valid SQLite date format) that you should instead be using :-
String query = "select sum(Entree) from Argent where date between '" + datedebut + "' and '" + datefin +"' ;";
Which would then resolve to something like :-
SELECT sum(entree) FROM argent WHERE date BETWEEN '2018-01-01' AND '2018-02-01';
For valid SQLite date formats; refer to Date And Time Functions
Note the above is in-principle code and has not been tested so may contain some simple typing errors.
The query below should have only returned the numbers 0 through 8. However, the result are 0 thru 87. and 88 thru 99 are not shown. The next numbers shown are 100 thru 799. 800 thru 999 are not shown. So I see a pattern here, and it is that if the first number is within the range specified it is returned.
public Cursor getList(String user) {
String zero = "0";
String query = ("SELECT * FROM flavors WHERE inventory >= "+zero+" AND inventory <= "+user);
return mDb.rawQuery(query, null);
How can I keep the expected results withing the query parameters?
Thanks for all your efforts.
EDIT
For anyone that are looking for an answer as I was. Here is the final working statement.
Thanks to #FAT I was able to learn more about the sql query process from the links that where provided. Googling is an art it seems. I changed my code to meet my needs as follows.
public Cursor getList(String user) {
String zero = "0";
String query = ("SELECT * FROM flavors WHERE inventory != '' AND (cast(inventory as real)) >= " + zero + " AND (cast(inventory as real)) <= " + user);
return mDb.rawQuery(query, null);
}
The "cast" was the key to getting the string to be used to compare the two numbers. I also learned that you can exclude all null items. By adding "!= '', only the items that had an entry where returned in accordance with the statement. This even works for decimal numbers such as 5.5 or .5 etc.
You can't compare String value using >= or <=. Try using int value instead of string. For this case your column inventory should be int type.
Try this:
public Cursor getList(int user) {
int zero = 0;
String query = ("SELECT * FROM flavors WHERE inventory >= " + zero + " AND inventory <= " + user);
return mDb.rawQuery(query, null);
}
You can use BETWEEN like the following:
SELECT * FROM flavors WHERE inventory BETWEEN X AND Y
I would like to implement a SQL-Query that gives me a range of entries. Example:
public List<Entry> getEntries(int lowerValue, int upperValue){
//Select upper - lower entries.
}
getEntries(0, 20) --> First 20 Entries
getEntries(21, 40) --> Entry 21 to 40
getEntries(12, 200) --> Entry 12 to 200
At the moment I get all entries like this:
public List<Log> getLogs(){
List<Log> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_LOGS + " WHERE 1";
//Cursor points to a location in your results
Cursor c = db.rawQuery(query, null);
//Move to the first row in your results
c.moveToFirst();
//Position after the last row means the end of the results
while (!c.isAfterLast()) {
if (c.getString(c.getColumnIndex("type")) != null) {
int id = c.getInt(c.getColumnIndex("_id"));
int type = c.getInt(c.getColumnIndex("type"));
long date = c.getLong(c.getColumnIndex("date"));
int refId = c.getInt(c.getColumnIndex("refId"));
String extra = c.getString(c.getColumnIndex("extra"));
list.add(new Log(id, type, date, refId, extra));
}
c.moveToNext();
}
db.close();
c.close();
return list;
}
I know there is a LIMIT clause, but that starts always from the first entry.
What you need is the combination of LIMIT and OFFSET
You could use
LIMIT <skip>, <count>
or
LIMIT <count> OFFSET <skip>
So some examples would be
"SELECT * FROM " + TABLE_LOGS + " WHERE type=1 LIMIT 20 OFFSET 0"
"SELECT * FROM " + TABLE_LOGS + " WHERE type=1 LIMIT 20 OFFSET 20"
"SELECT * FROM " + TABLE_LOGS + " WHERE type=1 LIMIT 20 OFFSET 40"
Hope this helps.
I have a table with events, and want to select all events which happen from three days ago. (The events do belong to categories which is a field in the Article table which has to description etc., but that works).
This is my code:
public List<Event> findByCategory(long catId, int start, int count) throws Exception {
String limit = "";
if (count > 0) limit = start + "," + count;
SQLiteQueryBuilder _QB = new SQLiteQueryBuilder();
_QB.setTables("Event e INNER JOIN Article a ON e.articleId=a.id");
String[] rows = _fields.keySet().toArray(new String[0]);
for (int i = 0; i < rows.length; i++) {
rows[i] = "e." + rows[i];
}
Cursor cursor = _QB.query(_db, rows, "date(e.startTime) > date('now','-3 days') AND EXISTS(SELECT * FROM CategoryArticleLink WHERE CategoryArticleLink.articleId = a.id AND EXISTS (SELECT * FROM Category WHERE Category.id = CategoryArticleLink.categoryId AND Category.id = '" + catId + "'))", null, null, null, "e.startTime ASC", limit);
List<Event> list = new ArrayList<>(cursor.getCount());
if (cursor.moveToFirst()) {
do {
Event item = getObject(cursor);
list.add(item);
} while (cursor.moveToNext());
}
cursor.close();
return list;
}
The resulting Query is:
SQLiteQuery: SELECT e.articleId, e.keynote, e.locationId, e.id, e.finishTime, e.startTime, e.languageCode, e.flag, e.lastUpdate FROM Event e INNER JOIN Article a ON e.articleId=a.id WHERE (date(e.startTime) > date('now','-3 days') AND EXISTS(SELECT * FROM CategoryArticleLink WHERE CategoryArticleLink.articleId = a.id AND EXISTS (SELECT * FROM Category WHERE Category.id = CategoryArticleLink.categoryId AND Category.id = '9'))) ORDER BY e.startTime ASC LIMIT 0,8
This returns an empty result set. However, if I take the date selection (date(e.startTime) > date('now','-3 days')) out of the query it returns all records as expected. So I must be doing something small wrong, but I just don't see what.
The field type on database generation is 'DATE', so that should be ok I expect.
The correct code in my setup is 'date(e.startTime / 1000, 'unixepoch') > date('now','-3 day')'. I use Date().getTime() to save the date/time as a long. But have uses a timestamp a 1000x larger then normal.
Moreover, the 'unixepoch' seems to be a needed addition in the date function.
I'm trying to retrieve the sum of a column from SQLITE. I am able to successfully get it.
But when I try to retrieve just the sum of 10 rows, it returns the sum of the entire column again. The query seems to be correct though.
public String getUnitsForWeek(Context context) throws IOException {
DataBaseHelper dbHelper = new DataBaseHelper(context);
String query = "SELECT sum(UNITS) FROM SERVICE_TABLE order by id DESC limit 7";
return String.valueOf(dbHelper.getString(query));
}
The dbHelper.getString method is:
public int getString(String query) {
String mypath = DB_PATH + DB_NAME;
SQLiteDatabase database = SQLiteDatabase.openDatabase(mypath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor cursor = null;
int i;
cursor = database.rawQuery(query, null);
cursor.moveToFirst();
i= cursor.getInt(cursor.getColumnIndex(cursor.getColumnName(0)));
return i;
}
Thanks.
SUM is an aggregate function that combines data from many rows into one. Since there is only one result row, LIMIT and ORDER BY are meaningless.
To sum UNITS on the 7 rows with highest ID, you can use a subselect:
SELECT SUM(UNITS) FROM (SELECT UNITS FROM SERVICE_TABLE ORDER BY id DESC LIMIT 7);
Can't you do a subelect?
SELECT sum(UNITS) FROM (SELECT UNITS FROM SERVICE_TABLE order by id DESC limit 7) s