I am trying to get the selected checkboxes deleted. I have no clue what to do after this code below:
I am using a simple cursor adapter. I also want to know how I could select and deselect all the checkboxes. I had researched everything but can't find any answer. I've been stuck for 3 days. ALso, Im not sure if the code below is even the correct path i need.
public class SecondCheckedListView extends ListActivity {
private Cursor mCursor;
private Long mRowId;
DBAdapter db = new DBAdapter(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondcheckedlistview);
db.open();
fillData();
}
private void fillData() {
mCursor = db.getAllContacts();
startManagingCursor(mCursor);
String[] from = new String[]{DBAdapter.KEY_FIRSTNAME, DBAdapter.KEY_LASTNAME};
int[] to = new int[]{R.id.textView1, R.id.textView2};
SimpleCursorAdapter d =
new SimpleCursorAdapter(this, R.layout.rowcheckedlistview, mCursor, from, to);
setListAdapter(d);
}
public class MyAdapter extends SimpleCursorAdapter {
private final Context mContext;
private final int mLayout;
private final Cursor mCursor;
private final int mNameIndex;
private final int mIdIndex;
private final LayoutInflater mLayoutInflater;
private final class ViewHolder {
public TextView firstname;
public TextView lastname;
public CheckBox cBox;
}
public MyAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.mContext = context;
this.mLayout = layout;
this.mCursor = c;
this.mNameIndex = mCursor.getColumnIndex(DBAdapter.KEY_FIRSTNAME);
this.mIdIndex = mCursor.getColumnIndex(DBAdapter.ROW_ID);
this.mLayoutInflater = LayoutInflater.from(mContext);
}
#Override
public View getView(final int pos, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(pos)) {
ViewHolder viewHolder;
if(convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.firstname = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.lastname = (TextView) convertView.findViewById(R.id.textView2);
viewHolder.cBox = (CheckBox) convertView.findViewById(R.id.bcheck);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) convertView.getTag();
}
String firstname = mCursor.getString(mNameIndex);
String rowId = mCursor.getString(mIdIndex);
}
return convertView;
}
}
}
what do you mean "delete"? You want to remove the checkbox from the listview? You might need
to do something like
viewHolder.RemoveView(cBox);
If you want to select/delsect all checkboxes, you'll probably want that based upon some other botton or checkbox. I do that with another checkbox like so:
private OnClickListener setSelectAllListener = new OnClickListener() {
#Override
public void onClick(View v) {
selectAllTouched = true;
if (!selectAllCheck.isChecked()) {
selectAll = false;
studs.notifyDataSetChanged();
}
else {
selectAll = true;
studs.notifyDataSetChanged();
}
}
};
And then in my custom adapter that does stuff with each checkbox in a listview, I use this:
if (selectAllTouched) {
if(selectAll){
holder.here.setChecked(true);
itemCheckedHere.set(pos, true);
int who= new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(who, classnum, ATTEND, 1, attendDate );
}
else{
holder.here.setChecked(false);
itemCheckedHere.set(pos, false);
int who = new Integer(holder.text2.getText().toString());
mDbHelper.updateAttend(who, classnum, ATTEND, 0, attendDate );
}
}
I used a sparse array, itemCheckedHere, to hold the values of all the check boxes so scrolling doesn't change the values on resued views.
Related
I've an ListView with data from SQLite that works correctly. Now I want to add more things to this list. To each row I want to add EditText and CheckBox. Something like this:
item1 CheckBox
EditText
item2 CheckBox
EditText
This is my List Class:
public class SeleccionarRelacionPregResp extends Activity implements, OnItemClickListener {
private ListView listaTodo;
private ListAdapter uGraduateListAdapter;
private String bundledCodigoPuntoDeControl;
private ArrayList<UndergraduateDetailsPojo> pojoArrayList;
protected DokesimApplication app;
String codigocaja;
Button btnPruebasGuardar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seleccionartodo);
listaTodo = (ListView) findViewById(R.id.ListaTodo);
listaTodo.setOnItemClickListener(this);
pojoArrayList = new ArrayList<UndergraduateDetailsPojo>();
uGraduateListAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, populateList());
listaTodo.setAdapter(uGraduateListAdapter);
PuntosDeControl pControlSeleccionado = new PuntosDeControl();
app = (DokesimApplication) getApplicationContext();
pControlSeleccionado = app.getpuntocontrol();
codigocaja = pControlSeleccionado.codigocaja;
}
public List<String> populateList() {
List<String> uGraduateNamesList = new ArrayList<String>();
AndroidOpenDbHelper openHelperClass = new AndroidOpenDbHelper(this);
SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();
Cursor cursor = sqliteDatabase.query("RelacionPregResp", null,
" relprcodigocaja = '" + codigocaja + "'",
null, null, null, null);
startManagingCursor(cursor);
while (cursor.moveToNext()) {
String numeropregunta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.numeropregunta));
String relprcodigocaja = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.relprcodigocaja));
String codigopregunta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.codigopregunta));
String pregunta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.pregunta));
String codigorespuesta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.codigorespuesta));
String respuesta = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.respuesta));
String valor = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.valor));
String tipodeguia = cursor.getString(cursor
.getColumnIndex(AndroidOpenDbHelper.tipodeguia));
UndergraduateDetailsPojo ugPojoClass = new UndergraduateDetailsPojo();
ugPojoClass.setNumeroPregunta(numeropregunta);
ugPojoClass.setRelPrCodigoCaja(relprcodigocaja);
ugPojoClass.setCodigoPregunta(codigopregunta);
ugPojoClass.setPregunta(pregunta);
ugPojoClass.setCodigoRespuesta(codigorespuesta);
ugPojoClass.setRespuesta(respuesta);
ugPojoClass.setValor(valor);
ugPojoClass.setTipoDeGuia(tipodeguia);
pojoArrayList.add(ugPojoClass);
uGraduateNamesList.add(pregunta);
}
sqliteDatabase.close();
return uGraduateNamesList;
}
#Override
protected void onResume() {
super.onResume();
uGraduateListAdapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, populateList());
listaTodo.setAdapter(uGraduateListAdapter);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
}
I need some suggestions or examples of how can I do it.
Thanks for any help.
What you basically need is Custom SimpleCursorAdapter.
I am pasting sample program which has Two TextViews in each list row.
You will have to modify it according to your requirement.
package org.sample;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyAdapter extends SimpleCursorAdapter
{
private Context context;
private Cursor cursor;
private int layout;
public MyAdapter(Context context, int layout, Cursor cursor, String[] from,
int[] to, int flags)
{
super(context, layout, cursor, from, to, flags);
this.context = context;
this.cursor = cursor;
this.layout = layout;
}
#Override
public int getCount()
{
if (cursor != null)
return cursor.getCount();
else
return 0;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup)
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
{
view = inflater.inflate(layout, null);
}
cursor.moveToPosition(position);
String title = cursor.getString(cursor
.getColumnIndex(DBHelper.BOOK_TITLE));
String author = cursor.getString(cursor
.getColumnIndex(DBHelper.BOOK_AUTHOR));
TextView titleTxt = (TextView) view.findViewById(R.id.bTitle);
TextView authorTxt = (TextView) view.findViewById(R.id.bAuthor);
titleTxt.setText(title);
authorTxt.setText(author);
return view;
}
}
Once you are ready with your cursor in MainActivity you can write following code.
myAdapter = new MyAdapter(context, R.layout.row, cursor, new String[]{ DBHelper.BOOK_TITLE, DBHelper.BOOK_AUTHOR }, new int[]{ R.id.bTitle, R.id.bAuthor }, 0);
listView.setAdapter(myAdapter);
You have to create your own class that extends from adapter what you need for example SimpleCursorAdapter, then specific with XML file, which elements will be included to your ListView and override getView() method to controling each item in ListView.
It's recommended to create and use design pattern Holder, which represents arbitrary object that holds child widgets of every row and then you will have full control over items.
So let basic example:
Declaration and init of ListView
this.contactList = new ListView(this);
this.contactList = (ListView) findViewById(R.id.contactList);
this.contactList.setAdapter(new ContactsAdapter());
This ContactsAdapter is your own created adapter.
public ContactsAdapter() {
super(getApplicationContext(),
R.layout.listview, cursor, new String[] {"name", "email", "phone"}, new int[] {R.id.name, R.id.email});
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
rowsWrapper = null;
LayoutInflater inflater = getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview, null, false);
rowsWrapper = new ListWidgetWrapper(convertView);
convertView.setTag(rowsWrapper);
}
else {
rowsWrapper = (ListWidgetWrapper) convertView.getTag();
}
Cursor tempC = cursor;
tempC.moveToPosition(position);
setActivitySettings();
rowsWrapper.getNameColumn().setText(tempC.getString(1));
rowsWrapper.getEmailColumn().setText(tempC.getString(2));
tempC = null;
return convertView;
}
}
rowsWrapper is mentioned design pattern Holder.
public class ListWidgetWrapper {
private View inView;
private TextView nameColumn = null, emailColumn = null, phoneColumn = null;
public ListWidgetWrapper(View inView) {
this.inView = inView;
}
public int getNameId() {
return inView.findViewById(R.id.name).getId();
}
public int getEmailId() {
return inView.findViewById(R.id.email).getId();
}
public TextView getNameColumn() {
if (this.nameColumn == null) {
this.nameColumn = (TextView) inView.findViewById(R.id.name);
}
return this.nameColumn;
}
public TextView getEmailColumn() {
if (this.emailColumn == null) {
this.emailColumn = (TextView) inView.findViewById(R.id.email);
}
return this.emailColumn;
}
}
So i have here TextView elemets, you have here widgets which you want have in ListView.
This require to write much more implementation but it's more faster, less energy consume when you don't use for example design pattern Holder because without it, your rows in ListView would be creating repeatedly when won't be in View and later go back.
More about SimpleCursorAdapter
I wanna return a particular filename from a simplecursoradapter back to the activity from which it was called.
I tried this link How communicate between Adapter and Activity and also this one Data between activity and adapter
But either didnt hel p me. I am posting both the activity code and adapter code here.Kindly help
Activity
videolist = (ListView) findViewById(R.id.VideoMusicList);
videolist.setAdapter(adapter);
//Adapter
public class SdCardAdapter extends SimpleCursorAdapter {
static final String TAG = "[SongListAdapter]";
int position;
CheckBox media_selected;
final String SETTING_TODOLIST = "todolist";
private String chk;
private Context context;
private Object itemText;
private ArrayList<string> selectedItems = new ArrayList<string>();
// String file;
private Object convertView;
// private final List<Model> list;
int count;
ListView listview;
private List<Model> list;
private Cursor videocursor;
private LayoutInflater mInflater;
private OnClickListener mClick;
private OnCheckedChangeListener mChecked;
String file_rel_path;
String file_abs_path;
String last_file;
/**
* The Class ViewHolder.
*/
static class ViewHolder {
/** The sdcard_item. Layout of each item in the list view */
RelativeLayout sdcard_item;
LinearLayout sdcard;
/** The title. Textview to display the song title */
TextView media_name;
CheckBox media_selected;
ListView listview;
int position;
}
public SdCardAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View v = super.newView(context, cursor, parent);
final Cursor filecursor = cursor;
final ViewHolder vh = new ViewHolder();
vh.media_name = (TextView) v.findViewById(R.id.sdcard_title);
position = cursor.getPosition();
count = cursor.getCount();
vh.media_selected = (CheckBox) v.findViewById(R.id.sdcard_checkbox);
vh.media_selected
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
System.out.println("checkbox ckicked......");
if (vh.media_selected.isChecked()) {
vh.media_selected.setId(1);
vh.media_selected.getId();
last_file = file_rel_path;
file_rel_path = vh.media_name.getText().toString();
Log.d("filename_........", file_rel_path);
v.setBackgroundColor(Color.GRAY);
} else if (!vh.media_selected.isChecked()) {
file_rel_path="";
vh.media_selected.setId(0);
vh.media_selected.getId();
v.setBackgroundColor(Color.BLACK);
}
Log.d("Position", "" + position);
for (int i = 0; i < count; i++) {
filecursor.moveToPosition(i);
file_abs_path = filecursor.getString(filecursor
.getColumnIndex(MediaStore.Video.Media.TITLE));
if (file_abs_path.equals(file_rel_path)) {
String file_path = filecursor.getString(filecursor
.getColumnIndex(MediaStore.Video.Media.DATA));
Log.d("filename.......", file_path);
}
}
}
});
vh.sdcard_item = (RelativeLayout) v.findViewById(R.id.sdcard_item);
v.setTag(vh);
return v;
}
}
//This is the string that i want to pass to my previous activity
String file_path = filecursor.getString(filecursor.getColumnIndex(MediaStore.Video.Media.DATA));
Use interface callBack :
In SdCardAdapter class create interface :
public interface SdCardAdapterListener
{
public void sendFilePath(String path);
}
Add a listener param in SdCardAdapter constructor :
private SdCardAdapterListener delegate;
public SdCardAdapter(Context context, int layout, Cursor c, String[] from,
int[] to, SdCardAdapterListener delegate)
{
super(context, layout, c, from, to);
this.delegate = delegate;
}
In Activity :
SdCardAdapter adapter = new SdCardAdapter(this, layout, c, from, to, new SdCardAdapterListener()
{
#Override
public void sendFilePath(String path)
{
// do something with path
}
});
videolist = (ListView) findViewById(R.id.VideoMusicList);
videolist.setAdapter(adapter);
Then, simply call delegate.sendFilePath(path) in SdCardAdapter for send to sendFilePath method in your Activity.
I'm trying to fill a grid view using data from a db cursor using a custom SimpleCursorAdapter.
My cursor has data (I checked), but nothing is shown in the GridView, and the getView() method is not even called.
Anybody can help? Why is getView() not called?
Thanks
Activity
dbAdapter = new DBAdapter(this);
dbAdapter.open();
Cursor c;
c = dbAdapter.fetchPCList();
startManagingCursor(c);
String[] from = new String[] {};
int[] to = new int[] {};
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new PCIconAdapter(this, R.layout.pc_icon, c, from, to));
c.close();
dbAdapter.close();
Adapter
public class PCIconAdapter extends SimpleCursorAdapter {
private final Context mContext;
private final int mLayout;
private final Cursor mCursor;
private final int mPCIDIndex;
private final int mClassNameIndex;
private final LayoutInflater mLayoutInflater;
private final class ViewHolder {
public TextView pc_id_view;
public TextView clas_name_view;
}
public PCIconAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mContext = context;
this.mLayout = layout;
this.mCursor = c;
this.mPCIDIndex = mCursor.getColumnIndex(DBAdapter.KEY_PC_LM_ID);
this.mClassNameIndex = mCursor.getColumnIndex(DBAdapter.KEY_PC_CLAS_NAME);
this.mLayoutInflater = LayoutInflater.from(mContext);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.pc_id_view = (TextView) convertView.findViewById(R.id.pc_id);
viewHolder.clas_name_view = (TextView) convertView.findViewById(R.id.clas_name);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
String pc_id = mCursor.getString(mPCIDIndex);
String clas_name = mCursor.getString(mClassNameIndex);
viewHolder.pc_id_view.setText(pc_id);
viewHolder.clas_name_view.setText(clas_name);
}
return convertView;
}
}
I had the same problem. I was using an ArrayAdapter and then I changed to a SimpleCursorAdapter, but it doesn't show anything on screen.
I removed
c.close();
dbAdapter.close();
and now its working fine.
because CursorAdapter does not have getView method . it have newView method .
so extend SimpleCursorAdapter and overRide newWiev and other methods like
public class ContactListCursorAdapter extends SimpleCursorAdapter implements Filterable {
private Context context;
private int layout;
public ContactListCursorAdapter (Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.context = context;
this.layout = layout;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
Cursor c = getCursor();
final LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(layout, parent, false);
int nameCol = c.getColumnIndex(People.NAME);
String name = c.getString(nameCol);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.name_entry);
if (name_text != null) {
name_text.setText(name);
}
return v;
}
#Override
public void bindView(View v, Context context, Cursor c) {
int nameCol = c.getColumnIndex(People.NAME);
String name = c.getString(nameCol);
/**
* Next set the name of the entry.
*/
TextView name_text = (TextView) v.findViewById(R.id.name_entry);
if (name_text != null) {
name_text.setText(name);
}
}
#Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (getFilterQueryProvider() != null) { return getFilterQueryProvider().runQuery(constraint); }
StringBuilder buffer = null;
String[] args = null;
if (constraint != null) {
buffer = new StringBuilder();
buffer.append("UPPER(");
buffer.append(People.NAME);
buffer.append(") GLOB ?");
args = new String[] { constraint.toString().toUpperCase() + "*" };
}
return context.getContentResolver().query(People.CONTENT_URI, null,
buffer == null ? null : buffer.toString(), args, People.NAME + " ASC");
}
}
Your column names array and Views array are empty. So column name to views mapping will never occur. That maybe the reason you are not getting callback on getView
If I remove
c.close();
dbAdapter.close();
it works...
So where am I supposed to close this cursor?...
I've got a ListActivity filled by an adapter extending SimpleCursorAdapter. Some category buttons can be clicked, which fills the listview with a list of articles in the corresponding category. When clicking on an item in the list a new activity is launched which shows the detail of the article.
Now, when pressing the back button in that article detail page, no data is shown. Does it have to reload the data from the DB? Isn't the data supposed to be cached?
Moreover, when going back to the myListActivity, onCreate is not called. Only onResume is called. Shall I do everything in onResume? In that case what's the best way to keep the value of the current category and retrieve it when going back to the ListActivity from the article detail?
Thanks
public class Home extends ListActivity implements OnItemClickListener{
private DBAdapter dbAdapter;
private HomeListAdapter adapter; //extends SimpleCursorAdapter
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// open database
dbAdapter = new DBAdapter(this);
dbAdapter.open();
/* more stuff */
getArticlesbyCat(category);
/* more stuff */
}
private void getArticles(int category){
Cursor c = dbAdapter.fetchArtByCat(category);
c.moveToFirst();
startManagingCursor(c);
String[] from = new String[] {};
int[] to = new int[] {};
setListAdapter(new HomeListAdapter(this, R.layout.article_row, c, from, to));
adapter.notifyDataSetChanged();
c.close();
}
#Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
/* Go to article page */
}
#Override
protected void onPause() {
super.onPause();
// close database
dbAdapter.close();
}
}
EDIT
public class HomeListAdapter extends SimpleCursorAdapter {
private int mLayout;
private Cursor mCursor;
private Resources mResources;
// Column index
private int mCatInd;
private int mURLPicInd;
private int mIntroInd;
private int mTitleInd;
private LayoutInflater mLayoutInflater;
private final ImageDownloader mImageLoader;
private final class ViewHolder {
public TextView category;
public ImageView image;
public TextView intro;
public TextView title;
}
public HomeListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mLayout = layout;
this.mCursor = c;
this.mCatInd = mCursor.getColumnIndex(DBAdapter.KEY_CATEGORY_NAME);
this.mURLPicInd = mCursor.getColumnIndex(DBAdapter.KEY_URL_PIC);
this.mIntroInd = mCursor.getColumnIndex(DBAdapter.KEY_INTRO);
this.mTitleInd = mCursor.getColumnIndex(DBAdapter.KEY_TITLE);
this.mLayoutInflater = LayoutInflater.from(context);
mResources = context.getResources();
mImageLoader = new ImageDownloader(mResources,
((BitmapDrawable)mResources.getDrawable(R.drawable.default_row_pic)).getBitmap(), 1);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.category = (TextView) convertView.findViewById(R.id.cat);
viewHolder.image = (ImageView) convertView.findViewById(R.id.picture);
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.intro = (TextView) convertView.findViewById(R.id.intro);
viewHolder.intro.setMaxLines(3);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
String category = mCursor.getString(mCatInd);
String title = mCursor.getString(mTitleInd);
String intro = mCursor.getString(mIntroInd);
String url_pic = mCursor.getString(mURLPicInd);
viewHolder.category.setText(category);
viewHolder.title.setText(title);
viewHolder.intro.setText(intro);
if(!url_pic.equals("")){
mImageLoader.download(url_pic, (ImageView) viewHolder.image);
}
else {
viewHolder.image.setImageResource(R.drawable.default_row_pic);
}
}
return convertView;
}
}
OK, so I have a cursor adapter that I cobbled together from various source and mostly seems to work -except my name fields. I have two checkboxes on a listview for each name but my names are all coming out the same (the first name)
Anyone spot the problem I've create? Your help would be appreciated.
public class MyDataAdapter extends SimpleCursorAdapter {
private Cursor c;
private Context context;
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<Boolean> itemCheckedHere = new ArrayList<Boolean>();
private ArrayList<Boolean> itemCheckedLate = new ArrayList<Boolean>();
private ArrayList<Integer> itemCheckedIdx = new ArrayList<Integer>();
int idxCol;
int idx;
// itemChecked will store the position of the checked items.
public MyDataAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
this.c = c;
this.context = context;
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
itemCheckedHere.add(i, false); // initializes all items value with false
itemCheckedLate.add(i, false); // initializes all items value with false
}
}
public View getView(final int pos, View inView, ViewGroup parent) {
TextView studentName;
ImageView studentPhoto;
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(R.layout.show_attendance, null);
}
final CheckBox cBoxH = (CheckBox) inView.findViewById(R.id.attend);
final CheckBox cBoxL = (CheckBox) inView.findViewById(R.id.late);
// set up name field
studentName = (TextView) inView.findViewById(R.id.stuname);
if (studentName != null)
{
int index = c.getColumnIndex(gradeBookDbAdapter.KEY_NAME);
String name = c.getString(index);
studentName.setText(name);
}
cBoxH.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.attend);
if (cb.isChecked()) {
itemCheckedHere.set(pos, true);
// do some operations here
} else if (!cb.isChecked()) {
itemCheckedHere.set(pos, false);
// do some operations here
}
}
});
cBoxL.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v.findViewById(R.id.late);
if (cb.isChecked()) {
itemCheckedLate.set(pos, true);
// do some operations here
} else if (!cb.isChecked()) {
itemCheckedLate.set(pos, false);
// do some operations here
}
}
});
cBoxH.setChecked(itemCheckedHere.get(pos)); // this will Check or Uncheck the
cBoxL.setChecked(itemCheckedLate.get(pos)); // this will Check or Uncheck the
// CheckBox in ListView
// according to their original
// position and CheckBox never
// loss his State when you
// Scroll the List Items.
return inView;
}
The cursor in the adapter is not set to the correct row.
First of all you should get rid of your own member variables for the cursor and the context! Then try to implement the bindView method of the CursorAdapter, it will provide the cursor already set to the current row:
public class MyDataAdapter extends SimpleCursorAdapter {
private ArrayList<String> list = new ArrayList<String>();
private ArrayList<Boolean> itemCheckedHere = new ArrayList<Boolean>();
private ArrayList<Boolean> itemCheckedLate = new ArrayList<Boolean>();
private ArrayList<Integer> itemCheckedIdx = new ArrayList<Integer>();
// itemChecked will store the position of the checked items.
public MyDataAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
for (int i = 0; i < c.getCount(); i++) {
itemCheckedHere.add(i, false); // initializes all items value with false
itemCheckedLate.add(i, false); // initializes all items value with false
}
}
public void bindView (View inView, Context context, Cursor cursor){
super.bindView(inView,context,cursor);
TextView studentName;
ImageView studentPhoto;
//inView is never null in bindView
final CheckBox cBoxH = (CheckBox) inView.findViewById(R.id.attend);
final CheckBox cBoxL = (CheckBox) inView.findViewById(R.id.late);
// set up name field
studentName = (TextView) inView.findViewById(R.id.stuname);
if (studentName != null)
{
int index = cursor.getColumnIndex(gradeBookDbAdapter.KEY_NAME);
String name = cursor.getString(index);
studentName.setText(name);
}
//your other code
}
//other methods
}
You're going to kick yourself. You just forgot to move the cursor to the position corresponding to the index in the ListView:
c.moveToPosition(pos)