What is the way to exchange Data between the Activity by using Intent?

There are two way to send  data between Activities. 

 (a) Forward data exchange (Activity Class A to B)

in class A
Intent i = new Intent(this, B.class)
i.putExtra(“username”, s1)
i.put extra(“password”, s2)
startActivity(i);
where s1 and s2 is String which is holding Data and by using PutExtra we are sending this data to another screen B.
We can also use Bundle class to sent Data but we use it when we have to send a large amount of data .like this way ….
Intent i = new Intent(this, B.class)
Bundle extras = new Bundle();
extras.putString(“Name”, “Your name here”);
i.putExtras(extras);
startActivityForResult(i, 1);

(b) Backward Data Exchange (Activity Class  B to A)
If you need to pass data back from an activity, you should instead use the
startActivityForResult() method. The following Try It Out demonstrates this.

In class B write following code …
Intent data = new Intent();
//---set the data to pass back---
data.setData(Uri.parse(s1));
setResult(RESULT_OK, data);

In class A use like this...
//Global Variable
int request_Code = 1;
….......
//Getting data
startActivityForResult(new Intent(“packagename.B”),request_Code);

public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == request_Code) {
if (resultCode == RESULT_OK) {
Toast.makeText(this,data.getData().toString(),Toast.LENGTH_SHORT).show();
}
}
}

No comments:

Post a Comment