How to extract objects from ListView - getItemAtPosition won't work

核能气质少年 提交于 2019-12-05 08:09:07

The ClassCastException is caused by the following line in your OnItemClickListener:

TableRow tableRow = (TableRow) (mListView.getItemAtPosition(myItemInt));

And that's because your adapter is filled with DashboardBean instances. The getItemAtPosition method returns an object belonging to the data structure the adapter works with, not an instance of the graphic widget (TableRow, I assume) which the object is shown on. Just writing:

DashboardBean board = (DashboardBean) (mListView.getItemAtPosition(myItemInt));

in place of the offending line would do the trick. You can then work directly with the fields in the DashboardBean object instead of passing through TextViews and similar UI elements.

You should be able to get your DashboardBean object in onItemclick like this:

DashboardBean bean = (DashboardBean) mListView.getItemAtPosition(myItemInt);

If you just want to extract object then OnItemClickListener makes your task easier.You ger view instance of the row.from that you can extract the contents.

Change

mListView.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, 
            int myItemInt, long mylng) {
        TableRow tableRow = (TableRow) (mListView.getItemAtPosition(myItemInt));

        String project = ((TextView) tableRow.findViewById(R.id.project)).getText().toString();
        String workRequest = ((TextView) tableRow.findViewById(R.id.work_request)).getText().toString();
        String startDate = ((TextView) tableRow.findViewById(R.id.start_date)).getText().toString();
        String status = ((TextView) tableRow.findViewById(R.id.status)).getText().toString();

          showWorkRequest(project, workRequest, startDate, status);

      }

  });

To This

mListView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView <? > myAdapter, View myView, int myItemInt, long mylng) {


        String project = ((TextView) myView.findViewById(R.id.project)).getText().toString();
        String workRequest = ((TextView) myView.findViewById(R.id.work_request)).getText().toString();
        String startDate = ((TextView) myView.findViewById(R.id.start_date)).getText().toString();
        String status = ((TextView) myView.findViewById(R.id.status)).getText().toString();

        showWorkRequest(project, workRequest, startDate, status);

    }

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!