Data transmission between Acitivity and acitivity
Use startActivityForResult to transmit data.
MainActivity. java:
1 public class MainActivity extends Activity { 2 Button btn; 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_main); 7 Button btn=(Button)findViewById(R.id.button1); 8 btn.setOnClickListener(new OnClickListener(){ 9 @Override10 public void onClick(View arg0) {11 Intent intent=new Intent(MainActivity.this,OtherActivity.class);12 startActivityForResult(intent,1); 13 } 14 });15 16 17 }18 protected void onActivityResult(int requestCode,int resultCode,Intent data){19 switch(requestCode){20 case 1:21 String result=data.getExtras().getString("result");22 }23 } 24 25 }
OtherActivity. java:
1 public class OtherActivity extends Activity { 2 Button btn2; 3 /** 4 * @param args 5 */ 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_other); 9 Button btn2=(Button)findViewById(R.id.button2);10 btn2.setOnClickListener(new OnClickListener(){11 12 @Override13 public void onClick(View arg0) {14 // TODO Auto-generated method stub15 Intent intent=new Intent();16 intent.putExtra("result", "hello world");17 OtherActivity.this.setResult(resultcode, intent);18 OtherActivity.this.finish();19 }});20 }21 }
Note:
1. Request Code requestCode: requestCode in startActivityForResult (intent, requestCode) and onActivityResult (int requestCode, int resultCode, Intent data) is the request code, which is used to identify the request source. For example, a single Activity has two buttons. Clicking these two buttons will open the same Activity. No matter which button opens the new Activity, when the new Activity is closed, the system will call the onActivityResult (int requestCode, int resultCode, Intent data) method of the previous Activity. In the onActivityResult () method, if you need to know that the new Activity is opened by that button, and you need to make corresponding business processing.
2. result code resultCode: in an Activity, you may use the startActivityForResult () method to open multiple different activities to process different businesses. When these new activities are closed, the system will call the onActivityResult (int requestCode, int resultCode, Intent data) method of Activi ty. To know which new Activity the data is returned from, you can do this in the onActivityResult () method (Result Activity and NewActivity are the new Activity to be opened ).