I am trying to implement a listview with a custom adapter. The problem is that it crashes whenever a onItemClickListener event is triggered.
java.lang.ClassCastException: imp.translator.diana.lang.CardItemData
cannot be cast to java.lang.String
at imp.translator.diana.lang.Speak$1.onItemClick(Speak.java:41)
at android.widget.AdapterView.performItemClick
This is my class:
final ListView list = (ListView) findViewById(R.id.list_view);
list.addHeaderView(new View(this));
list.addFooterView(new View(this));
BaseInflaterAdapter<CardItemData> adapter = new BaseInflaterAdapter<CardItemData>(new CardInflater());
CardItemData data = new CardItemData("Translate");
adapter.addItem(data, false);
CardItemData data2 = new CardItemData("Voice to Text");
adapter.addItem(data2, false);
CardItemData data3 = new CardItemData("Record");
adapter.addItem(data3, false);
CardItemData data4 = new CardItemData("Info");
adapter.addItem(data4, false);
list.setAdapter(adapter);
list.setClickable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView myAdapter, View myView, int position, long mylng) {
String selectedFromList = (String) (myAdapter.getItemAtPosition(position));
}
});
and my adapter:
public class BaseInflaterAdapter<T> extends BaseAdapter
{
private List<T> m_items = new ArrayList<T>();
private IAdapterViewInflater<T> m_viewInflater;
public BaseInflaterAdapter(IAdapterViewInflater<T> viewInflater)
{
m_viewInflater = viewInflater;
}
public BaseInflaterAdapter(List<T> items, IAdapterViewInflater<T> viewInflater)
{
m_items.addAll(items);
m_viewInflater = viewInflater;
}
public void setViewInflater(IAdapterViewInflater<T> viewInflater, boolean notifyChange)
{
m_viewInflater = viewInflater;
if (notifyChange)
notifyDataSetChanged();
}
public void addItem(T item, boolean notifyChange)
{
m_items.add(item);
if (notifyChange)
notifyDataSetChanged();
}
public void addItems(List<T> items, boolean notifyChange)
{
m_items.addAll(items);
if (notifyChange)
notifyDataSetChanged();
}
public void clear(boolean notifyChange)
{
m_items.clear();
if (notifyChange)
notifyDataSetChanged();
}
#Override
public int getCount()
{
return m_items.size();
}
#Override
public Object getItem(int pos)
{
return getTItem(pos);
}
public T getTItem(int pos)
{
return m_items.get(pos);
}
#Override
public long getItemId(int pos)
{
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent)
{
return m_viewInflater != null ? m_viewInflater.inflate(this, pos, convertView, parent) : null;
}
}
and the CardItemData:
public class CardItemData
{
private String m_text1;
public CardItemData(String text1)
{
m_text1 = text1;
}
public String getText1()
{
return m_text1;
}
}
Any idea what might be wrong here?
java.lang.ClassCastException: imp.translator.diana.lang.CardItemData
cannot be cast to java.lang.String
the above exception was due to
String selectedFromList = (String) (myAdapter.getItemAtPosition(position)); here you are try to convert CardItemData into String
try this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView myAdapter, View myView, int position, long mylng) {
CardItemData selectedFromList = (CardItemData) (myAdapter.getItemAtPosition(position));
String pos = selectedFromList.getText1();
}
});
Any idea what might be wrong here?
your getItem is returning T which is, in your case, an instance of CardItemData, but here:
String selectedFromList = (String) (myAdapter.getItemAtPosition(position));
you are casting it to String. You probably want to cast it to CardItemData. Btw, Java supports covariant return types, so you should be able to use
#Override
public T getItem(int pos) {
return m_items.get(pos);
}
Its a typecast issue, you are type casting " CardItemData " to " String "
String selectedFromList = (String) (myAdapter.getItemAtPosition(position));
use "getItem" method to get clicked " CardItemData " item.
Check the link given below
Android Docs link
Related
I made a spinner in which im using a arrayadapter to populate it with images and text. on OnItemSelected i want to select only and only the text not the image.
Here is my code for the MainActivity.java
ArrayList<ItemData> list = new ArrayList<>();
list.add(new ItemData("Select Plan Category",R.drawable.ic_bars));
list.add(new ItemData("Hookah",R.drawable.ic_006_hookah));
list.add(new ItemData("Drinks",R.drawable.ic_005_pint));
list.add(new ItemData("Gedi",R.drawable.ic_004_racing));
list.add(new ItemData("Snacks",R.drawable.ic_003_chips));
list.add(new ItemData("Shopping",R.drawable.ic_002_cart));
list.add(new ItemData("Bownling",R.drawable.ic_001_bowling));
SpinnerAdapter adapter = new SpinnerAdapter(getActivity(), R.layout.spinner_layout,R.id.categoryText,list);
categorySpinnerjava.setAdapter(adapter);
Here is my code for the ItemData.java
public class ItemData {
private String planCategorytext = "";
Integer imageId;
public ItemData(String text, Integer imageId)
{
this.planCategorytext=text;
this.imageId=imageId;
}
public String getPlanCategorytext() {
return planCategorytext;
}
public void setPlanCategorytext(String planCategorytext) {
this.planCategorytext = planCategorytext;
}
public Integer getImageId() {
return imageId;
}
public void setImageId(Integer imageId) {
this.imageId = imageId;
}
}
And here is my code for the SpinnerAdapter.java(that is extending the ArrayAdapter
int groupid;
Activity getActivity;
ArrayList<ItemData> list;
LayoutInflater inflater;
public SpinnerAdapter(Activity context, int groupid, int id, ArrayList<ItemData> list) {
super(context, id,list);
this.list=list;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.groupid=groupid;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View itemView = inflater.inflate(groupid,parent,false);
ImageView imageView=(ImageView)itemView.findViewById(R.id.categoryVector);
imageView.setImageResource(list.get(position).getImageId());
TextView textView = (TextView)itemView.findViewById(R.id.categoryText);
textView.setText(list.get(position).getPlanCategorytext());
return itemView;
}
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
return getView(position,convertView,parent);
}
I want to only select the text not the image. And when i normally do the
String spinnerselection = categorySpinnerjava.getSelectedItem().toString();
It gives me a output of "applicationpackage.ItemData#randomnumbers"
you are getting this error because
"applicationpackage.ItemData#randomnumbers"
your categorySpinnerjava.getSelectedItem(); return your model class ItemData not a String
Try this
ItemData itemData = (ItemData) categorySpinnerjava.getSelectedItem();
String data= itemData.getPlanCategorytext();
Integer imageId = itemData.getImageId();
You can get the selected spinner item's text in the following way:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
String selectedText=list.get(pos).getPlanCategorytext();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
OR
String selectedItemText=list.get(spinner.getSelectedItemPosition()).getPlanCategorytext();
Where list is the arraylist with ItemData which you used above to populate the data in spinner.
Also about this:
String spinnerselection = categorySpinnerjava.getSelectedItem().toString();
You have to replace categorySpinnerjava.getSelectedItem().toString(); with list.get(spinner.getSelectedItemPosition()).getPlanCategorytext();
Try implementing using Interface.
Set text data inside SpinnerAdapter and extend Interface in Activity class to get the selected text
Try the following:
String spinnerselection = ((ItemData) categorySpinnerjava.getSelectedItem()).getPlanCategorytext();
Didn't try it yet, but in theory it should work.
Try like this,
ItemData spinnerselection = (ItemData)categorySpinnerjava.getSelectedItem();
String plan = spinnerselection.getPlanCategorytext();
Override getItem() in your adapter. Cause getSelectedItem() return :
adapter.getItem(position);
#Override
public String getItem(int position) {
return list.get(position);
}
I have used Customized ListView And not ExtendedListView. i have taken relative layout in order to show it as sub_list. By default i have set the visibilty of this sub_list relative layout as GONE. And on the click of any listItem that relative layout(by default set as gone) will appear on the screen respectively. But When I click on any of the rows the sub_list appear for each row simultaneously. What i want is that it should be shown only for one row at a time. I have already checked this similar [question]: How to modify only one row at a time in Listview? and modified my code but still i am unable to achieve my goal.
Here is my pieace of code:
public class CustomAdapter extends BaseAdapter {
Activity context;
ArrayList<String> s_date,c_number,d_ration,s_time,download_path,a_number,a_name,dt_number;
int flag=0,temp=1,position;
String mUrl;
int posview;
private int selectedIndex;
CustomAdapter(Activity context, ArrayList<String> start_date, ArrayList<String> caller_number, ArrayList<String> duration,ArrayList<String> start_time, ArrayList<String> download_path, ArrayList<String> agent_number, ArrayList<String> agent_name,ArrayList<String> dt_num)
{
this.context=context;
this.s_date=start_date;
this.c_number=caller_number;
this.d_ration=duration;
this.s_time=start_time;
this.download_path=download_path;
this.a_number=agent_number;
this.a_name=agent_name;
this.dt_number=dt_num;
selectedIndex = -1;
}
public void setSelectedIndex(int ind)
{
selectedIndex = ind;
notifyDataSetChanged();
}
#Override
public int getCount() {
return s_date.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int pos, final View v, ViewGroup g)
{
//LayoutInflater l=context.getLayoutInflater();
//View rowView=l.inflate(R.layout.log_layout,null,true);
posview=pos;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View row = inflater.inflate(R.layout.list_item, g, false);
TextView start_date = (TextView) row.findViewById(R.id.start_date);
start_date.setText(s_date.get(pos));
TextView caller_number = (TextView) row.findViewById(R.id.caller_number);
caller_number.setText(c_number.get(pos));
TextView duration = (TextView) row.findViewById(R.id.duration);
duration.setText(d_ration.get(pos));
TextView start_time = (TextView) row.findViewById(R.id.start_time);
start_time.setText(s_time.get(pos));
TextView agent_name = (TextView) row.findViewById(R.id.agent_name);
agent_name.setText(a_name.get(pos));
TextView agent_number = (TextView) row.findViewById(R.id.agent_number);
agent_number.setText(a_number.get(pos));
TextView dt_numb=(TextView)row.findViewById(R.id.dt_number);
dt_numb.setText("MHL No. -"+dt_number.get(pos));
RelativeLayout r = (RelativeLayout)row.findViewById(R.id.sub_layout);
r.setVisibility(position == posview ? View.VISIBLE : View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
posview=pos;
notifyDataSetChanged();
}
});
return row;
}
}
Previously my code was:
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//setSelectedIndex(view.getId());
RelativeLayout sub_list = (RelativeLayout) row.findViewById(R.id.sub_layout);
sub_list.setVisibility(View.VISIBLE);
//notifyDataSetChanged();
}
});
I am getting all the data dynamically. This is how i'm using the adapter in MainActivity:
CustomAdapter a=new CustomAdapter(MainScreen.this,start_date,caller_number,duration,start_time,download_path,agent_number,agent_name,dt_number);
data_list.setAdapter(a);
In this start_date caller_number etc are arraylist.This is how i'm parsing data in MainActivity.
JSONObject responseObject = new JSONObject(response);
JSONObject callLog = responseObject.getJSONObject("call_log");
Iterator<String> phoneNumbers = callLog.keys();
while (phoneNumbers.hasNext()) {
String number = phoneNumbers.next();
// Log.v("string number",number);
JSONObject numberLog = callLog.getJSONObject(number);
Iterator<String> callEntries = numberLog.keys();
while (callEntries.hasNext()) {
String entry = callEntries.next();
//Log.v("unique keys are",entry);
JSONObject entryObject = numberLog.getJSONObject(entry);
jsonArray.put(entryObject.getString("start_date"));
jsonArray.put(entryObject.getString("start_time"));
jsonArray.put(entryObject.getString("end_date"));
jsonArray.put(entryObject.getString("end_time"));
jsonArray.put(entryObject.getString("recording_path"));
String startDate = entryObject.getString("start_date");
start_date.add(startDate);
String startTime = entryObject.getString("start_time");
start_time.add(startTime);
String endDate = entryObject.getString("end_date");
String endTime = entryObject.getString("end_time");
String call_sdate = entryObject.getString("call_sdate");
String call_edate = entryObject.getString("call_edate");
String call_type = entryObject.getString("call_type");
String caller = entryObject.getString("caller");
caller_number.add(caller);
String duartion = entryObject.getString("duartion");
String call_duartion = entryObject.getString("call_duartion");
duration.add(call_duartion);
String dtmf = entryObject.getString("dtmf");
String dt_num = entryObject.getString("dt_number");
dt_number.add((dt_num));
String recording_path = entryObject.getString("recording_path");
download_path.add(recording_path);
String agent_mobile = entryObject.getString("agent_mobile");
agent_number.add(agent_mobile);
String a_name = entryObject.getString("agent_name");
agent_name.add(a_name);
Create two variables :
Map<Integer, View> lastExpanded = new HashMap<>();
int lastExpandedPosition =-1;
Create a function in your adapter :
private void expand(int i, View layout){
if(!lastExpanded.containsKey(i)){
layout.setVisibility(View.VISIBLE);
lastExpanded.put(i, layout);
if(lastExpanded.containsKey(lastExpandedPosition)){
expand(lastExpandedPosition, lastExpanded.get(lastExpandedPosition));
}
lastExpanded.remove(lastExpandedPosition);
lastExpandedPosition = i;
lastExpanded.put(lastExpandedPosition, layout);
}else{
layout.setVisibility(View.GONE);
lastExpandedPosition = -1;
lastExpanded.remove(i);
}
}
now,
final RelativeLayout layout = (RelativeLayout) row.findViewById(R.id.b);
layout.setVisibility(View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
expand(i, layout);
}
});
You can acheive this easily with expandable listview and your adapter class should extend BaseExpandableListAdapter
in activity
private int lastExpandedPosition = -1;
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
final int groupPosition, long id) {
// TODO Auto-generated method stub
if (parent.isGroupExpanded(groupPosition)) {
expListView
.collapseGroup(lastExpandedPosition);
} else {
expListView.expandGroup(groupPosition);
}
return true;
}
});
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
// TODO Auto-generated method stub
if (lastExpandedPosition != -1
&& groupPosition != lastExpandedPosition) {
expListView
.collapseGroup(lastExpandedPosition);
}
lastExpandedPosition = groupPosition;
}
});
You have to use ArrayList which contents as your data while you click on the item.
public class DataModel{
private String s_date,c_number,d_ration,s_time,download_path,a_number,a_name,dt_number;
private boolean isChildVisible;
..... create it's setter and getter methods.
}
when itemclick is called that time you should update the flag of isChildVisible for that position.
public void setSelectedIndex(int ind)
{
arrayListDataModel.get(ind).setIsChildVisible(true);
notifyDataSetChanged();
}
In your getview method :
public View getView(final int pos, final View v, ViewGroup g)
{
----your initialization code.
RelativeLayout r = (RelativeLayout)row.findViewById(R.id.sub_layout);
r.setVisibility(arrayListDataModel.get(pos).isChildVisible() ? View.VISIBLE : View.GONE);
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setSelectedIndex(pos);
}
});
return row;
}
parse the data with below code :
final ArrayList<DataModel> dataModelList = new ArrayList<>();
while (callEntries.hasNext()) {
DataModel dataModel = new DataModel();
String entry = callEntries.next();
//Log.v("unique keys are",entry);
JSONObject entryObject = numberLog.getJSONObject(entry);
jsonArray.put(entryObject.getString("start_date"));
jsonArray.put(entryObject.getString("start_time"));
jsonArray.put(entryObject.getString("end_date"));
jsonArray.put(entryObject.getString("end_time"));
jsonArray.put(entryObject.getString("recording_path"));
String startDate = entryObject.getString("start_date");
dataModel.setStartDate(startDate);
String startTime = entryObject.getString("start_time");
dataModel.setStartTime(startTime);
...... same as above for others fields
dataModelList.add(dataModel);
}
So what i m trying to do is get a String value on click of an item.
But through this code when i click on the item i get the position of the converter class or something like that,which i dont understand.
"MainActivity$Converter#30e6eb1" in the toast. I just want the subject part to Appear in the Toast.
#Override
protected void onPostExecute(String result) {
JSONObject jsonObject;
JSONArray jsonArray;
CustomAdapter customAdapter;
ListView listview;
listview = (ListView) findViewById(R.id.xlistview);
customAdapter = new CustomAdapter(getApplicationContext(), R.layout.row_layout);
listview.setAdapter(customAdapter);
//Log.d("json_raw_home",result);
if (result != null) { //Log.d("post execute",result);
try {
jsonObject = new JSONObject(result);
jsonArray = jsonObject.getJSONArray("data");
int count = 0;
String subject, description;
while (count < jsonArray.length()) {
JSONObject JO = jsonArray.getJSONObject(count);
subject = JO.getString("subject");
description = JO.getString("description");
Converter converter = new Converter(subject, description);
customAdapter.add(converter);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(getApplicationContext(),item, Toast.LENGTH_LONG).show();}
});
}
}
public class CustomAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomAdapter(Context context, int resource) {
super(context, resource);
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row==null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
contactHolder=new ContactHolder();
contactHolder.tv_subject=(TextView)row.findViewById(R.id.xsubject_tv);
contactHolder.tv_description=(TextView)row.findViewById(R.id.xdescription_tv);
row.setTag(contactHolder);
}
else
{
contactHolder=(ContactHolder)row.getTag();
}
Converter converter = (Converter) this.getItem(position);
contactHolder.tv_subject.setText(converter.getSubject());
contactHolder.tv_description.setText(converter.getDescription());
return row;
}
public class ContactHolder{
TextView tv_subject,tv_description;
}
}
public class Converter {
private String subject,description;
public Converter(String subject, String description) {
this.setSubject(subject);
this.setDescription(description);
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
}
Change
String item = String.valueOf(parent.getItemAtPosition(position));
to
String item = ((Converter)parent.getAdapter().getItem(position)).getSubject()
You pass Converter objects to CustomAdapter to list them. So if you call getItem you have to concat Object to Converter. So;
change
String item = String.valueOf(parent.getItemAtPosition(position));
to
String item = ((Converter)parent.getAdapter().getItem(position)).getSubject();
so final code:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = ((Converter)parent.getAdapter().getItem(position)).getSubject();
Toast.makeText(getApplicationContext(),item, Toast.LENGTH_LONG).show();}
});
parent.getItemAtPosition(position); return the object of at position whatever you return from getItem(position).
Converter item = (Converter )parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),item.getSubject(), Toast.LENGTH_LONG).show();
I have a custom adapter for GridView Adapter
I want to get an specific value from the selected Item such as "stamp ID"
I was developing this to display only the stamps long time ago and now I want to be able to click on one stamp to send him to next page
I looked in the internet for a solution but most of the tutorials require me to modify a lot on the Adapter code (Witch means creating a new class)
I need to know if there a simple way to fix this using the adapter that I am using.
this is the part on StampActiviy class where connect
GridView gridView = (GridView) findViewById(R.id.gvStamps);
// Pass the results into ListViewAdapter.java adapterCollected,adapterunCollected
adapterListStamps = new ListViewListStampsAdapter(KioskStampsListActivity.this, arraylistStamps);
// Set the adapter to the ListView
gridView.setAdapter(adapterListStamps);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// I need to get StampId then send the user to next screen
Toast.makeText(KioskStampsListActivity.this, ""+arg2+" - "+stampsUtil.getStampId(), Toast.LENGTH_LONG).show();
}
});
this is the ListViewListStampsAdapter
public class ListViewListStampsAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewListStampsAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView tvStampName, tvStampId;
ImageView stampImage;
String STAMP_IMAGE_URL = SharedPrefUtils.getUrl(context, "images/stamp/");
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.single_stamp_layout, parent, false);
// Get the position
resultp = data.get(position);
tvStampName = (TextView) itemView.findViewById(R.id.tvStampName);
tvStampId = (TextView) itemView.findViewById(R.id.tvStampId);
stampImage = (ImageView) itemView.findViewById(R.id.stampImage);
tvStampName.setText(resultp.get(KioskStampsListActivity.TAG_STAMP_NAME));
tvStampId.setText(resultp.get(KioskStampsListActivity.TAG_STAMPS_ID));
// Passes stampImage images URL into ImageLoader.class
imageLoader.DisplayImage(STAMP_IMAGE_URL+resultp.get(StampsActivity.TAG_STAMP_IMAGE), stampImage);
Animation myFadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadein);
stampImage.startAnimation(myFadeInAnimation);
return itemView;
}
}
this is StampUtil class
public class StampsUtil {
private static String StampId, message, stampimage, stampname;
public String getStampId() {
return StampId;
}
public void setStampId(String stampId) {
StampId = stampId;
}
public static String getMessage() {
return message;
}
public static void setMessage(String message) {
StampsUtil.message = message;
}
public static String getStampimage() {
return stampimage;
}
public static void setStampimage(String stampimage) {
StampsUtil.stampimage = stampimage;
}
public static String getStampname() {
return stampname;
}
public static void setStampname(String stampname) {
StampsUtil.stampname = stampname;
}
}
Thanks
Try below code:
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// I need to get StampId then send the user to next screen
Toast.makeText(KioskStampsListActivity.this, ""+arg2+" - "+stampsUtil.getStampId(), Toast.LENGTH_LONG).show();
System.out.println(arraylistStamps.get(i).getStampId());// you can get value
}
});
You can use
grid.getItemAtPosition(position).toString();
I have used like this:-
public static String getUrl(int position){
String itemName = grid.getItemAtPosition(position).toString();
return itemName;// Return your string value
}
OR
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String itemName = grid.getItemAtPosition(position).toString();
}});
and in Adapter :-
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return web[position]; //--> web is my array of string
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
I have a listview and i am populating the data to the list view form DB using custom adapter. Its working fine, but when i click on the list item, i want to get the ID of the item which is clicked to pass it on to the next activity to do some stuff. But when i click on list item, i am not able to get the ID.
Any idea why is this happening?
my list listener:
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this,
CountryActivity.class);
intent.putExtra("countryId", adapter.getItem(position).getId());//here i am getting error saying
//The method getId() is undefined for the type Object.
startActivity(intent);
}
});
But i have defined my countries.java (POJO) for type specification
public class Countries {
Integer id;
String countryName = "", countryIcon = "";
public Countries(Integer id, String countryName, String countryIcon) {
this.id = id;
this.countryName = countryName;
this.countryIcon = countryIcon;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getCountryIcon() {
return countryIcon;
}
public void setCountryIcon(String countryIcon) {
this.countryIcon = countryIcon;
}
}
i am fetching data out of cursor obj (visas) from the below code:
names = new ArrayList<Countries>();
do {
country = new Countries(Integer.parseInt(visas.getString(0)),
visas.getString(1), visas.getString(2));
// Log.d("VISA", visas.getString(0));
names.add(country);
} while (visas.moveToNext());
here is my adapter code:
public class VisaAdapter extends ArrayAdapter<Countries> {
private final Context context;
private final ArrayList<Countries> values;
Resources resc = getContext().getResources();
public VisaAdapter(Context context, ArrayList<Countries> values) {
super(context, R.layout.list_item, values);
this.context = context;
this.values = values;
}
#Override
public Countries getItem(int position) {
return values.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_item, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values.get(position).getCountryName());
// Change icon based on name
String icon = values.get(position).getCountryIcon();
int resIcon = resc.getIdentifier(icon, "drawable", "com.m7.visaapp");
rowView.setBackgroundResource(R.drawable.list_view_places_row);
imageView.setImageResource(resIcon);
return rowView;
}
}
You must cast the getItem(position) return value to a Countries object.
Change this:
intent.putExtra("countryId", adapter.getItem(position).getId());
To this:
Countries countries = (Countries)adapter.getItem(position);
intent.putExtra("countryId", countries.getId());
Update:
Actually, after reading #Tushar's comment, I think you should make names a VisaAdapter instead of an ArrayList<Countries>(). Then, your original line of code, above, should work as-is.
adapter.getItem(position)
function Returns an Object so type cast it to Country like
(Countries)adapter.getItem(position)