Asccending order by column name using cursor - android

Android Studio 0.4.6
Hello,
I have the following function that should get the rows of the database in ASC order based on the column name. However it just gets the rows in the order that they are listed in the database.
So it should be in alphabetical order for names in the database.
I think my cursor query is correct, as in the debugger the cursor value is:
SQLiteQuery: SELECT _id, name, phone, email FROM friends ORDER BY name ASC
Which is what I want. I then set my cursor to the first row and loop over over them until I get to the last row.
However, it doesn't display in the alphabetical for name.
private void loadDB() {
Cursor cursor = db.query(FriendContract.TABLE,
new String[] {FriendContract.Column.ID, FriendContract.Column.NAME, FriendContract.Column.PHONE, FriendContract.Column.EMAIL},
null, null, null, null, FriendContract.Column.NAME + " ASC");
/* Check if database is empty */
if(cursor.getCount() == 0) {
/* There are no rows to load - so just return */
Log.d(TAG, "loadDB() cursor.getCount() == 0. There are no rows, just just refresh listview");
adapter.notifyDataSetChanged();
return;
}
/* Clear all items from array list -
we are going to fill this with the content of the database */
friendsList.clear();
Friend friend;
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
friend = new Friend();
friend.setId(cursor.getLong(0));
friend.setName(cursor.getString(1));
friend.setPhone(cursor.getString(2));
friend.setEmail(cursor.getString(3));
/* Add this to the list of friends */
friendsList.add(friend);
cursor.moveToNext();
}
/* Clean up */
cursor.close();
/* Refresh the listview with the loaded friends */
adapter.notifyDataSetChanged();
}

The code my above question is working as expected.

Related

CursorIndexOutOfBoundsException on SQLite get

I want to get data from an SQLite table and I know that table will always have only one record. I'm trying to do that get using:
public User_Token getUser_TokenDB() {
String sql = "SELECT * FROM " + TABLE_NAME_USER_TOKEN +" WHERE ID = " + 1;
Cursor cursor = this.database.rawQuery(sql, null);
User_Token auxUserToken = new User_Token(
cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3));
return auxUserToken;
}
But I always get:
'java.lang.RuntimeException: Unable to start activity ComponentInfo{com.support.android.iplfit/com.support.android.iplfit.Activities.MainActivity}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0'.
The only way I can access this information is by returning an array of Tokens and do .get(0) but I feel like it is not the right way, since it has no sense to return an array of only one object.
The cursor index starts out of bounds. You need to use Cursor#moveToFirst() which moves the cursor to the 0 index and returns true if there are items in the cursor.
So something like this:
if (cursor.moveToFirst()) {
// Cursor has items and is ready for extraction
} else {
// Cursor has no items.
}
You need to move cursor at first row before you can get data from it. Call moveToNext method before accessing data from cursor
while(cursor.MoveToNext()) {
User_Token auxUserToken = new User_Token(
cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3));
}
You aren't moving to a position within the cursor, thus the location is before any rows i.e. -1.
You need to move to a row and in your case you want the first row (not that there are any (i.e. the message says size of 0)) and only if the move can be made do you want to extract data. Otherwise you would handle no data available.
The Cursor move???? methods (moveToFirst, moveToLast, moveToNext, moveToPrevious, moveToPosition) all return true if the move can be made, otherwise false.
So your code code be :-
Cursor cursor = this.database.rawQuery(sql, null);
if (cursor.moveToFirst) {
User_Token auxUserToken = new User_Token(
cursor.getLong(0),
cursor.getString(1),
cursor.getString(2),
cursor.getString(3));
} else {
return null; //???? handle no data how you want perhaps null.
}
return auxUserToken;
As a note it's inadvisable to generally use column offsets, rather the more common way is to get the offset according to the column name using getColumnIndex(column_name). So (assuming the column name is id) would be to replace cursor.getLong(0) with cursor.getLong(cursor.getColumnIndex("id")

Retrieve the contents of first three rows of a android database using a cursor

Currently in my code i'm using a cursor to retrieve the entire database
My code is
public Cursor getAll() {
return (getReadableDatabase().rawQuery(
"SELECT _id, note, amt, dueDate FROM New", null));
}
The function of retrieving the contents is to populate the same in a listview.
Now I want to retrieve the contents of the first three rows of the same database using cursor to display in another listview.
Need Help, Thanks in Advance.
The correct way to do it is to limit the result number to three:
"SELECT _id, note, amt, dueDate FROM New ORDER BY _id LIMIT 3"
Then you just iterate over the cursor (as usual)
Since you've already obtained a Cursor, in order to get the first three rows of the result, you do this:
Cursor cursor = getAll();
cursor.moveToFirst();
int count = 0;
while(!cursor.isAfterLast() && count < 3)
{
// Grab your data here using cursor.getLong(0), cursor.getString(1) etc.
// and store it an array.
count++;
cursor.moveToNext();
}
cursor.close();
You may want to limit the query results to at most three by adding a LIMIT 0,3 statement to your SQL. Having obtained an array of at most three elements containing your records, you can then proceed to place them in the other ListView you are referring to. You do this by adding them to this ListView's source array. Then call the ListView adapter's notifyDataSetChanged method to have it update itself.
So you can do this in two ways:
Create a separate select:
SELECT * FROM Table_Name LIMIT 3;
Select three rows from cursor:
int n = 0;
cursor.moveToFirst();
while (!cur.isAfterLast() && n < 3) {
// Use the data
n++;
cur.moveToNext();
}
cur.close();

