From last night to now, I finally debugged an example of startActivityForResult. The Internet is either too complicated or vague, which makes me take many detours, so I wrote an experience.
On a main interface (main Activity), you can connect to many different sub-function modules (sub-Activities). After the sub-module work is finished, you return to the main interface and return some data completed by the sub-module to be handed over to the main Activity for processing. Starting the main interface with startActivity is a new Intent instance, and the accessed main interface is still not called out below the activity stack. One of the biggest problems in this is that if you cannot return to the original interface, multiple sub-function modules cannot provide data or services to the main interface together. At this time, you need to use startActivityForResult!
Purpose: It is the main interface and a sub-function module. You must start second from main. After receiving the data sent by main, second will finish doing the work, press OK to report the result to main, and close it yourself and return to main.
Specific implementation:
It is divided into four parts:
class sendButtonListen implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
String str = "dajia hao ";
("send", str);
(, );
startActivityForResult(intent, 0);
}
}
2. In the OnCreate function in SecondActivity, receive data sent from the intent in main.
@Override
public void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_second);
okButton = (Button)findViewById(); //Press this ok key and it will return to main.
Intent intent = getIntent();
String getStr = ("send");
TextView tv = (TextView)findViewById();
(getStr);
(,
"The data sent back from MainActivity is: "+getStr,
Toast.LENGTH_SHORT).show();
(new okButtonListen());
}
class okButtonListen implements OnClickListener{
public void onClick(View v) {
// TODO Auto-generated method stub
Intent sendIntent = new Intent(, );//I learned this method today, please note it! This is convenient for writing, this is not bound to Inent
Bundle bundle = new Bundle();
("send", "Hello everyone");
(bundle);
(RESULT_OK, sendIntent);
();
}
4. After returning to main, main will receive the data sent from second. Rewrite its OnActivityResult method in MainActivity.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
Bundle bundle = ();
String str = ("send");
(,
"I came back, the data sent back by the second activity is: "+str,
Toast.LENGTH_SHORT).show();
}
}
Notice:Don't create a new Intent here. OnActivityResult has three parameters. The third parameter is Intent. You just need to use it as the parameters.