Android: Select data from SQLite database - advice - android

Please give me advice, what is the efficient way to select data from database if I have query like SELECT * FROM order_list WHERE order_number = ? In table I have more entries (in my case) with common order number and I'd like to create List for entries with same order number and then shot it in ListView. I don't know if it is efficient first select all order numbers and then in foreach loop select and create List<Item> or exists something better. I've tried find some example but unsuccessfully. How should I solve this problem? Thank you. I appreciate every help.

You can use the same you are thinking like this:
"select col1,col2,col3 from table WHERE order_number = ? ", new String[]{YOUR_VARIABLE_HERE};
For example:
public Object[] getData(String Id) {
Cursor c = null;
ArrayList<String> arrayListProductName = new ArrayList<String>();
ArrayList<String> arrayListProductId = new ArrayList<String>();
db=helper.getWritableDatabase();
c = db.rawQuery("select distinct Column1,Column2 from Table1inner join Table2 on Table1.anyId = Table2.anyId Table2.Id = ?", new String[]{Id});
c.moveToFirst();
while(!c.isAfterLast())
{
arrayListProductName.add(c.getString(c.getColumnIndex("Column1")));
arrayListProductId.add(c.getString(c.getColumnIndex("Column2 ")));
c.moveToNext();
}
c.close();
db.close();
return new Object[]{arrayListProductName,arrayListProductId};
}
And in your Activity class:
helper = new YourDatabaseHelper(this);
Object[] objectScheme = merchandisingHelper.getData(retId);
arrayListSchemeProductName = (ArrayList<String>) objectScheme[0];
arrayListSchemeProductId = (ArrayList<String>) objectScheme[1];
Hope this will help you.
Thanks

Use GROUPBY in SQL
SELECT *
FROM table_name
WHERE column_name = yourvalue
GROUP BY your_columnname
The GROUP BY is used in conjunction with the aggregate functions to group the result-set by one or more columns. In your case it will group your records based on your order number.After grouped you can assign to your list view or what ever you want.

If I understand correctly you want to know if it's more efficient to :
filter using a WHERE order_number = ? clause
load everything, then filter in a loop.
Then 1 is a much better solution, it will avoid a lot of unnecessary object creation. If you have a lot of rows it may be interesting to add an index on the order_number column.
If you want to show the result in a Listview the best solution is to connect the SQLiteCursor to the ListView, using a SimpleCursorAdapter.
This is very efficient because you only have to load data when the ListView needs it.

Related

Android SQLite get youngest person from database

I have a Person object that I store in a SQLite database.
Person has Age, FirstName, and LastName.
At a given moment, I want to find the youngest person (lowest Age).
How can I do this?
So far I have this:
public Person getYoungest(Cursor c) {
c.moveToFirst();
db.rawQuery("SELECT MIN(" + AGE + ") FROM " + PERSON_TABLE, null);
// Person youngestPerson = ???
// return youngestPerson;
}
However, I'm really confused at what the "rawQuery" does. It doesn't return a person object. Also, I'm not sure whether the query gives me the lowest "age", or the record containing the lowest "age" (which is what I want). I'm very new to SQL, so this is all strange to me.
Any advice?
What you are currently doing is querying for smallest age value from your dataset. If you want to get the whole data row of such you need to use ORDER BY, like
SELECT * FROM ... ORDER BY age ASC LIMIT 1
which would sort the data by Age in ascending order. As you want just one we use LIMIT to ensure this is going that way (and to make things faster), yet note that most likely many records may have the same age (incl. lowest value) so you may extend ORDER BY to fine tune sorting.
SQLite returns strings, numbers, byte arrays.
They are not like java-objects. You have to retrieve your each value and initialize your person in the code using a constructor.
Or use realm database that easily helps to store java-objects using sqlite.
do not forget to improve the performance by using
SELECT * FROM ... LIMIT 1
like Marcin Orlowski said.
to retrieve the data use this:
if (c.moveToFirst()) {
int idColIndex = c.getColumnIndex("id");
int nameColIndex = c.getColumnIndex("name");
int emailColIndex = c.getColumnIndex("email");
int id = c.getInt(idColIndex)
String name = c.getString(nameColIndex)
String email = c.getString(emailColIndex)
to create an object use this:
new Person(<your values>);
db.rawQuery ==> return a Cursor which point to the returned data from select statement so you should make
Cursor cursor = db.rawQuery("SELECT * FROM PERSON_TABLE ORDER BY age ASC , null);
if(cursor.moveToFirst()) //mean find data and point to the samllest
cursor.getString(c.getColumnIndex("field_name"));

Query Database with an array list and get an array list of results back

I have setup an application which currently can lookup an input id with one on the database to then give a single result. E.g. user enters id = 1 , database contains a record with an id of 1 then returns the name or number etc...
Now I want to improve the system slightly by querying my database with an arraylist which contains a range of id's e.g. 3, 456, 731 etc... which I want my database to search for. I have also grouped multiple values to certain id's for example the database might search for an id of 3 it will then find 5 results I want it to return the telephone number of each one of those results into another arraylist which I can print to the logs.
I hope I have explained this enough, but please ask questions if you require more information.
The code below demonstrates the modified version of the query used to gain a single result, but I cannot see what I'm doing wrong to gain multiple results.
Activity....
// New array list which is going to be used to store values from the database
ArrayList<String> contactsList;
// This arrayList has been received from another activity and contains my id's
ArrayList<String> contacts = intent.getStringArrayListExtra("groupCode");
// The database which i'm using
ContactDBHandler contactDBHandler = new ContactDBHandler(getApplicationContext(), null, null, 1);
//getAllValues is used to pass my arraylist id's to the database.
contactsList = contactDBHandler.GetAllValues(contacts);
// Simple log statement to loop and display results
for (int i = 0; i < contactsList.size(); i++){
Log.i("Numbers", contactsList.get(i));
}
ContactDBHandler
Query
// I'm telling it to get the contact number from the contact_list
// when the groupcode matches the code recieved.
public ArrayList<String> GetAllValues(ArrayList groupCode)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = null;
String alarmName = "";
ArrayList<String> list = new ArrayList<>();
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code=?", new String[]{groupCode+ ""});
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed())
{
cursor.close();
}
return list;
}
Thanks
Can you see where I have gone wrong?
Try this:
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (" + TextUtils.join(",", Collections.nCopies(groupCode.size(), "?")) + ")", groupCode.toArray(new String[groupCode.size()]));
Your current code fails to pass the list in the sql-format: = does only support single values, for lists you have to use IN.
Your code would result in a query like this:
SELECT contact_number FROM contact_list WHERE grp_code=["some_id","other_id"]
But what you need (and my code produces) is:
SELECT contact_number FROM contact_list WHERE grp_code IN ('some_id','other_id')
References:
SQL query to find rows with at least one of the specified values
WHERE IN clause in Android sqlite?
IN clause and placeholders
https://developer.android.com/reference/android/text/TextUtils.html#join(java.lang.CharSequence,%20java.lang.Iterable)
You cannot pass an ArrayList to an SQLQuery. To check for multiple values in the same field you have to use the 'in' keyword.
Ex:
SELECT * FROM `table1` where column in ( 'element1', 'element2', 'element3')
In your case,
String str = "";
for(String s: groupCode){
str = str+","+"\'"+s+"\'";
}
//to remove the extra ' in the begining
str = str.substring(1);
return str;
cursor = db.rawQuery("SELECT contact_number FROM contact_list WHERE grp_code IN (?)", new String[]{str});

