ClassCastException:无法强制转换为NewsItem

时间:2014-01-19 07:59:48

标签: java android listview onitemclicklistener

newsitem是一个保存我数据的类。 当我单击列表视图中的项目时,我收到此错误:

01-19 11:03:20.094: E/AndroidRuntime(860): FATAL EXCEPTION: main

01-19 11:03:20.094: E/AndroidRuntime(860): java.lang.ClassCastException: java.lang.Integer cannot be cast to com.example.NewsItem

01-19 11:03:20.094: E/AndroidRuntime(860):  at com.example.ListViewContents$2.onItemClick(ListViewContents.java:72)

01-19 11:03:20.094: E/AndroidRuntime(860):  at android.widget.AdapterView.performItemClick(AdapterView.java:282)

01-19 11:03:20.094: E/AndroidRuntime(860):  at android.widget.AbsListView.performItemClick(AbsListView.java:1037)

01-19 11:03:20.094: E/AndroidRuntime(860):  at android.widget.AbsListView$PerformClick.run(AbsListView.java:2449)

01-19 11:03:20.094: E/AndroidRuntime(860):  at android.widget.AbsListView.onTouchEvent(AbsListView.java:3085)

01-19 11:03:20.094: E/AndroidRuntime(860):  at android.widget.ListView.onTouchEvent(ListView.java:3591)

点击时应该打开一个活动。

这是我的ListviewContents类中的onCreate方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listviewcontents);
    intent = getIntent();
    url_topic = intent.getIntExtra("key", 0);
    listview = (ListView)findViewById(R.id.custom_list);
    adapter = new LazyImageLoadAdapter(this,arraylist_newitems);
    listview.setAdapter(adapter);

    Button buttonrefresh = (Button)findViewById(R.id.button_refresh);
    buttonrefresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            adapter.imageLoader.clearCache();
            adapter.notifyDataSetChanged();
        }
    });

    new LongImageFetch().execute((Void)null);

     listview.setOnItemClickListener(new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,
                  int position, long id) {
                String url ;
                NewsItem newitem = (NewsItem) listview.getItemAtPosition(position);
                url = newitem.getUrllink();
                Intent intent = new Intent(getApplicationContext(),WebViewActivity.class);
                intent.putExtra("URL", url);
                startActivity(intent);
              }
            });

}

2 个答案:

答案 0 :(得分:0)

java.lang.ClassCastException: java.lang.Integer cannot be cast to com.example.NewsItem

listview.getItemAtPosition(position);返回一个整数值。

但你有

NewsItem newitem = (NewsItem) listview.getItemAtPosition(position);
// casting it to  NewsItem 

你可能想要

NewsItem newitem = (NewsItem)arraylist_newitems.get(position)

答案 1 :(得分:0)

OnItemClickListener将视图传递给您用作参数。

这是否有效:

NewsItem newitem = (NewsItem)view;