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.
Related
I am trying to understand the populating of a list view from data held in a SQLite table. I am using the following code. I have looked at a lot of similar questions on this site but have not been able to figure our where I have gone wrong as there seems to be a myriad of ways to tackle this. This is my bdhandler code:
public Product getAllRows(){
String query = "select * from "+TABLE_PRODUCTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
Product product = new Product();
if (cursor.moveToFirst()){
cursor.moveToFirst();
cursor.close();
}else{
product = null;
}
db.close();
return product;
}
In the activity class, I do not understand what I should be using to populate the list view.
Where can I get more detailed info to try and understand where I am missing what I need to do?
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});
I try to implement a "android.support.v7.widget.SearchView" into my toolBar who should provide some suggestions to the user.
I wished activeAndroid could provide me a way to retrieve a CursorAdapter directly from my query (basically a getAll()).
The following link seems to be deprecated since .toSql() require private access and "Cache" is unresolved.
Any idea?
You can create a Cursor via ActiveAndroid using:
Cursor cursor = ActiveAndroid.getDatabase().rawQuery("SELECT * FROM TABLE", null);
The CursorAdapter you will need to build yourself but is quite easy and the "Defining the Adapter" section of the link you provided should give you what you need to get started.
Please note that ActiveAndroid 3.1.0 does show the .toSql() as public.
One thing you will need to do is make sure your ActiveAndroid db model includes the expected _id column which is not there by default with ActiveAndroid. You'll want to uninstall the app or perform a database migration to see the changes to the underlying db model. Otherwise you may get this error
java.lang.IllegalArgumentException: column '_id' does not exist
Include the expected '_id' column which is not there by default with ActiveAndroid:
#Table(name = "Items", id = BaseColumns._ID)
Request the cursor like this:
public Cursor getCursor() {
String sql = new Select()
.from(Item.class)
.toSql();
String[] params = null;
Cursor cursor = Cache.openDatabase().rawQuery(sql, params);
return cursor;
}
You could then create an adapter like this:
ListAdapter adapter = new SimpleCursorAdapter(context,
android.R.layout.simple_list_item_1,
c, new String[] {"Name"}, new int[] { android.R.id.text1}
);
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.
Now I want to access an entire column from database and then compare it with some text that I have stored...but I am getting no idea on how to do that..So can someone please help me with this...
Entire column? You mean all the values for a given column accross all records?
You should iterate the ResultSet obtained and start comparing the values (for example - if you iterate using "rs" object of ResultSet, you should compare:
String valueFromDB = rs.getString("myColumn");
String someTextStored = .... //the text being stored
if (valueFromDB != null) {
if (someTextStored.equals(valueFromDB) {
//Comparison succeeded - implement some logic here for handling success
}
}
And the above code should be inside a loop code that iterates over the ResultSet and
uses the "next" method to obtain the next record.
Hope this helps you
public ArrayList<String> getValues(){
Cursor cursor = null;
SQLiteDatabase db = getReadableDatabase();
Log.v("done","getting rows ");
cursor = db.rawQuery("SELECT YourColumnName FROM "+TABLE_NAME, null);
if(!cursor.moveToFirst()){
}
else{
do {
list_values.add(cursor.getString(0));
} while (cursor.moveToNext());
}
db.close();
cursor.close();
return list_values;
}
Now you are having all the values of a particular column you can compare it from this array list.