When selecting all rows from android sqlite database for an application, it is returning the last entry for all the entries

I am currently working on an android application. I have a sqlite database that stores text (that I just use as strings in my application) in four columns. I am trying to return all of the rows and columns from the table. I have created and inserted data into the table and verified it is there using sqlite3 from the adb shell. I use the same statement as I use in my program and it returns all the rows with all of the correct data. In my program I store all of the data in an ArrayList<ArrayList<String>> format by iterating through the cursor. It returns the correct number of ArrayList<String> that corresponds to the rows, but they all have the information from only the last row. Here is my code:
private static final String SELECT = "SELECT * FROM " + TABLE_NAME;
public ArrayList<ArrayList<String>> allRecipes()
{
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
ArrayList<String> recipe = new ArrayList<String>();
Cursor cursor = db.rawQuery(SELECT, null);
if(cursor.moveToFirst())
{
do
{
recipe.clear();
recipe.add(cursor.getString(1));
recipe.add(cursor.getString(2));
recipe.add(cursor.getString(3));
recipe.add(cursor.getString(4));
results.add(recipe);
}while(cursor.moveToNext());
if(cursor != null && !cursor.isClosed())
cursor.close();
}
return results;
}
I then iterate through the ArrayLists in another part of my program and all of the information contained is just duplicates of the last row entered into the table. I have checked the ArrayLists in my other method as soon as it receives it, and they are all the same, so I am assuming it must be an issue in this code segment somehow. I have also tried the select statement with group by and order by clauses and it still does not work. Using the db.query() with correct parameters causes the same issues as well.
It happens because you add link to recipe in your array list, and change values of recipe on every iteration in cycle.
You should change code to this one
public ArrayList<ArrayList<String>> allRecipes()
{
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
Cursor cursor = db.rawQuery(SELECT, null);
if(cursor.moveToFirst())
{
do
{
ArrayList<String> recipe = new ArrayList<String>();
recipe.add(cursor.getString(1));
recipe.add(cursor.getString(2));
recipe.add(cursor.getString(3));
recipe.add(cursor.getString(4));
results.add(recipe);
}while(cursor.moveToNext());
if(cursor != null && !cursor.isClosed())
cursor.close();
}
return results;
}

how to retrieve particular records from SQLite in android

I need to get data from DB & displayed it as list with pagination.
i.e. If i retrieved 4 items..i need to display first 2 items in first page.
When i click next button.,remaining 2 items should be displayed which replaces old 2.
How could i restrict data from DB as 2 like that?
My code..
db.open();
// db.insertTitle("Money");
//db.insertTitle("make");
//db.insertTitle("make");
//db.insertTitle("make");
Cursor c = db.getAllTitles();
if (c.moveToFirst())
{
do {
String firstName = c.getString(c.getColumnIndex("user"));
results.add( firstName );
} while (c.moveToNext());
}
setListAdapter(new ArrayAdapter<String>(DisplayAll.this, android.R.layout.simple_list_item_1,results));
db.close();
}
My DBAdapter..
public Cursor getAllTitles()
{
return db.query(DATABASE_TABLE, new String[]
{
KEY_ROWID,
KEY_USER,
},
null,
null,
null,
null,
null);
}
Please try this
public Cursor getAllRecords(int page,int totalRecord)
{
return db.rawQuery("select * from your_table_name limit "+(page-1)*totalRecord+","+totalRecord, null);
}
Where limit = how many record you want at a time if you want 2 record then pass limit = 2 if 10 record then set limit = 10..
and page = first initial page variable with 1 and when second time you fetch next record increase your page variable by 1 .

Cursor returns zero rows from query to table

I've created an SQLiteDatabase in my app and populated it with some data. I can connect to my AVD with a terminal and when I issue select * from articles; I get a list of all the rows in my table and everything looks fine. However, in my code when I query my table, I get a cursor back that has my tables columns, but zero rows of data. Here is my code..
mDbHelper.open();
Cursor articles = mDbHelper.fetchAllArticles();
startManagingCursor(articles);
Cursor feeds = mDbHelper.fetchAllFeeds();
startManagingCursor(feeds);
mDbHelper.close();
int titleColumn = articles.getColumnIndex("title");
int feedIdColumn = articles.getColumnIndex("feed_id");
int feedTitleColumn = feeds.getColumnIndex("title");
/* Check if our result was valid. */
if (articles != null) {
int count = articles.getCount();
/* Check if at least one Result was returned. */
if (articles.moveToFirst()) {
In the above code, my Cursor articles returns with my 4 columns, but when I call getCount() it returns zero, even though I can see hundreds of rows of data in that table from command line. Any idea what I might be doing wrong here?
Also.. here is my code for fetchAllArticles..
public Cursor fetchAllArticles() {
return mDb.query(ARTICLES_TABLE, new String[] {ARTICLE_KEY_ROWID, ARTICLE_KEY_FEED_ID, ARTICLE_KEY_TITLE,
ARTICLE_KEY_URL}, null, null, null, null, null);
}
try moving mDbHelper.close(); to the end
Also - could you post fetch method src ?

Categories

Resources