Android - How to retrieve values from SQLite Database and post them as Checkboxes

I'm currently trying to retrieve values from my SQLite Database. Screenshot
And output the value of the subname and units on checkboxes. I'm pretty sure I just have to get the IDs so I could output the subname and units values as checkboxes, so subname + unit = 1 checkbox. Could you please provide a sample code or link me a tutorial on how to do this? I'm rather clueless on how to do this and really new to Android.
I'm also looking for a way on how to save their IDs afterwards and add them into another table, so when I retrieve the IDs it will output the values. If you know how to do this too please do help. Thank you! Your time is much appreciated
Currently I have this in my DatabaseHandler.java. I just really don't know the code or syntax on how to retrieve it in my MainActivity and output it on checkboxes.
//get all subjects
public List < Subject > getAllSubjects() {
List < Subject > subjectList = new ArrayList < Subject > ();
//select all query
String selectQuery = " SELECT * FROM " + TABLE_SUBJECTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
//loop through all rows and add it to list
if (cursor.moveToFirst()) {
do {
Subject subject = new Subject();
subject.setID(Integer.parseInt(cursor.getString(0)));
subject.setSubName(cursor.getString(1));
subject.setUnits(cursor.getString(2));
//ADD CONTACT TO LIST
subjectList.add(subject);
} while (cursor.moveToNext());
}
return subjectList;
}

SELECT one record and bind to text boxes

this is my query
SELECT *
FROM articles
WHERE id >1
ORDER BY id ASC
LIMIT 1
my requirement is very simple. I just want to select only one record and bind to textViews . This is what I had done so far.
public Article oneRecord()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT * FROM articles WHERE id=3;", null);
if(c.moveToFirst()){
Article a= new Article();
a.setId(c.getString(c.getColumnIndex("id")));
a.setImage_url(c.getString(c.getColumnIndex("image_url")));
a.setTitle(c.getString(c.getColumnIndex("title")));
a.setBody(c.getString(c.getColumnIndex("body")));
}
return a;
}
I am not sure I have understood you problem correctly or not. However there is not special thing to do. Just update TextView after getting article from database.
Article a = getOneRecordFromDB();
titleView.setText(a.getTitle());
bodyView.setText(a.getBody());

What is going wrong in this?

I am fetching the list of tables from the database. I am using this code to get the list of tables:
public void showAllTable()
{
db.execSQL("select name from sqlite_master where type = 'table'");
}
This query execute successful in to the shell window.
Now I want to display that list of tables in Android. How it is possible? I am calling this function from another activity.
Edited:
Thanks to Stack Overflow, I found the answer here.
The usual way to display a list of data is to use a ListView. To do this you will need to do the following:
1: change your db query to db.query instead of db.exec and store the values in a List:
ArrayList<String> tables = new ArrayList<String>();
Cursor mCursor = db.query("sqlite_master", new String[]{"name"}, "type = table",
null,null,null,null);
if (mCursor.getCount() > 0) {
for (mCursor.moveToFirst(), !mCursor.isAfterLast(), mCursor.moveToNext()) {
tables.add(mCursor.getString(0));
}
}
/** Important! always close cursors and DB's */
mCursor.close();
db.close();
return tables;
2: Use a ListView and an ArrayAdapter to display the information. See The Android Tutorial on how to do this.

Categories

Resources