volk
volk

Reputation: 1196

ClassCastException at Java.lang.String in Android

I have no idea why I'm getting it on this line of code (where the arrow is)

protected void onListItemClick(ListView l, View v, int position, long id) {
--->    App selection = (App) l.getItemAtPosition(position);

Custom ArrayAdapter:

public class MyCustomAdapter extends ArrayAdapter<String>{

private ArrayList<String> myarr = new ArrayList<String>();
private LayoutInflater inflater;

//objects = array of whatever you want to add to the list
public MyCustomAdapter(Context context,
        int textViewResourceId, List<String> objects) {
    super(context, textViewResourceId, objects);
    myarr = (ArrayList<String>) objects;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
 public View getView(int position, View convertView, ViewGroup parent) {

      View row = convertView;
      if(row==null){
       row=inflater.inflate(R.layout.list_row, parent,false);
      }

      ((TextView)row.findViewById(R.id.rowtextview)).setText(myarr.get(position));

      return row;
     }

This is the arrayadapter that does the work. I'm assuming the problem is in here.

Upvotes: 0

Views: 644

Answers (2)

Caner
Caner

Reputation: 59148

You must have stored String in your ListView. It gives the exception because it cannot cast String to App

EDIT
The objects in your myarr are displayed in your ListView. Those objects are all Strings. In the line where you get exception you are trying to convert the String at position to an App. It cannot do that so you get the exception. So try this:

String selection = (String) l.getItemAtPosition(position);

EDIT2
Change myarr to

private ArrayList<App> myarr = new ArrayList<App>();

Change the following line:

((TextView)row.findViewById(R.id.rowtextview)).setText(myarr.get(position).getText());

Add App class:

public String getText(){/*...*/}
public void setText(String text){/*...*/}
public String toString(){ /*...*/}

Upvotes: 3

RajaReddy PolamReddy
RajaReddy PolamReddy

Reputation: 22493

if it is custom use like this

MyFont f = fontArray[pos];
selected_font = f.getValue();

Upvotes: 0

Related Questions