populate listview row from more than one database row - android

I have a listview and i would like to populate a row with several calculations done on multiple database tables rows winch carry the row id as column (group).
So for example one of my database tables has three rows all of winch have a unique row id for one coloumn and also another column (group) which has the same value for all rows allowing them to be grouped together.
What i would like to do is pass a cursor over each row which has the same value in the column group and do a few things on each row like add,minus,subtract etc. and then add the result from each row to a value which i can then attach to the list view.
How can i go about doing this?

You can put the results in an Array and then do your operations you want on each item. Then you use an arrayAdapter to put the items in it.
public String[][] getResultSetAsArray(Cursor cursor) {
int numberOfColumns = cursor.getColumnCount();
int numberOfRows = cursor.getCount();
String [][] resultSetAsArray = new String[numberOfColumns][numberOfRows];
for (int currentColumn = 0; currentColumn < numberOfColumns; currentColumn++)
{
cursor.moveToFirst();
for (int currentRow = 0; currentRow < numberOfRows; currentRow++)
{
resultSetAsArray[currentColumn][currentRow] = cursor.getString(currentColumn);
cursor.moveToNext();
}
}
return resultSetAsArray;
}
This method gives you all the results of a cursor back in a two-dimensional array. If you only have one column, you just use the method and put [0] after it to put it in one array.
Example:
String table = tablename;
String[] columns = {column1, column2};
String orderBy = columnNameToOrder;
Cursor cursor = db.query(table, columns, null, null, null, null, orderBy);
String[] column1Values = dbRetrieval.getResultSetAsArray(tabLabelCursor)[0];
String[] column2Values = dbRetrieval.getResultSetAsArray(tabLabelCursor)[1];
String[][] values = dbRetrieval.getResultSetAsArray(tabLabelCursor); // all the database values in a two-dimensional array.

Related

Disabling button and storing in database

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.

Android database update records

In a table of my database, I have 7 records.
Now I want to update the records through a WHERE clause.
First, count the records, according to a clause
int pos = 0;
String SQL = "SELECT COUNT(posizione) FROM operatori WHERE posizione>0;";
final Cursor cur = db2.rawQuery(SQL, null);
while (cur.moveToNext()) {
pos = cur.getInt(0);
}
cur.close();
//then, with a for loop, update all the records based on a WHERE clause
for (int i = 1; i <= pos; i++) {
ContentValues cv1 = new ContentValues();
cv1.put(OperatoriTable.POSIZIONE, i);
db2.update(OperatoriTable.TABLE_NAME, cv1, OperatoriTable.POSIZIONE + ">0", null);
}
db2.close();
but, for example, if posequals 5, should enter the numbers 1,2,3,4,5. Instead, it is always inserted 1. Where am I wrong?
Your update statement probably updates multiple rows at once.
Each time you call db2.update in the for loop, it probably overwrites all rows where posizione>0 with the value currently in cv1.

Android, Database count for each record

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

Assigning values of Two DB Columns to a Cursor?

I have a query that returns 2 set of Columns from DB and I want to how can I assign these columns to a Cursor and later use them for further processing.
Thats my Query:
public List<String> getAllCapabilities1(String myRub)
{
List<String> Caps = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT Cap_Name, Cap_ID FROM capability where Rub_ID = '"+myRub+"'";
SQLiteDatabase database = this.dbOpenHelper.getReadableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
Caps.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
This query returns:
Cap_Name Cap_ID
Cap 1 1
Cap 2 2
Cap 3 3
With normal cursor I can handle one Column very easily but I need to know how to assign both columns at a time.
Android Cursor is the ResultSet of SELECT query and it can contain any number of columns.
Each column value can be got as:
Cursor c = db.rawQuery("SELECT * FROM TABLE_NAME", null);
while(c.moveToNext()) {
Log.d("Column1", c.getString(c.getColumnIndex("Column1")));
Log.d("Column2", c.getString(c.getColumnIndex("Column2")));
}
For your problem, create a custom class CapDetails with attributes CapId and CapName.
Change your method declaration as:
public List<CapDetails> getAllCapabilities1(String myRub)
and change the declaration caps to List of CapDetails instead of List of String.
within cursor loop:
while (cursor.moveToNext())
{
CapDetails capDetails = new CapDetails();
// Assign each column value to respective capDetails attribute. then,
caps.add(capDetails);
}

android cursor.moveToNext()?

I am trying to query all the columns in a table into one long text view and/or string. I know this might not be the right way to do things but I have to do this. Correct me if I am wrong, I was under the impression that move next would get the next column in the row:
Cursor c = db.get();
if(c.moveToFirst){
do{
string = c.getString(0);
}while(c.moveToNext);
}
I thought that this would get the first column and display all of its contents instead I get the first column and first row. What am I doing wrong? Is there a better or real way to get this information without using a ListView?
The simple use is:
Cursor cursor = db.query(...);
while (cursor.moveToNext()) {
...
}
moveToFirst is used when you need to start iterating from start after you have already reached some position.
Avoid using cursor.getCount() except if it is required.
And never use a loop over getCount().
getCount is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.
If your query matches 1000 rows, the cursor actually has only the first row. Each moveToNext searches and finds the next match. getCount must find all 1000. Why iterate over all if you only need 10? Why iterate twice?
Also, if your query doesn't use an index, getCount may be even slower - getCount may go over 10000 records even though the query matches only 100. Why loop 20000 instead of 10000?
For clarity a complete example would be as follows which I trust is of interest. As code comments indicated we essentially iterate over database rows and then columns to form a table of data as per database.
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null,
null);
//if the cursor isnt null we will essentially iterate over rows and then columns
//to form a table of data as per database.
if (cursor != null) {
//more to the first row
cursor.moveToFirst();
//iterate over rows
for (int i = 0; i < cursor.getCount(); i++) {
//iterate over the columns
for(int j = 0; j < cursor.getColumnNames().length; j++){
//append the column value to the string builder and delimit by a pipe symbol
stringBuilder.append(cursor.getString(j) + "|");
}
//add a new line carriage return
stringBuilder.append("\n");
//move to the next row
cursor.moveToNext();
}
//close the cursor
cursor.close();
}
I am coding my loops over the cusror like this:
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
cursor.getString(cursor.getColumnIndex("column_name"));
cursor.moveToNext();
}
That always works. This will retrieve the values of column "column_name" of all rows.
Your mistake is that you loop over the rows and not the columns.
To loop over the columns:
cursor.moveToFirst();
for(int i = 0; i < cursor.getColumnNames().length; i++){
cursor.getString(i);
}
That will loop over the columns of the first row and retrieve each columns value.
moveToNext move the cursor to the next row. and c.getString(0) will always give you the first column if there is one. I think you should do something similar to this inside your loop
int index = c.getColumnIndex("Column_Name");
string = c.getString(index);
cursor.moveToFirst() moves the cursor to the first row. If you know that you have 6 columns, and you want one string containing all the columns, try the following.
c.moveToFirst();
StringBuilder stringBuilder = new StringBuilder();
for(int i = 0; i < 6; i++){
stringBuilder.append(c.getString(i));
}
// to return the string, you would do stringBuilder.toString();

Categories

Resources