I have a ListView in my Class which will display a list of every category in the database table. In that list view I have three TextViews, ROWID CategoryName and CategoryCount respectively as so:
private void populateCategoryList() {
DatabaseHandler db = new DatabaseHandler(this);
TextView tvCategoryItem = (TextView) findViewById(R.id.tvCategoryItem);
TextView tvCatID = (TextView) findViewById(R.id.tvCatID);
TextView tvCatCount = (TextView) findViewById(R.id.tvCatCount);
Cursor cursor = db.getCategories();
// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
// startManagingCursor(cursor); //TODO Turned off because on back from contact details made a closed cursor error
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { db.KEY_ROWID, db.KEY_CATEGORY };
int[] toViewIDs = new int[] { R.id.tvCatID, R.id.tvCategoryItem };
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.item_categorylist, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);
/****** COUNT CODE ******/
// tvCatCount = (db.countCategory(category));
// Set the adapter for the list view
lvCategories = (ListView) findViewById(R.id.lvCategories);
lvCategories.setAdapter(myCursorAdapter);
db.close();
You can see in the toFields above that I do not yet have a field set for the count. I will use tvCatCount for this. The question is, how and where do I insert the count code. In this case the count? I think that the countCategory will need to be a for loop where it should get the id of the current category entry for that row, call the db.countCategory and tehn set the value in the TextView to the returned result?
Here is the db.countCategory code:
public int countCategory(category){
SQLiteDatabase db = this.getWritableDatabase();
String[] categoryColumns = new String[] { KEY_ROWID, KEY_CATEGORY };
Cursor c = db.query(CATEGORY_TABLE, null, null, null, KEY_CATEGORY + "=" + category, null, null);
int result = c.getCount();
c.close();
Log.i("DATABASE", "Category Count for id " + id + "is " + result);
return result;
}
which should count every entry in the table equal to the value of "id". This code already works elsewhere, so I am not too worried about it, but to count for each row in a listview, that is a different animal.
To show the count of expenses for each category, you would need a table with these columns:
_id | CategoryName | Count
To compute this, you have to join the categories table to the expenses table, and use GROUP BY to get one output row for each distinct category value:
SELECT Category.rowid AS _id,
Category.Name,
COUNT(*) AS NumberOfExpenses
FROM Category
JOIN Expenses ON Category.rowid = Expenses.CategoryID
GROUP BY Category.rowid
Related
I am calling same activity for 5, 6 different movies to book ticket. I have used button for seats. I set button disable after clicking and store its id in sql database. Now when I come again to book another ticket for same movie, same show
String[] projection= new String[]{
movieEntry.COLUMN_NAME_SEAT
};
//where clause
String selection=movieEntry.COLUMN_NAME_MN + " =?"+" AND "+movieEntry.COLUMN_NAME_MD +" =?" +" AND "+movieEntry.COLUMN_NAME_MT +" =?" ;
// int i=0;
String colindex=null;
// this query is select seatno from tablename
// where movie_name='movie that user selected' and movie_time='user seklected currently'
//and movie_date='';
//it is working correctly its fetching all records
// i am trying to add all this fetched seatno to the seatsArraylist so that
//we can get it from this arrayList and disable that seats for the user for that particular movie and date and time
// but problem is that it is adding only one records to arraylist
//can you plz go through this code
String[] selectionArgs ={ Movietitle, Datem, Mtiming} ;
try{
Cursor cursor = rdb.query(
movieEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
null
);
if(cursor!= null ) {
int i=0;
while(cursor.moveToFirst())
{
colindex= cursor.getString(i);
seatsArrayList.add(colindex);
i++;
tv1.setText(seatsArrayList.get(2));
}
tv.setText(colindex);
}
/* for(int j=0;j<=seatsArrayList.size();j++)
{
if(seatsArrayList.get(j)=="Seat4")
{
theBtn[3].setEnabled(false);
}
}*/
You are not supposed to iterate in your cursor like that you have just made your cursor to move to the first part (0th). To iterate in a cursor its easy with a for loop like this:
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
// all operations should be here
}
And again even inside the loop the method cursor.getString(int) the int passed is not the index of a cursor but it is a column index. In your table there may be multiple columns the first one is (0th) the second column is (1st). So you should pass column indexes.
I know this question has been asked a number of times but for some reason I can't solve it.
I am 100% sure that there is no problem in the column name.
This is the table definition:
CREATE TABLE IF NOT EXISTS categories (category_id INTEGER, category_name TEXT, PRIMARY KEY(category_id))
This is the access to the column.
As can be seen I do a small test first to make sure I have the correct column name.
Using the name I print to the LogCat the value of the column in the first row.
It works perfectly. Yet, when passed to the adapter I get the above error.
Cursor mGroupsCursor = _dbHelper.fetchGroup();
getActivity().startManagingCursor(mGroupsCursor);
mGroupsCursor.moveToFirst();
String colName = "category_name";
Log.d("ToratYavneh", "i = " + i + " category_name = " + mGroupsCursor.getString(mGroupsCursor.getColumnIndex(colName)));
ExpandableListView elv = (ExpandableListView) view.findViewById(R.id.list);
MyExpandableListAdapter adapter = new MyExpandableListAdapter(mGroupsCursor, getActivity(),
R.layout.rowlayout_category, // Your row layout for a group
R.layout.rowlayout_sub_category, // Your row layout for a child
new String[] { colName }, // Field(s) to use from group cursor
new int[] {R.id.category_name }, // Widget ids to put group data into
new String[] { "sub_category_name" }, // Field(s) to use from child cursors
new int[] { R.id.sub_category_name }); // Widget ids to put child data into
elv.setAdapter(adapter);
I thought that maybe the problem was in the child but it never reaches getChildrenCursor.
Here is the code for the cursor:
public Cursor fetchGroup() {
String query = "SELECT * FROM categories";
return _database.rawQuery(query, null);
}
Am using db query to sum the column values by using group by clause. I can get the total amount but i couldn't display the values in simplecursoradapter. Please help me to display the total values. I have posted my code below.
String[] columns = new String[] { KEY_ID, KEY_CATEGORY,"sum("+KEY_AMOUNT+")as" + KEY_AMOUNT,
KEY_COMMENT };
Cursor cursor = db.query(TABLENAME2, columns, null, null, null, null,
null);
return cursor;
To display the values in Listview using Simplecursoradapter
String[] from = new String[] { Dailydialog.KEY_CATEGORY,
Dailydialog.KEY_AMOUNT,Dailydialog.KEY_COMMENT};
int[] to = new int[] { R.id.id2, R.id.id3,R.id.id4};
cursorAdapter1 = new SimpleCursorAdapter(this, R.layout.dailydialogall, cursor1,
from, to);
listview_dialog.setAdapter(cursorAdapter1);
Total values are not listed in Listview.
Instead of "sum("+KEY_AMOUNT+")as" + KEY_AMOUNT use " sum("+KEY_AMOUNT+") as " + KEY_AMOUNT. Notice the spaces? Its always a good idea to print your query in log. Another thing is that you need to specify group by clause as well for sum function otherwise only one row will be returned with total sum of amount of all the rows.
In my project I have to select multiple values and pass it to a query. i.e page1 contains checkboxes. I am storing the selected checkbox id's into an array.
I am shuffling that array and getting the values randomly. Now I need to pass these random values to a query. Using IN operator in database I can pass the values
statically but how can I pass the values dynamcially to the query.
For ex:(Passing values statically)
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above query the id's 21 and 22 are know previously and so we are passing statically but I want to send the values to query dynamically.
Page1:
public static ArrayList<String> chksublist = new ArrayList<String>();
Page2:
Collections.shuffle(chksublist );
SELECT * FROM Persons WHERE person_id IN ('21','22')
In the above line I want to send the random values which are in chksublist array.
String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ")";
But shuffling the chksublist before sending it to your SQL query has no impact on the result set you get from SQL. It will not randomly permute your results. Remove Collections.shuffle(chksublist); and use
String query = "SELECT * FROM Persons WHERE person_id IN (" + TextUtils.join(",", chksublist) + ") ORDER BY RANDOM()";
see how values are dynamicaly passed
// Getting single contact
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
// here new String[] { String.valueOf(id) } value is added dynamicaly which is passed to the function
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
You can generate your query like this
int values[]; //it contains your generated values like 21,22....
String query="SELECT * FROM Persons WHERE person_id IN (";
for(int i=0;i<values.length;i++){
query=query+"'"+values[i]+"'";
if(i<values.length-1){
query=query+","; //No , after last values
}
}
query+=")";
finally pass this query.
Try it
cursor = database.query(tablename,
new String[] {"TopName"}, "id IN(?,?)", new String[]{"2","3"}, null, null, null);
using raw query
String query = "SELECT * FROM Persons WHERE person_id IN ("+parameter1+","+parameter2+")";
db.rawQuery(query);
I'm new in android. I'm facing a problem creating a listview using data from sqlite database.
I found this code below to create a listview from contact data
public class Test extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a cursor with all people
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_list_item_1,
// Give the cursor to the list adatper
c,
// Map the NAME column in the people database to...
new String[] {Contacts.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
private static final String[] CONTACT_PROJECTION = new String[] {
Contacts._ID,
Contacts.DISPLAY_NAME
};
}
Now I use this code to pull data from database
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c = myDB.rawQuery("SELECT * FROM " + TableName , null);
Now How can I combine these two codes so I can show data pulled from a database in this list.
Thanks in advance.
If you want to list the data from both sources (contact and DB), I think only option you have is construct an array with return values from both sources.
List finalList = new ArrayList();
Cursor c = getContentResolver().query(Contacts.CONTENT_URI,CONTACT_PROJECTION, null, null, null);
startManagingCursor(c);
c.moveToFirst();
Iterate this cursor and populate the String value to finalList
SQLiteDatabase myDB= null;
String TableName = "myTable";
myDB = this.openOrCreateDatabase("DatabaseName", MODE_PRIVATE, null);
// Get a cursor with all people
Cursor c2 = myDB.rawQuery("SELECT * FROM " + TableName , null);
startManagingCursor(c2);
c2.moveToFirst();
Iterate c2 cursor and add values to finalList.
Convert finalList to array by Iterating finalList
String[] ipArray = new String[finalList.size()];
loop through list and populate the values to ipArray.
I don't have IDE handy, so I have typed the flow.
If suppose you already have data in your cursor, you can follow code in the following tutorial
http://chetanandroidarora.wordpress.com/2011/12/18/customcursoradapter/