Select last row - android

Please how can I retrieve the last on an Android DB? I'm using the Sugar ORM library to abstract all db operation but I can't seem to be able to figure out how to retrieve the oldest record on the db.

You have to order by some timestamp, if you have it, or by the ID, if it is autoincrementing, and take only the first result:
Thing.find(Thing.class, null, null, null, "timestamp DESC", "1");

The basic algorithm is
Get a list of all objects from the database
Take the one with the "maximum" date
I'm unfamiliar with Sugar ORM, so I don't know how to do this with that particular library other than coding it myself. The SQL query for this would be fairly straight forward.

Related

Android SQLite ORDER BY query won't process

Ok, so I have a database of an accounting app, which contains the information of various items purchased.
Said database looks like this:
Unsorted SQLite database
Upon running the query SELECT * FROM items ORDER BY totalPrice DESC; in SQLite Studio 3.1.1, the db sorts itself cleanly to this:
Updated database
However, trying to run mDatabase.rawQuery("SELECT * FROM items ORDER BY totalPrice DESC;") via the Java SQLite library results in nothing. The db isn't sorted at all. I've also tried running mDatabase.query("items", null, null, null, null, null, "totalPrice DESC;");
I'm at a complete loss as to what to do for this problem. Any help is appreciated.
The command doesn't seem to go through, the database remains the same as the top picture.
A SELECT statement does not change the database. It returns data from the database. The Cursor that you get back from rawQuery() or query() will have the rows in its result set sorted per the ORDER BY clause. The actual database, though, will remain untouched.

Accelerate the insertion into Sqlite datatbase Android?

I use this function to insert data into the SQLite Android data base:
public long insertAccount(String code,String name,int s3,int s4,String s5,String s6,int s7,
int s8,int s9,int s10,int s11,String s12,String s13,int s14,int s15,int s16) {
//container and place in it the information you want inserted, updated, etc.
ContentValues initialValues = new ContentValues();
initialValues.put(Code, code);
initialValues.put(Name,name);
initialValues.put(Type, s3);
initialValues.put(Level1, s4);
initialValues.put(Father, s5);
initialValues.put(ACCCurr,s6);
initialValues.put(AccNat, s7);
initialValues.put(LowLevel, s8);
initialValues.put(DefNum, s9);
initialValues.put(AccClass, s10);
initialValues.put(SubClass, s11);
initialValues.put(SSClass1, s12);
initialValues.put(SSClass2, s13);
initialValues.put(Stype1, s14);
initialValues.put(Stype2, s15);
initialValues.put(Stype3, s16);
return db.insert(DATABASE_TABLE, null, initialValues);
}
But this takes much time when inserting about 70,000+ rows! How can I accelerate the process of insertion into the data base, and after the insert is done, how can I apply Update on it?
Some options:
Prepopulate your database. See "Ship an application with a database"
Use transactions to reduce the time waiting for I/O. See e.g. "Android SQLite database: slow insertion". Likely you cannot wrap all 70k rows in a single transaction but something like 100..1000 inserts per transaction should be doable, cutting the cumulative I/O wait time by orders of magnitude.
Inserting into SQLlite android using PHP? how is it possible using php in android phone, I am sorry I didn't got this.
Anyways I believe you have written the java code up here and you have like 7k+ records that you want to insert in your db.
The style of inserting a bulk of records in any db is called "Bulk Inserts", the idea is to create as less number of transactions as possible and rather do all the inserts in one shot; In case of relational db's like sql server and oracle its done by specific api's as well, but in sqllite the plain old idea is to make a single transaction with a bunch of data
check out this article which uses the same technique http://www.techrepublic.com/blog/software-engineer/turbocharge-your-sqlite-inserts-on-android/ and also explains it quite well.
You have to use transaction to done insertion in 1 time. you can use this:
//before insertion
db.beginTransaction();
//====do insertion
//after insertion
db.setTransactionSuccessful()
db.endTransaction();

