2012-08-26 93 views
0

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

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); 
     } 
     }); 

回答

0

使用它从SQLLite数据库检索数据。

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); 
     } 
     }); 
+0

但是,通过整个专栏,不是吗?我只想传递所选项目的数据。 – user1617102

+0

是的,因为您可能没有正确设置光标。你可能已经习惯了检索所有的行,这就是它传递整个列的原因。 – Swayam

+0

检查我更新的答案。我添加了代码以使用onItemClick中的光标来检索仅对应的行。 – Swayam

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); 
    } 
});