单击列表视图中的项目时如何显示数据库中的数据

时间:2017-12-07 18:00:08

标签: android sqlite listview

单击列表视图中的项目时,尝试访问数据库中的数据时出现问题。

这是我的数据库处理程序中的方法:

    public Match getMatchFromId(int matchId)
    {
        SQLiteDatabase db = this.getReadableDatabase();
        Match m = null;
        Cursor cursor;

        cursor = db.rawQuery("select * from " + MATCH_TABLE + " where " +
        MATCH_ID_COL + "='" + matchId + "'" , null);

        while(cursor.moveToNext())
        {
            m = new Match();
            m.setHome(cursor.getString(cursor.getColumnIndex(MATCH_HOME_TEAM_COL)));
            m.setAway(cursor.getString(cursor.getColumnIndex(MATCH_AWAY_TEAM_COL)));
            m.setHomeScore(cursor.getString(cursor.getColumnIndex(MATCH_HOMESCORE_COL)));
            m.setAwayScore(cursor.getString(cursor.getColumnIndex(MATCH_AWAYSCORE_COL)));
            m.setDate(cursor.getString(cursor.getColumnIndex(MATCH_DATE_COL)));
            m.setTime(cursor.getString(cursor.getColumnIndex(MATCH_TIME_COL)));
            m.setRedCard(cursor.getString(cursor.getColumnIndex(MATCH_REDCARD_COL)));
            m.setBookings(cursor.getString(cursor.getColumnIndex(MATCH_BOOKINGS_COL)));
            m.setTypeOfMatch(cursor.getString(cursor.getColumnIndex(MATCH_TYPEOFMATCH_COL)));
//            m.setGroundId(cursor.getInt(cursor.getColumnIndex()));
        }
        cursor.close();

        return m;
    }

我只是遇到了如何通过列表视图访问数据的问题。我希望能够单击该项目,并将其带到另一个活动进行编辑。

public class ViewMatchesActivity extends AppCompatActivity {
DBHandler myDB;
ArrayList<Match> matches = new ArrayList<Match>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_matches);
    myDB = new DBHandler(this);
    final ListView listView = (ListView) findViewById(R.id.listview);

    matches = myDB.getAllMatches();
    MyAdapter myAdapter = new MyAdapter(ViewMatchesActivity.this, R.layout.list2col, matches);

    listView.setAdapter(myAdapter);

任何帮助都会很好,因为我是Android Studio的新手。

1 个答案:

答案 0 :(得分:0)

您需要添加一个监听器来监听相应的事件(可能是项目点击)。然后提取id(或者可以用于唯一标识表id或rowid中的行(通常是同一个东西)经常使用的),在创建Intent之后将该数据放入Intent Extra中,然后调用其他活动使用意图。

您可以按照以下方式编写代码: -

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //>>>> position is the position of the clicked item, 0 for the first item.
            //>>>> position will also be the respective offset into matches
            //>>>> position SHOULD NOT BE USED to try to perform arithmetic
            //>>>> calculation of rowid/id of the row in the table
            //>>>> So get rowid via matches.get(position).
            Intent intent = new Intent(getApplicationContext(),your_other_activity.class);
            intent.putExtra("KEYFORDATA",row_id_to_so_selected_item_can_be_edited);
            StartActivity(intent);
        }
    });

请注意!显然上述情况不会起作用,需要根据需要进行调整。