Multi-Dimensional Checkbox array in android - android

Am trying to create dynamic checkboxes based on contents of two tables. I am able to create the checkboxes but the problem comes on the OnCheckedChangeListener where i cant pick the index of the clicked checkbox. Below is my code. Any assistance is highly appreciated
I call getViews() on the onCreate() Method
public void getViews(){
// TableLayout ref from xml where we want to Display list
final TableLayout proF = (TableLayout) findViewById(R.id.TableLayout_views);
// Get the database and run the query
final SQLiteDatabase datb = mDatabase.getWritableDatabase();
Cursor curs = datb.rawQuery("SELECT * FROM " + tarea.AREA_TABLE_NAME
+ " WHERE " + tarea.AREA_ID + " LIKE '" +"1"+ "' ", null);
curs.moveToFirst();
if (curs.getCount() > 0) {
for (int i = 0; i < curs.getCount(); i++) {
area_id = curs.getInt(curs.getColumnIndex(tarea.AREA_ID));
curs.moveToNext();
}
}
System.out.println("Area Id is : " + area_id);
Cursor cur = datb.rawQuery("SELECT * FROM " + tclass.CLASS_TABLE_NAME
+ " WHERE " + tclass.CLASS_AREA_ID + " LIKE '" +area_id+ "' ", null);
cur.moveToFirst();
clss = new String[cur.getCount()];
if (cur.getCount() > 0) {
int i ;
for (i = 0; i < cur.getCount(); i++) {
clss[i] = cur.getString(cur.getColumnIndex(tclass.CLASS_ITEM));
System.out.println("Class item : " + clss[i]);
class_id = cur.getInt(cur.getColumnIndex(tclass.CLASS_ID));
System.out.println("Class Id is : " + class_id);
Cursor c = datb.rawQuery("SELECT * FROM " + tmonitoring.MONITORING_TABLE_NAME
+ " WHERE " + tmonitoring.MONITORING_CLASS_ID + " LIKE '" +class_id+ "' ", null);
c.moveToFirst();
avail = new CheckBox[cur.getCount()][c.getCount()];
edtbox = new EditText[cur.getCount()][c.getCount()];
System.out.println("cur.getCount()>>" + cur.getCount());
System.out.println("c.getCount()>>" + c.getCount());
System.out.println("avail.length >> "+avail.length);
// class Dynamic table
TableRow RowArea = new TableRow(this);
TableRow tRow = new TableRow(this);
TableRow items = new TableRow(this);
int color = getResources().getColor(R.color.font_color_bg);
int color2 = getResources().getColor(R.color.font_color_white);
TextView tResult = new TextView(this);
tResult.setText("MON ITEM");
tResult.setTextColor(color2);
TextView tResult1 = new TextView(this);
tResult1.setText("_____________");
tResult1.setTextColor(Color.rgb(255, 106, 0));
TextView tResults = new TextView(this);
tResults.setText("RESULT");
tResults.setTextColor(color2);
TextView tResult2 = new TextView(this);
tResult2.setText("____________");
tResult2.setTextColor(Color.rgb(255, 106, 0));
TextView tResults1 = new TextView(this);
tResults1.setText("ACTION");
tResults1.setTextColor(color2);
TextView tResults2 = new TextView(this);
tResults2.setText("____________");
tResults2.setTextColor(Color.rgb(255, 106, 0));
TextView tResults3 = new TextView(this);
tResults3.setText("ACTION");
tResults3.setTextColor(color2);
TextView tResult3 = new TextView(this);
tResult3.setText("____________");
tResult3.setTextColor(Color.rgb(255, 106, 0));
TextView AreaResults = new TextView(this);
AreaResults.setBackgroundColor(color);
AreaResults.setGravity(Gravity.CENTER | Gravity.CENTER_HORIZONTAL);
AreaResults.setTextColor(color2);
AreaResults.setText(clss[i]);
RowArea.addView(AreaResults);
tRow.addView(tResult);
items.addView(tResult1);
tRow.addView(tResults);
items.addView(tResult2);
tRow.addView(tResults1);
items.addView(tResults2);
tRow.addView(tResults3);
items.addView(tResult3);
proF.addView(RowArea);
proF.addView(tRow);
proF.addView(items);
if (c.getCount() > 0) {
int j;
for (j = 0; j < c.getCount(); j++) {
System.out.println("Monitoring item : " + c.getString(c.getColumnIndex(tmonitoring.MONITORING_ITEM)));
TableRow newRow = new TableRow(this);
newRow.setGravity(Gravity.CENTER);
newRow.setTag(c.getString(c.getColumnIndex(tmonitoring.MONITORING_CLASS_ID)));
// column 1 mon item
TextView nameCol = new TextView(this);
nameCol.setWidth(20);
nameCol.setMaxWidth(8);
nameCol.setTypeface(nameCol.getTypeface(), Typeface.BOLD);
nameCol.setText(" " + c.getString(c.getColumnIndex(tmonitoring.MONITORING_ITEM)));
//column 2 checkbox
CheckBox chkbox = new CheckBox(this);
chkbox.setId(j);
chkbox.setText("Yes");
avail[i][j] = chkbox;
System.out.println("avail["+i+"]["+j+"]>> " + chkbox);
System.out.println("avail id->" + avail[i][j].getId());
avail[i][j].setOnCheckedChangeListener(checkListener);
//column 3 take pic
Button picCol = new Button(this);
picCol.setText("Take Pic");
picCol.setTag(c.getInt(c.getColumnIndex(tmonitoring.MONITORING_CLASS_ID)));
picCol.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
SQLiteDatabase db = mDatabase.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM "
+ shelfImage.IMAGE_TABLE_NAME + ";", null);
if (cursor.getCount() > 25) {
Log.v(TAG, "Alert SRR to upload data");
AlertDialog al = showAlertUpload();
al.show();
} else {
Intent myIntent = null;
myIntent = new Intent(Design_Template1.this, Capturephoto.class);
Bundle bund = new Bundle();
bund.putInt("r", r);
bund.putString("user", name);
bund.putInt("userid", userid);
bund.putString("dealer", dealer);
bund.putString("week", weekno);
bund.putString("ticket", Ticket);
bund.putString("picArray", picArray);
myIntent.putExtras(bund);
Design_Template1.this.startActivityForResult(myIntent, 0);
}
cursor.close();
db.close();
}
});
// column 4 view pic
Button viewCol = new Button(this);
viewCol.setText("View Guideline");
viewCol.setTag(c.getInt(c.getColumnIndex(tmonitoring.MONITORING_CLASS_ID)));
viewCol.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = (Integer) v.getTag();
}
});
newRow.addView(nameCol);
newRow.addView(chkbox);
newRow.addView(picCol);
newRow.addView(viewCol);
proF.addView(newRow);
c.moveToNext();
}
}
c.close();
cur.moveToNext();
}
}
curs.close();
cur.close();
datb.close();
}
My click listener is as below
private OnCheckedChangeListener checkListener = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
// Test avail Checkbox
StringBuffer r = new StringBuffer();
int clss;
db1 = mDatabase.getReadableDatabase();
System.out.println("area_id on click listener : " + area_id);
Cursor cur = db1.rawQuery("SELECT * FROM " + tclass.CLASS_TABLE_NAME
+ " WHERE " + tclass.CLASS_AREA_ID + " LIKE '" +area_id+ "' ", null);
cur.moveToFirst();
for(int i = 0; i < cur.getCount(); i++){
clss = cur.getInt(cur.getColumnIndex(tclass.CLASS_ID));
System.out.println("Classid on click listener : " + clss);
results = db1.rawQuery("SELECT "+tmonitoring.MONITORING_ITEM+" FROM " + tmonitoring.MONITORING_TABLE_NAME
+ " WHERE " + tmonitoring.MONITORING_CLASS_ID + " LIKE '" +clss+ "' ", null);
for (int u = 0; u < results.getCount(); u++) {
if (avail[u] != null) {
r.append("\nResults->" + u + " : ").append(
avail[i][u].isChecked());
}
}
cur.moveToNext();
}
cur.close();
results.close();
db1.close();
}
};
The part where i check if isChecked() throws ArrayIndexOutOfBoundsException. Please help

