Relatively simple task: How do I pass back the selected item from one activity to another?

Posted by Brian D on Stack Overflow See other posts from Stack Overflow or by Brian D
Published on 2011-01-09T06:22:07Z Indexed on 2011/01/09 6:53 UTC
Read the original article Hit count: 221

Filed under:

I have two activities: one displays an image and a button, the other displays a photo gallery. I want to be able to select any of the images in the gallery and then display them on the first activity in place of the default image.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.gallery);

    Gallery g = (Gallery) findViewById(R.id.gallery);
    g.setAdapter(new ImageAdapter(this));

    g.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id) {
            Toast.makeText(PhotoGallery.this, "Position: " + id, Toast.LENGTH_SHORT).show();

            Intent intent=new Intent();   
            intent.putExtra("PictureID", position);
            setResult(RESULT_OK, intent);
            finish();


        }
    });
}

Am I even close here? I'm not quite sure what to do with any string or int I would attach to the Intent -- can I attach the object itself? I'd much rather pass back at minimum the string name of the resource (image), but the only thing I can seem to figure out right now is how to pass back the position of the picture ... not a great solution. I can clarify more if necessary -- thanks.

© Stack Overflow or respective owner

Related posts about android