For EfficientAdapter What code I need to use under onListItemClick to get text of selected item?
I tried:
str=(String) ((TextView)l.getItemAtPosition(position)).getText()
But this only brings CastException, since it fetches the LinearLayout view holding the textview and imageview (see code here)
Please help!
Some of the code:
public class Bookmarks extends ListActivity {
public static Typeface mFace;
public EfficientAdapter eff;
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return DAT.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_text, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.text.setTypeface(mFace);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(DAT[position]);
return convertView;
}
static class ViewHolder {
TextView text;
}
}
public Object getItem(int position) {
return position;
}
public void onResume(Bundle icicle) {
eff.notifyDataSetChanged();
}
protected void onListItemClick(ListView l, View v, int position, long id) {
//////////CRASHES on next line!!!!!!!!!!!!!!!!!!
TextView tv = (TextView) l.getItemAtPosition(position);
String str = tv.getText().toString();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
eff = (new EfficientAdapter(this));
setListAdapter(eff);
registerForContextMenu(getListView());
}
}
There isn’t really enough information in your question (see my comment above), but here’s a guess at an answer:
First,
getText()is documented to return a CharSequence, not a String. It might return a String, but you don’t know that it does. So it would be safer to write:Second, if that doesn’t work, try breaking down that statement so you can get a better idea of where the exception is coming from. Something like this, perhaps, might be clearer:
EDIT based on your update:
1) If you’re going to implement
onListItemClick, be sure that you begin the method by calling up to the base class, as shown below.2) Here’s the problem: (I realized this after copying and pasting in a different example, which I think won’t be necessary now): ListView.getItemAtPosition doesn’t return a View at all; it returns an item from your Adapter (a Cursor, an array entry, whatever.) To get the TextView, you need to use
findViewById, or better still, your ViewHolder. I think this will work:If you’re still having problems, please copy and paste the traceback for the exception that you’re getting.