setting the tag will help you to recognize the created checkbox on later stage.
avail = new CheckBox[cur.getCount()][c.getCount()];
avail.setTag(i);//add this line
And inside
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
Integer i=(Integer)buttonView.getTag();
above line gets the checkbox on which the check/uncheck event is performed.
this way you would be able to find out the index.

Related

SQLite and ListView

I have a ListView in my class, I have a cursor regarding a number x which is incrementing each time, I am using this cursor in a ListView but at the time when I am using this x only one row is showing in the ListView. I want to show all the lists regarding the incrementing value. My code is as follows:
if (cursor.moveToFirst()) {
do {
do {
int x = cursor.getInt(cursor.getColumnIndex("trainId"));
String s1 = "SELECT * FROM route_table WHERE trainId=" + x + " AND stationId=" + FromStationId + ";";
String s2 = "SELECT * FROM route_table WHERE trainId=" + x + " AND stationId=" + ToStationId + ";";
final Cursor c1 = SQ.rawQuery(s1, null);
final Cursor c2 = SQ.rawQuery(s2, null);
if (c1 != null && c1.moveToFirst()) {
i = c1.getInt(c1.getColumnIndex("_id"));
c1.close();
}
if (c2 != null && c2.moveToFirst()) {
j = c2.getInt(c2.getColumnIndex("_id"));
c2.close();
}
if (i < j) {
Toast.makeText(this, "My Train is:" + x, Toast.LENGTH_SHORT).show();
String fstring = "SELECT * FROM train_table WHERE _id=" + x + ";";
final Cursor c3 = SQ.rawQuery(fstring, null);
final ListView lv = (ListView) findViewById(R.id.tiimetable_list);
CursorAdapterTimeTable myc = new CursorAdapterTimeTable(this, c3);
lv.setAdapter(myc);
// List(x);
}
break;
} while (cursor.moveToNext());
continue;
} while (cursor.moveToNext());
Only one row is showing, because every time the query is executed a new adapter is created.
Try this to get all items where "_id" are greater than 0:
String fstring = "SELECT * FROM train_table WHERE _id > 0";
final Cursor c3 = SQ.rawQuery(fstring, null);
final ListView lv = (ListView) findViewById(R.id.tiimetable_list);
CursorAdapterTimeTable myc = new CursorAdapterTimeTable(this, c3);
lv.setAdapter(myc);

refresh SQLite database table according to Android spinner

I already did my code based on WIllJBD's suggestion
I want the table refresh the data when its clicked according to spinner, but my toast gave "Database Error". Here is the code for the selected item on spinner
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String tam = spDealer.getSelectedItem().toString();
String dealerID = in.getDealID(tam);
String queryrow = in.MatchDealerID(dealerID);
if (queryrow == dealerID)
{
Cursor c = in.getViewInfoBilling(queryrow);
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
mytable.addView(row);
}
in.close();
} else
{
Toast.makeText(Billing.this, "Data Error!!",Toast.LENGTH_LONG).show();
}
}
And here is my method:
public Cursor getViewInfoBilling(String id){
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID = id", null);
return mcursor;}
public String getDealID(String dealName) throws SQLException{
Cursor mCursor = db.query(Dealer_TABLE, null, ""+Col_DealerName+"=?", new String[]{dealName}, null, null,null);
if(mCursor.getCount()<1){
mCursor.close();
return "Not Exist";
}
mCursor.moveToFirst();
String tampDealID = mCursor.getString(mCursor.getColumnIndex(Col_DealerID));
mCursor.close();
return tampDealID;}
public String MatchDealerID(String tam){
String matchquery = "SELECT DealerID FROM SODashboard, Dealer " +
"WHERE SODashboard.TampDealerIDSOD = tam";
return matchquery;
}
Isnt the ID selected on spinner already same with the ID thats on DB? I already created MatchDealerID and getDealID to compare them.. what should I do make the table refreshes after clicked? Please help me to solve this issue... thank you
There is something wrong in this method.
public Cursor getViewInfoBilling(String id){
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID =" + id, null);
//OR
/*
Cursor mcursor = db.rawQuery("SELECT BillDate,SODashboardNo, SODashboardAmount " +
"FROM SODashboard, Bill WHERE SODashboard.SODashboardNo = Bill.TampSODashboardNo " +
"AND SODashboard.DealerID =?", new String[] { id });
*/
return mcursor;}
There are two versions , try both , have good luck

