How do I get a string from my cursor into my putExtra call in an onItemClick for a ListView? I need to grab the string from my DB column named 'gotoURL' into the:
i.putExtra("Url", ???).
...of my onItemClick in the Activity. Sample code would be helpful for the learning. Thnx!!
My Activity has:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_view2);
final ListView lv = getListView();
activityTitle = (TextView) findViewById(R.id.titleBarTitle);
activityTitle.setText("ADVISORY CIRCULATORS");
displayResultList();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
// #Override
public void onItemClick(AdapterView<?> a, View v, int position,long id)
{
Toast.makeText(List_AC.this, "Clicked!", Toast.LENGTH_LONG).show();
Object o = lv.getItemAtPosition(position);
Adapter_AC fullObject = (Adapter_AC)o;
Intent i = new Intent(List_AC.this, DocView.class);
//i.putExtra("url", Adapter_AC.gotoURL);
startActivity(i);
}
});
}
private void displayResultList() {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File dbfile = new File(extStorageDirectory
+ "/XXX/XXX/dB/XXX.db");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
null);
Cursor databaseCursor = db.rawQuery(
"SELECT * FROM AC_list ORDER BY `label` ASC", null);
Adapter_AC databaseListAdapter = new Adapter_AC(this,
R.layout.list_item, databaseCursor, new String[] { "label",
"title", "description" }, new int[] { R.id.label,
R.id.listTitle, R.id.caption });
databaseListAdapter.notifyDataSetChanged();
this.setListAdapter(databaseListAdapter);
} else if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_UNMOUNTED)) {
Log.i("tag", "SDCard is NOT writable/mounted");
Alerts.sdCardMissing(this);
}
}
}
And my Adapter:
public class Adapter_AC extends SimpleCursorAdapter {
private Cursor dataCursor;
private LayoutInflater mInflater;
public Adapter_AC(Context context, int layout, Cursor dataCursor,
String[] from, int[] to) {
super(context, layout, dataCursor, from, to);
this.dataCursor = dataCursor;
mInflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.label);
holder.text2 = (TextView) convertView.findViewById(R.id.listTitle);
holder.text3 = (TextView) convertView.findViewById(R.id.caption);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
dataCursor.moveToPosition(position);
int label_index = dataCursor.getColumnIndex("label");
String label = dataCursor.getString(label_index);
int title_index = dataCursor.getColumnIndex("title");
String title = dataCursor.getString(title_index);
int description_index = dataCursor.getColumnIndex("description");
String description = dataCursor.getString(description_index);
int goto_index = dataCursor.getColumnIndex("gotoURL");
String gotoURL = dataCursor.getString(goto_index);
holder.text1.setText(label);
holder.text2.setText(title);
holder.text3.setText(description);
return convertView;
}
static class ViewHolder {
TextView text1;
TextView text2;
TextView text3;
}
}
You can use the CursorAdapter's getItem() method to get a Cursor pointing to the current id. Like so:
...
Cursor cursor = adapter.getItem(id);
i.putExtra("url", cursor.getString(cursor.getColumnIndex("gotoURL")));
...
Note that I suspect you'll need to include that column in your projection, like so:
Adapter_AC databaseListAdapter = new Adapter_AC(this,
R.layout.list_item, databaseCursor, new String[] { "label",
"title", "description", "gotoURL" }, new int[] { R.id.label,
R.id.listTitle, R.id.caption, R.id.dummy });
And create a dummy (View.GONE) invisible field for it so that the data is pulled in the cursor.
You might try using the 'Tag' field in the ListView: set it to the correct value when creating and reading it to get the right value when clicked...
Related
I want to display a list of songs on clicking the album in a grid.
Here's my code for DisplayAlbum extends AppCompatActivity implements LoaderManager.LoaderCallbacks
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.album_detail);
Intent i = getIntent();
b = i.getExtras();
String str;
// if((str =(String) b.getCharSequence("album_name"))!= null)
// Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
val = new String[]{(String) b.getCharSequence("album_name")};
ListView lv = (ListView) findViewById(R.id.al_songs);
mAdapter = new DisplaySongsAdapter(this, null);
lv.setAdapter(mAdapter);
}
static final String[] ALBUM_DETAIL_PROJECTION = { MediaStore.Audio.Media._ID,MediaStore.Audio.Media.ALBUM_ID,MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.DURATION};
String where = MediaStore.Audio.Media.ALBUM + "=?";
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String orderby = MediaStore.Audio.Media.TITLE;
return new CursorLoader(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,ALBUM_DETAIL_PROJECTION, where, val, orderby);
}
And this is the code for DisplaySongsAdapter extends CursorAdapter
public DisplaySongsAdapter(Context context, Cursor c) {
super(context, c);
mcontext=context;
nInflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView songTitle = (TextView) view.findViewById(R.id.songTitle);
songTitle.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
TextView alname = (TextView) view.findViewById(R.id.al_name);
alname.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM)));
TextView artist = (TextView) view.findViewById(R.id.songArtist);
artist.setText(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
ImageView albumArt = (ImageView) view.findViewById(R.id.list_image);
albumArt.setScaleType(ImageView.ScaleType.FIT_XY);
ImageView albumimg = (ImageView) view.findViewById(R.id.al_art);
albumimg.setScaleType(ImageView.ScaleType.FIT_XY);
ImageButton listmenu = (ImageButton) view.findViewById(R.id.expanded_menu);
listmenu.setOnClickListener(overflowClickListener);
Long albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
Bitmap img = getAlbumart(context,albumId);
if(img != null) {
albumArt.setImageBitmap(img);
albumimg.setImageBitmap(img);
}
else{
Bitmap def = getDefaultAlbumArt(context);
albumArt.setImageBitmap(def);
albumimg.setImageBitmap(img);
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = nInflater.inflate(R.layout.song_item, parent, false);
return view;
}
But the activity doesnt populate the listview. It simply shows a blank inflated layout. Why is that the case? Where did I go wrong?
It might be related to the fact that you don't actually feed any items in the adapter :-)
mAdapter = new DisplaySongsAdapter(this, null);
I solved it using a SimpleCursorAdapter. However I would still like to know a way around with LoaderManager
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 am now using a custom simplecursoradapter to get set data to a listview, in every entry of the listview there is a button and I want to assign a url to each of them so when you click it, jump to another webview activity with the url, but I don't know how to get the url in the adapter, can anyone explain how it works? with an example code snippet would be perfect
My adapter:
public class ChannelAdapter extends SimpleCursorAdapter{
private LayoutInflater mInflater;
private List<ChannelPoster> items;
private Context mContext;
private String dblink;
public ChannelAdapter(Context context, int layout, Cursor c, String[] from,
int[] to) {
super(context, layout, c, from, to);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position,View convertView,ViewGroup par)
{
ViewHolder holder;
if(convertView == null)
{
convertView = mInflater.inflate(R.layout.channelview, null);
holder = new ViewHolder();
holder.image = (ImageView) convertView.findViewById(R.id.poster);
holder.text = (TextView) convertView.findViewById(R.id.channel);
holder.button = (ImageButton) convertView.findViewById(R.id.douban);
holder.button.setTag(curItem.url);
holder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = (String) view.getTag();
Intent myIntent = new Intent(view.getContext(), Doubanframe.class);
myIntent.putExtra("dblink", dblink);
view.getContext().startActivity(myIntent);
}
});
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ChannelPoster tmpN=(ChannelPoster)items.get(position);
holder.text.setText(tmpN.getChannel());
holder.image.setImageResource(tmpN.getPoster());
holder.button.setTag(curItem.url);
holder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = (String) view.getTag();
Intent myIntent = new Intent(view.getContext(), Doubanframe.class);
myIntent.putExtra("dblink", dblink);
view.getContext().startActivity(myIntent);
}
});
return convertView;
}
private class ViewHolder
{
ImageView image;
TextView text;
ImageButton button;
}
}
This is how I use it
mDB = new ChannelDB(this);
String[] columns = {mDB.KEY_ID, mDB.KEY_POSTER, mDB.KEY_CHANNEL, mDB.KEY_PATH, mDB.KEY_DBLINK};
String table = mDB.channelS_TABLE;
c = mDB.getHandle().query(table, columns, null, null, null, null, null);
startManagingCursor(c);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.channelview,
c,
new String[] {mDB.KEY_POSTER, mDB.KEY_CHANNEL, mDB.KEY_DBLINK},
new int[] { R.id.poster, R.id.channel, R.id.douban});
I have a ListView that populates data from a DB into a complex-ListView. A string in the 'gotoURL' column of the db is a URL to load a link into a WebView using the putExtra intent. When I click on a ListItem to go to the next Activity, my method grabs the correct string data, but it pulls the string from the wrong db row. As per my 'log.i(...);' indicates in the DDMS, the correct id row is selected but the string from the column is pulled from the first row id and not from the row id selected(???) - it does this on any ListItem selected.
I cant figure out how to write this to function correctly. Plz help with example code. Thank-you.
My Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_view2);
activityTitle = (TextView) findViewById(R.id.titleBarTitle);
activityTitle.setText("ADVISORY CIRCULATORS");
displayResultList();
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos,
long id) {
String url = "";
lv.getItemIdAtPosition(pos);
TextView tv = (TextView) lv.findViewById(R.id.dummy);
url = (String) tv.getTag();
LLog.i("tag", "ID:" + id + "URL: " + url + " selected");
Intent i = new Intent(List_AC.this, DocView.class);
i.putExtra("url", url);
startActivity(i);
}
});
}
private void displayResultList() {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File dbfile = new File(extStorageDirectory
+ "/Aero-Technologies/flyDroid/dB/flyDroid.db");
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
null);
Cursor databaseCursor = db.rawQuery(
"SELECT * FROM AC_list ORDER BY `label` ASC", null);
Adapter_AC databaseListAdapter = new Adapter_AC(this,
R.layout.list_item, databaseCursor, new String[] { "label",
"title", "description", "gotoURL" }, new int[] {
R.id.label, R.id.listTitle, R.id.caption,
R.id.dummy });
databaseListAdapter.notifyDataSetChanged();
this.setListAdapter(databaseListAdapter);
} else if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_UNMOUNTED)) {
Log.i("tag", "SDCard is NOT writable/mounted");
Alerts.sdCardMissing(this);
}
}
}
My Adapter:
public class Adapter_AC extends SimpleCursorAdapter {
static Cursor dataCursor;
private LayoutInflater mInflater;
public Adapter_AC(Context context, int layout, Cursor dataCursor,
String[] from, int[] to) {
super(context, layout, dataCursor, from, to);
this.dataCursor = dataCursor;
mInflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.label);
holder.text2 = (TextView) convertView.findViewById(R.id.listTitle);
holder.text3 = (TextView) convertView.findViewById(R.id.caption);
holder.text4 = (TextView) convertView.findViewById(R.id.dummy);
holder.text4.setVisibility(View.GONE);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
dataCursor.moveToPosition(position);
int label_index = dataCursor.getColumnIndex("label");
String label = dataCursor.getString(label_index);
int title_index = dataCursor.getColumnIndex("title");
String title = dataCursor.getString(title_index);
int description_index = dataCursor.getColumnIndex("description");
String description = dataCursor.getString(description_index);
int goto_index = dataCursor.getColumnIndex("gotoURL");
String gotoURL = dataCursor.getString(goto_index);
holder.text1.setText(label);
holder.text2.setText(title);
holder.text3.setText(description);
//holder.text4.setText(gotoURL);
holder.text4.setTag(gotoURL);
return convertView;
}
static class ViewHolder {
TextView text1;
TextView text2;
TextView text3;
TextView text4;
}
}
OK your onItemClick has a few things wrong (see inline comments):
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos,
long id) {
String url = "";
lv.getItemIdAtPosition(pos); //you're never storing this value, but that's not the problem
//This "lv" is the main problem: you're asking the LISTVIEW for the TextView
//That's why you always get the first one. You should be asking the current view (v) instead
TextView tv = (TextView) lv.findViewById(R.id.dummy);
url = (String) tv.getTag();
LLog.i("tag", "ID:" + id + "URL: " + url + " selected");
Intent i = new Intent(List_AC.this, DocView.class);
i.putExtra("url", url);
startActivity(i);
}
});
However, why are you trying to use the data in the holder instead of getting the backing tiem?
I've got ListActivity and I am using custom CursorAdapter.
In each item of the list I've got also checkbox...
Now I have in my list screen a perm button, when you press on it,
It should find all the checkboxes which are 'checked' and do some operations on the item which it's checkbox is 'checked'.
How can I retrieve all the checked ones?
I've done focusable:false, so I can use OnClickListener, but I don't know how farther then
this..
Thanks,
some code:
This is in my ListActivity class:
final String columns[] = new String[] { MyUsers.User._ID,
MyUsers.User.MSG, MyUsers.User.LOCATION };
int[] to = new int[] { R.id.toptext, R.id.bottomtext,R.id.ChkBox,
R.id.Location};
Uri myUri = Uri.parse("content://com.idan.datastorageprovider/users");
Cursor cursor = getContentResolver().query(myUri, columns, null, null, null);
startManagingCursor(cursor);
ListCursorAdapter myCursorAdapter=new ListCursorAdapter(this,R.layout.listitem, cursor, columns, to);
this.setListAdapter(myCursorAdapter);
and this is my Custom Cursor adapter class:
public class ListCursorAdapter extends SimpleCursorAdapter
{
private Context context;
private int layout;
public ListCursorAdapter(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);
return v;
}
#Override
public void bindView(View v, Context context, Cursor c)
{
TextView topText = (TextView) v.findViewById(R.id.toptext);
if (topText != null)
{
topText.setText("");
}
int nameCol = c.getColumnIndex(MyUsers.User.MSG);
String name = c.getString(nameCol);
TextView buttomTxt = (TextView) v.findViewById(R.id.bottomtext);
if (buttomTxt != null)
{
buttomTxt.setText("Message: "+name);
}
nameCol = c.getColumnIndex(MyUsers.User.LOCATION);
name = c.getString(nameCol);
TextView location = (TextView) v.findViewById(R.id.Location);
if (locationLinkTxt != null)
{
locationLinkTxt.setText(name);
}
}
//Modify to meet your needs
String[] from = new String[]{ YourDbAdapter.KEY_WORDS_ROWID, YourDbAdapter.KEY_WORDS_ROWID};
int[] to = new int[]{ R.id.row_item_checkbox};
mAdapter = new SimpleCursorAdapter(this, R.layout.row_item_with_checkbox, yourDbCursor, from, to);
mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(view.getId() == R.id.myCheckbox )
{
CheckBox cb = (CheckBox) view;
cb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final long id = cursor.getLong(columnIndex); //Your row id
//You can do the necessary work here such as adding to an List or somehting
}
});
return true;
}
return false;
}
});