我可以在ListView
中的SQLiteDatabase
填充我的lunch.java
个项目。现在我想点击一个项目(ListView
内的总共8个项目)并转到一个名为Display.java
的新活动,并显示它的所有营养成分。
编辑后
lunch.java:
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
switch(pos)
{
case 0 :
String mealName = (String) parent.getItemAtPosition(pos);
Cursor cursor = dbopener.getBreakfastDetails(mealName);
cursor.moveToNext();
id = cursor.getLong(cursor.getColumnIndex(mealName));
String message = cursor.getString(1) + "\n" + cursor.getInt(2);
Intent event1 = new Intent("com.edu.tp.iit.mns.Display");
event1.putExtra("name", id);
startActivity(event1);
break;
Display.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
TextView tv = (TextView) findViewById(R.id.tvfoodName);
Intent intent = getIntent();
long id = intent.getLongExtra("name", -1);
if(id == -1){
return;
}
tv.setText(-1);
}
答案 0 :(得分:5)
在onItemcClick
中,您已经点击了id
元素,id
参数。用它来识别下一个活动中的项目:
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
newActivity.putExtra("the_key", id);
startActivity(newActivity);
}
然后在您的Display
活动中获取该长值,并从数据库中获取与该id
对应的数据:
Intent newActivity = getIntent();
long id = newActivity.getLongExtras("the_key", -1);
if (id == -1) {
//something has gone wrong or the activity is not started by the launch activity
return
}
//then query the database and get the data corresponding to the item with the id above
上述代码适用于基于Cursor
的适配器的情况。但是您可能使用基于列表的适配器(因为getItemAtPosition(pos)
返回String
而不是Cursor
。在这种情况下,我会使getLunchDetails
方法返回该膳食名称的唯一id
并将其传递给Details
活动:
public void onItemClick(AdapterView<?> parent, View v, int pos, long id) {
String mealName = (String)parent.getItemAtPosition(pos);
Cursor cursor = dbopener.getLunchDetails(mealName);
cursor.moveToNext();
long id = cursor.getLong(cursor.getColumnIndex("the name of the id column(probably _id"));
Intent newActivity = new Intent("com.edu.tp.iit.mns.Display");
newActivity.putExtra("the_key", id);
startActivity(newActivity);
}