cannot be cast to android.database.Cursor

I want get info Object in row item ListView ..listview load info in database..
add Income
public void addIncome(OIncome income) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TABLE_INCOME_COLUMN_NAME, income.get_name());
values.put(TABLE_INCOME_COLUMN_CATEGORY, income.get_category() + 1);
values.put(TABLE_INCOME_COLUMN_AMOUNT, income.get_amount());
values.put(TABLE_INCOME_COLUMN_DATE, income.get_date());
values.put(TABLE_INCOME_COLUMN_TIME, income.get_time());
values.put(TABLE_INCOME_COLUMN_NOTE, income.get_note());
db.insert(TABLE_INCOME, null, values);
db.close();
}
Get Income
public List<OIncome> getIncome() {
List<OIncome> list = new ArrayList<OIncome>();
String selectIncome = "SELECT * FROM " + TABLE_INCOME + " INNER JOIN "
+ TABLE_CATEGORY + " ON " + TABLE_CATEGORY + "."
+ TABLE_CATEGORY_COLUMN_ID + "=" + TABLE_INCOME + "."
+ TABLE_INCOME_COLUMN_CATEGORY + " WHERE " + TABLE_INCOME + "."
+ TABLE_INCOME_COLUMN_DATE + "=" + "'" + GET_DATE + "'"
+ " ORDER BY " + TABLE_INCOME + "." + TABLE_INCOME_COLUMN_DATE
+ " DESC";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectIncome, null);
if (cursor.moveToFirst()) {
do {
OIncome income = new OIncome();
income.set_amount(cursor.getFloat(3));
income.set_category(cursor.getInt(8));
income.set_name(cursor.getString(1));
income.set_date(cursor.getString(4));
income.set_time(cursor.getString(5));
list.add(income);
} while (cursor.moveToNext());
}
return list;
}
in class ListIncomeAdapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(layout, null);
}
OIncome income = list.get(position);
TextView tvnameincome = (TextView) convertView
.findViewById(R.id.tvnameincome);
TextView tvdateincome = (TextView) convertView
.findViewById(R.id.tvdateincome);
TextView tvtimeincome = (TextView) convertView
.findViewById(R.id.tvtimeincome);
TextView tvamountincome = (TextView) convertView
.findViewById(R.id.tvamountincome);
ImageView imglistincome = (ImageView) convertView
.findViewById(R.id.imglistincome);
Other other = new Other();
// OCatergory catergory = data.get(position);
tvnameincome.setText(income.get_name());
tvdateincome.setText(other.convertDateYear(income.get_date()));
tvtimeincome.setText(income.get_time());
tvamountincome.setText(income.get_amount() + "");
imglistincome.setImageResource(income.get_category());
return convertView;
}
How can I get the information of that item..
please give me a few lines of
get information on that item
You have to extract it from the parent, like below. I'm not 100% sure on the syntax though, because I don't have my Android workspace here.
OIncome income = (OIncome) ((ListView) parent).getItemAtPosition(position);
This replaces your line of code, which throws the Cast Exception:
OIncome income = list.get(position);