How to extract records in a sequential manner, from a table in Sqlite?

I have a table in Sqlite which contains three components for each record (eg A, ​​B, C), and the primary key (id) is random. I would like a SQL query that extracts each record sequentially, as if you were applying a loop to the database.
I know there is a clause like LIMIT but it only returns the first element (LIMIT 1) instead, two elements (LIMIT 2) ... but I want to extract a record, and process it and move on to another. Recalling that the id is random.
It is not ideal to write the queries by hand as methods have been provided to generate safe queries.
database.query(DATABASE_TABLE, new String[] {ROW_ID, ROW_COLUMN_ONE, ROW_COLUMN_TWO, ... }, null, null, null, null, new String[] {ROW_ID});
This will return all rows in your database ordered by the ROW_ID column.
This site might be of further use as it covers some common use cases for SQLite implementation.
http://www.vogella.com/articles/AndroidSQLite/article.html
What kind of processing?
If you want to update or alter the data in some way, you can probably do it within SQL, but it sounds like you have something more complicated in mind that just "UPDATE table SET value_column = value WHERE key_column = key".
If that's the case you will need to extract the records and iterate through them in java. Take a look at android.database.*.

Can't manage an instance of Cursor for my SQLite database

I've successfully copied an existing SQLite database to android, as it was recommended here http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
and now when i'm writing
Cursor cur = db.db.query("student",
null, null, null, null, null, null);
The app breaks trying to create a cursor. I'm sure there is a "student" table.
Could you help me with suggesting any reasons of why this happens, please?
I just guessing, but db.db.query() looks wrong... you sure you didn't mean db.query() ?
A more collaborative answer than my comment. I would think you'll be fine by doing something like this tutorial does http://droidreign.com/2010/10/dev-tutorials-android-sqlite-database-basics/ . About half the way down is the part you are looking for.
Edit: I guess the problem with your query is that you ask for none of the columns (second parameter in your query). It should probably be at least one of your columns.

how add limit clause to manageQuery on android

Android's API provides a clean mechanism via SQLite to make queries into the contact list. However, I am not sure how to limit the results:
Cursor cur = ((Activity)mCtx).managedQuery(
People.CONTENT_URI,
columns,
"LIMIT ? OFFSET ?",
new String[] { Integer.toString(limit), Integer.toString(offset) },
null
);
Doesn't work.
Actually, depending on the provider you can append a limit to the URI as follows:
uri.buildUpon().appendQueryParameter("limit", "40").build()
I know the MediaProvider handles this and from looking at recent code it seems you can do it with contacts too.
You are accessing a ContentProvider, not SQLite, when you query the Contacts ContentProvider. The ContentProvider interface does not support a LIMIT clause directly.
If you are directly accessing a SQLite database of your own, use the rawQuery() method on SQLiteDatabase and add a LIMIT clause.
I found out from this bug that Android uses the following regex to parse the LIMIT clause of a query:
From <framework/base/core/java/android/database/sqlite/SQLiteQueryBuilder.java>
LIMIT clause is checked with following sLimitPattern.
private static final Pattern sLimitPattern = Pattern.compile("\\s*\\d+\\s*(,\\s*\\d+\\s*)?");
Note that the regex does accept the format offsetNumber,limitNumber even though it doesn't accept the OFFSET statement directly.
I think you have to do this sort of manually. The Cursor object that is returned from the managedQuery call doesn't execute a full query right off. You have to use the Cursor.move*() methods to jump around the result set.
If you want to limit it, then create your own limit while looping through the results. If you need paging, then you can use the Cursor.moveToPosition(startIndex) and start reading from there.
You can specify the "limit" parameter in the "order" parameter, maybe even inside other parameters if you don't want to sort, because you'll have to specify a column to sort by then:
mContentResolver.query(uri, columnNames, null, null, "id LIMIT 1");

Categories

Resources