Tuesday, February 25, 2014

Android: Passing value from one activity to another

Objective : To pass some data from one activity to another. Here the user's selection of listview item from main activity to another activity.

Scenario: Main activity has a ViewGroup -  ListView. Based on the user's selection of the item from the ListView another activity (Second activity here)gets started. But the selected item value needs to be passed from the main activity to the Second Activity.

//attaching a listener on listview

MainActivity - onCreate()
…..
    listview.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, final View view,
                      int position, long id){
            
                            Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
                            String value = (String)parent.getItemAtPosition(position);

// putExtra is called to send key-value pair to the SecondActivity
                            intent.putExtra("key", value);
                            startActivity(intent);
                            
               }
    });


SecondActivity - onCreate()

Intent intent = getIntent();

//retrieving extras that are sent in bundle.
Bundle bundle = intent.getExtras();

String value = bundle.getString("key");

No comments:

Post a Comment