Monday, 15 October 2012

Passing data using explicit intents in Android


In my last tutorial (Creating and managing activities) I show you how to switch between 2 activities by pressing button. Not much fun, but essential for android apps. In most cases you would like to pass some data, so in this tutorial we will create editText to put some data in and we pass this data to another activity with Intent to display that text. Simply saying intent is the way how we are going to access components.

We are going to create 4 files again (main.xml, Main.java, second.xml, Second.java)
In main.xml add editText and give it id editText1.
In second.xml add textView1 to display our text and give it id textView1.

In your main.java add this code:
  @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        final EditText editT = (EditText) findViewById(R.id.editText1);
        Button b = (Button) findViewById(R.id.button1);
       
        b.setOnClickListener(new OnClickListener() {
                    
                     public void onClick(View v) {
                           Intent intent = new Intent(Main.this, Second.class);
                          
                           intent.putExtra("text", editT.getText().toString()); // put data into intent
                           startActivity(intent);
                          
                     }
              });
    }

In this method we instantiate Intent and adding the text from EditText - intent.putExtra("text", editT.getText().toString());// first parameter is the name of string, we can define whatever we want, second parameter is actual value, we can access method getText from EditText to retrieve value

In second.java:

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              // TODO Auto-generated method stub
              super.onCreate(savedInstanceState);
              setContentView(R.layout.second);
             
              TextView txtView = (TextView) findViewById(R.id.textView1);
              txtView.setText(getIntent().getExtras().getString("text"));
             
             
             
              Button button = (Button) findViewById(id.back);
              button.setOnClickListener(new OnClickListener() {
                    
                     public void onClick(View v) {

                                  startActivity(new Intent(Second.this, Main.class));
                          
                          
                     }
              });
             
              }

Now we simply access textView setText method and set text from intent:
txtView.setText(getIntent().getExtras().getString("text"));

We stored only one string “text”, but we could easily pass more values, take for example registration form (First Name, Last Name, Address, Email etc).