Get full SQlite database information from relevant row/record when clicking listView item (which contains partial information from the row/record)

I have a method named getData that populates a listView from my database limited to specified columns from the table:
public ArrayList<String> getData() {
// TODO Auto-generated method stub
String[] columns = new String[] { KEY_ROWID, KEY_MODULE_CODE,
KEY_MODULE_NAME, KEY_LECTURE_PRACTICAL,
KEY_LECTURE_PRACTICAL_SHORT, KEY_LECTURE_DAY,
KEY_LECTURE_DAY_SHORT, KEY_START_TIME, KEY_END_TIME,
KEY_LOCATION, ADDITIONAL_INFO };
Cursor c = ourDatabase.query(DATABASE_MODULES, columns, null, null,
null, null, null);
ArrayList<String> results = new ArrayList<String>();
int indexModCode = c.getColumnIndex(KEY_MODULE_CODE);
int indexLectPracShort = c.getColumnIndex(KEY_LECTURE_PRACTICAL_SHORT);
int indexLectDayShort = c.getColumnIndex(KEY_LECTURE_DAY_SHORT);
int indexLectStart = c.getColumnIndex(KEY_START_TIME);
int indexLectLoc = c.getColumnIndex(KEY_LOCATION);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
results.add(c.getString(indexModCode) + " "
+ c.getString(indexLectPracShort) + " "
+ c.getString(indexLectDayShort) + " "
+ c.getString(indexLectStart) + " "
+ c.getString(indexLectLoc));
}
return results;
}
This works fine and here is how I populate my listview (ModuleDatabaseHandler is the class where the database is managed):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_modules_test);
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
ArrayList<String> data = info.getData();
info.close();
l = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 ,data);
l.setAdapter(adapter);
l.setOnItemClickListener(this);
}
I want to be able to click the listView item, and view ALL the information pertaining to the record (in the listView it only shows certain information). I have attempted to create a new method in the ModuleDatabaseHandler class called getAllData.
Below is the OnItemClick for the ListView item which launches a new activity, passing through the information from getAllData using putExtra:
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView temp = (TextView) view;
Toast.makeText(this, temp.getText() + " " + i, Toast.LENGTH_SHORT)
.show();
ModuleDatabaseHandler info = new ModuleDatabaseHandler(this);
info.open();
String module_info = info.getAllData(); // METHOD TO GET ALL DATA
info.close();
Intent fullModuleDetails = new Intent();
fullModuleDetails.setClassName("com.example.collegetimetable",
"com.example.collegetimetable.ModuleDetails");
fullModuleDetails.putExtra("list1", module_info);
startActivity(fullModuleDetails);
}
Here is the getAllData method which retrieves all the information from the database. How could I alter this method, to retrieve only the information for the row relating to the particular listView item that was clicked by the user?
public String getAllData() {
String[] columns = new String[]{ KEY_ROWID, KEY_MODULE_CODE, KEY_MODULE_NAME, KEY_LECTURE_PRACTICAL, KEY_LECTURE_DAY, KEY_START_TIME,KEY_END_TIME, KEY_LOCATION, ADDITIONAL_INFO};
Cursor c = ourDatabase.query(DATABASE_MODULES, columns, null, null, null, null, null);
String results = "";
int indexRow = c.getColumnIndex(KEY_ROWID);
int indexModCode = c.getColumnIndex(KEY_MODULE_CODE);
int indexModName = c.getColumnIndex(KEY_MODULE_NAME);
int indexLectPrac = c.getColumnIndex(KEY_LECTURE_PRACTICAL);
int indexLectDay = c.getColumnIndex(KEY_LECTURE_DAY);
int indexLectStart = c.getColumnIndex(KEY_START_TIME);
int indexLectEnd = c.getColumnIndex(KEY_END_TIME);
int indexLectLoc = c.getColumnIndex(KEY_LOCATION);
int indexLectInfo = c.getColumnIndex(ADDITIONAL_INFO);
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
results = results + ( c.getString(indexModCode) + " " + c.getString(indexModName) + " " + c.getString(indexLectPrac)
+ " " + c.getString(indexLectDay) + " " + c.getString(indexLectStart) + " " + c.getString(indexLectEnd) + " "
+ c.getString(indexLectLoc) + " " + c.getString(indexLectInfo));
}
return results;
}
Thanks for any help
Instead of looping through the data, you would do something along the lines:
public String getAllDataForRow(int row) {
String[] columns = new String[]{ KEY_ROWID, KEY_MODULE_CODE, KEY_MODULE_NAME, KEY_LECTURE_PRACTICAL, KEY_LECTURE_DAY, KEY_START_TIME,KEY_END_TIME, KEY_LOCATION, ADDITIONAL_INFO};
Cursor c = ourDatabase.query(DATABASE_MODULES, columns, null, null, null, null, null);
if(c.moveToPosition(row)) {
String result = "";
for(int columnIndex = 0; columnIndex<c.getColumnCount();columnIndex++) {
result += c.getString(columnIndex)+" ";
}
return result;
} else {
throw new IllegalArgumentException("Row " + row + " does not exist");
}
}
Also, if you didn't know: If you want all columns, you actually do not have to specify them in the projection, but can just pass null instead of columns.
Hope that helps.

