I can populate my ListView of items from my SQLiteDatabase in lunch.java. now I want to click the one item(total 8 items inside the ListView) and go to a new activity called Display.java and display all the nutrition facts of it.

AFTER EDITING

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

}
有帮助吗?

解决方案

In the onItemcClick you already have the id of the element that was clicked, the id parameter. Use that to identify the item in your next activity:

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

Then in your Display activity get that long value and get the data from the database corresponding to that 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

The above code would work for the case of a Cursor based adapter. But you probably use a list based adapter(because of the getItemAtPosition(pos) returning a String and not a Cursor). In this case I would make the getLunchDetails method to return the unique id of that meal name and pass that to the Details activity:

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top