将数据从ListView传递到另一个Activity

时间:2012-08-26 17:58:25

标签: android listview

我有一个ListView,其中每个ListItem在其布局中有2个TextView。单击ListItem时,我想将这些TextView的值传递给另一个活动。我所有的尝试都失败了,所以我问你我该怎么做?我如何传递SQLite ROW_ID,R.id.text1和R.id.text2的值?

    Cursor cursor = database.getAllNames();
    adapter = new SimpleCursorAdapter(this, R.layout.listrow, cursor,
            new String[] { Database.KEY_DATE , Database.KEY_NAME },
            new int[] {R.id.text1, R.id.text2}, 0);

    listView = (ListView) findViewById(R.id.list);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(SendingData.this, ReceivingData.class);
            intent.putExtra("id", id); //this should pass the SQLite ROW_ID
            intent.putExtra("date", date); //this should pass the value of R.id.text1
            intent.putExtra("name", name); //this should pass the value of R.id.text2
            startActivity(intent);  
        }
        });

2 个答案:

答案 0 :(得分:0)

使用此方法从SQLite数据库中检索数据。

cursor.getString(c.getColumnIndex(Database.columns[i])) // i is the index of the column whose details you want to fetch

然后你可以将它们作为参数传递给intent.putExtra。

listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Cursor cursor = null;
            cursor = (Cursor) parent.getItemAtPosition(position);
            Intent intent = new Intent(SendingData.this, ReceivingData.class);
            intent.putExtra("id", cursor.getInt(cursor.getColumnIndex(Database.columns[0]))); //assuming that the first column in your database table is the row_id
            intent.putExtra("date", cursor.getString(cursor.getColumnIndex(Database.columns[1]))); //assuming that the second column in your database table is the text1
            intent.putExtra("name", cursor.getString(cursor.getColumnIndex(Database.columns[2]))); //assuming that the third column in your database table is the text2
            startActivity(intent);  
        }
        });

答案 1 :(得分:0)

您可以直接从视图中获取数据,而无需访问游标(并使用onItemClick方法中传递的行ID)。:

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

        TextView text1 = (TextView) view.findViewById(R.id.text1);
        TextView text2 = (TextView) view.findViewById(R.id.text1);
        String date = text1.getText().tostring();
        String name = text2.getText().tostring();

        Intent intent = new Intent(SendingData.this, ReceivingData.class); 
        intent.putExtra("id", id); //this should pass the SQLite ROW_ID 
        intent.putExtra("date", date); //this should pass the value of R.id.text1 
        intent.putExtra("name", name); //this should pass the value of R.id.text2 
        startActivity(intent);   
    } 
});