Cursor Index Out of Bound

i trying to search in database whether the id is exist or not, when it exist i open the next activity , but when it not exist the app crash.. i coundnt find the bug , error Cursor Index out of bound
Database dbc = new Database(this);
dbc.open();
String id = searchId.getText().toString();
boolean checkId = dbc.isGotId(id);
if(checkId == true){
String s = searchId.getText().toString();
Bundle b = new Bundle();
b.putString("key",s);
b.putInt("keyX", radioBtnFlag);
Intent a = new Intent(SearchUpdate.this, UpdateDelete.class);
a.putExtras(b);
startActivity(a);
searchId.setText(null);
}else if(checkId == false){
Log.v(id, id + "2222222");
Dialog d = new Dialog(this);
d.setTitle("Error!");
TextView tv = new TextView(this);
tv.setText("This Search is allow only ID! "+ radioBtnFlag);
d.setContentView(tv);
d.show();
searchId.setText(null);
and here ...
public boolean isGotId(String id){
boolean result = false;
try{
Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Pro_ID + "=" + id, null);
result = true;
}catch(SQLiteException e)
{
result = false;
}//catch
return result;
}//isGOtId
Try this...
public boolean isGotId(String id){
Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " +
Pro_ID + "=" + id, null);
int numberOfRows = sId.getCount();
if(numberOfRows <= 0)
{
return false;
}
return true;
}
try{
Cursor sId = ourDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + Pro_ID + "=" + id, null);
if(sId.moveToFirst() && sId ! = null)
result = true;
}catch(SQLiteException e)
{
result = false;
}

Categories

Resources