单击列表视图后如何检索类的实例

时间:2013-06-13 14:12:24

标签: android

我有一个数据库中的类数组显示在listview中。当在列表视图上单击一行时,我希望该类实例中的所有数据都显示在页面上其他位置的文本视图中。我正在使用的类是一个Player类,它还包含一个playerid。

我尝试过类似的东西,但它不起作用,任何帮助都会非常感谢!

     playerlistview.setOnItemClickListener(new OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> listView, View view,
         int position, long id) {

     Player selplayer =  (Player) playerlistview.getAdapter().getItem(position);

     String playername = selplayer.name;
     String playerposition = selplayer.position;
     String playerdob = selplayer.dob;
     String playergoals = selplayer.goals;
     String playerpoints = selplayer.points;

     txtplayername.setText(playername);
     txtplayerposition.setText(playerposition);
     txtplayerdob.setText(playerdob);
     txtplayergoals.setText(playergoals);
     txtplayerpoints.setText(playerpoints);

}
      });



AndroidRuntime(793): java.lang.ClassCastException: com.example.corkgaaapp.Squad$Player cannot be cast to android.database.Cursor
AndroidRuntime(793): at com.example.corkgaaapp.Squad$1.onItemClick(Squad.java:97)

1 个答案:

答案 0 :(得分:0)

您可以从字符串名称创建类的实例:

    String selplayer =  ((TextView) playerlistview.getItemAtPosition(position)).getText().toString();
    Player myPlayer = (Player)Class.forName(selPlayer);

我不知道您拥有什么类型的数据库,但您可以检索数据并创建新实例

    int position = 42; //position is the row user clicked in the list view
    String[] playerinfo = new String[5];

    /* database retrieval here for position into array playerinfo*/

    txtplayername.setText(playerinfo[0]);
    txtplayerposition.setText(playerinfo[1]);
    txtplayerdob.setText(playerinfo[2]);
    txtplayergoals.setText(playerinfo[]3);
    txtplayerpoints.setText(playerinfo[4]);

    myPlayer = new Player(playerinfo[0], playerinfo[1].....);