Android中Java.lang.String的ClassCastException

时间:2011-11-11 08:30:25

标签: android string classcastexception

我不知道为什么我会在这行代码中找到它(箭头所在的位置)

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

自定义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;
     }

这是完成工作的arrayadapter。我假设问题就在这里。

2 个答案:

答案 0 :(得分:3)

您必须在String中存储ListView。它提供了例外,因为它无法将String强制转换为App

修改
myarr中的对象会显示在ListView中。这些对象都是String个。在您获得例外的行中,您尝试将String转换为positionApp。它不能这样做,所以你得到了例外。所以试试这个:

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

<强> EDIT2
myarr更改为

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

更改以下行:

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

添加App类:

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

答案 1 :(得分:0)

如果是这样的自定义用途

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