when we select data from mysql database and show it in list view, then the 1st data of the database showed in the first of the list.
I want to show the first data in the last of the listView and last data in the first of the list.
Is there any method to do it?
Use this..
SQLiteDatabase sqLiteDatabase=dbHelper.getReadableDatabase();
String query = "select * from " + TABLE_NAME;
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
cursor.moveToLast();
while (cursor.moveToPrevious())
{
//Your code here
.
.
.
}
Related
Good evening everyone
Brief overview before a greater explanation. I currently have a SQL database which feeds into an arraylist thanks to a modal, we then feed this arraylist to our recycle view adapter which then populates the row.
Now i'm trying to build in the option for the user to select a row and then a check becomes true and tick is displayed. As you all currently know if the state is not stored then it start moving to random rows or being removed completely.
Lets start at the beginning with my SQL Lite database. Three simple rows Title , Description and checkbox state. Note that when a new row is added to the sql he checkbox column is automatically set to false.
Snippet below of the SQL query used to populate my recyclerView adapter
ArrayList<NoteInfoModal> noteInfoModalArrayList = new ArrayList<>();
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + Primary_Table + " ORDER BY Col_DateOrder ASC", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()){
NoteInfoModal noteInfoModal = new NoteInfoModal();
noteInfoModal.setNoteName(cursor.getString(cursor.getColumnIndex(Col_NoteTitle)));
Applying it to the adapter
homeScreenAdapter = new HomeScreenAdapter(getContext(), primaryDatabase.populateHomeScreenOldestFirst(), filterOption, HomeScreenFragment.this);
Finally binding the information inside the adapter to the correct view (This one is for the check box)
((CustomViewHolder) holder).chkNote.setChecked(Boolean.valueOf(noteInfoModal.noteCheckBox));
Now I understand that I could simply update the row of the SQL DB to be true as this will then save the state, but if the user closes and then opens the app again I want them all to unchecked / false each time
Just looking for another way of approaching this issue.
Thank you
I thought I would input the current way in which I have resolved the issue.
Now when the user click a check box it will update the SQL to become true or false and because I want all results to be false upon app reopening I have implemented a small section of SQL Lite code which will set a column to false for me.
public boolean checkboxStateColumn ()
{
SQLiteDatabase db = this.getReadableDatabase();
ContentValues args = new ContentValues();
args.put(Col_CheckedRow, "false");
int i = db.update(Primary_Table, args, Col_CheckedRow + "=" + Col_CheckedRow , null);
return i > 0;
}
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.
I have large number of strings, approximately 15,000 that I stored in a SQLite database using the following code:
void addKey(String key, String value, String table) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_KEY, key); // Contact Name
values.put(KEY_VALUE, value); // Contact Phone
// Inserting Row
db.insert(table, null, values);
db.close(); // Closing database connection
}
And then i search through that database using the following method in order to pick out any strings that match the key im looking for:
public String searchKeyString(String key, String table){
String rtn = "";
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Log.d("searchKeyString","searching");
if(cursor.getString(1).equals(key))
rtn = rtn + "," + cursor.getString(2);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
Log.d("searchKeyString","finish search");
return rtn;
}
The goal is to do this in real time as the user is typing on the keep board so response time is key and the way it stands now it takes over a second to run through the search.
I considered reading all of the items into an array list initially and sorting through that which might be faster, but i thought an array list of that size might cause memory issues. What is the best way to search through these entries in my database?
A couple of things you can do...
Change the return to a StringBuilder until the end.
Only use a readable version of the database (that's probably not making much difference though)
Do not get a new instance of the database every time, keep it opened until you don't need it anymore
Query for only what you need with the "WHERE" argument in the SQL query.
See the code below with some changes:
// move this somewhere else in your Activity or such
SQLiteDatabase db = this.getReadableDatabase();
public String searchKeyString(String key, String table){
StringBuilder rtn = new StringBuilder();
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table + " WHERE KEY_KEY=?";
Cursor cursor = db.rawQuery(selectQuery, new String[] {key});
// you can change it to
// db.rawQuery("SELECT * FROM "+table+" WHERE KEY_KEY LIKE ?", new String[] {key+"%"});
// if you want to get everything starting with that key value
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Log.d("searchKeyString","searching");
rtn.append(",").append(cursor.getString(2));
} while (cursor.moveToNext());
}
cursor.close();
Log.d("searchKeyString","finish search");
return rtn.toString();
}
Note even if you want this to happen in "real-time" for the user, you will still need to move this to a separate Thread or ASyncTask or you are going to run into problems....
You should consider using SELECT * FROM your-table LIMIT 50, for example. And you can put two buttons "Back", "Next" on your view. If every page has max 50 items, the user is at page 1, and he taps "Next", then you can use this query:
SELECT * FROM your-table LIMIT 50 OFFSET 50
If your table contains most of text-data, and you want to integrate search deeply into your app, consider using virtual table with FTS.
Let sqlite do the hard lifting.
First off, add an index to the field you're searching for, if you don't have one already. Secondly, don't do a SELECT all with manual table scan, but rather use a query in the form
SELECT column_value
FROM my_table
WHERE column_key LIKE "ABC%"
This returns the least amount of data, and the sql engine uses the index.
i dunno about better but maybe it'd be faster to make queries for the selected strings one by one.
public String searchKeyString(String key, String table){
String rtn = "";
Log.d("searchKeyString",table);
// Select All Query
String selectQuery = "SELECT * FROM " + table + "WHERE column_1 = " + key;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
rtn = rtn + "," + cursor.getString(2);
}
cursor.close();
db.close();
Log.d("searchKeyString","finish search");
return rtn;
}
EDIT:
Well i dunno how those custom keyboard apps do it, but those AutoCompleteTextViews are hooked up to adapters. you could just as easily make a cursorAdapter and hook your auto-complete view to it.
http://www.outofwhatbox.com/blog/2010/11/android-autocompletetextview-sqlite-and-dependent-fields/
http://www.opgenorth.net/blog/2011/09/06/using-autocompletetextview-and-simplecursoradapter-2/
I have an activity which has two edit text fields: one for the title and the other for the story.
The entries made two text fields are saved in the database, also the database has a ROW_ID,TITLE_ID and STORY_ID. The entries are displayed in a list view.
When an item is long clicked, I get the row id corresponding to that item.
How should I get the TITLE_ID and STORY_ID from this?
Say, you have the corresponing row id of item which is long clicked in a variable rid. Then run the following query:
String q = "SELECT * FROM TABLE_NAME where(ROW_ID like '"+rid+"')";
Cursor c = db.rawQuery(q, null); // db is a object of SQLiteDatabase type
Then retrieve TITLE_ID and STORY_ID like:
if(c.getCount() == 0)
{
//No entry found
}
else {
c.moveToFirst();
do {
String titleid = c.getString(c.getColumnIndex("TITLE_ID"));
String storyid = c.getString(c.getColumnIndex("STORY_ID"));
} while (c.moveToNext());
c.close();
Then use them as you like :)
You could query the data base for the TITLE_ID and STORY_ID that correspond to the ROW_ID.
Post what code you have and we will be able to give more specific answers.
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();