Riy*_*329 0 database sqlite android data-retrieval android-listview
我可以ListView从我的SQLiteDatabasein 填充我的项目lunch.java.现在我想点击一个项目(共8个项目ListView)并转到一个新的活动,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;
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
在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);
}
Run Code Online (Sandbox Code Playgroud)
然后在您的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
Run Code Online (Sandbox Code Playgroud)
上面的代码适用于Cursor基于适配器的情况.但是你可能使用基于列表的适配器(因为getItemAtPosition(pos)返回a String而不是a 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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2669 次 |
| 最近记录: |