android-intent data return

Sometimes data needs to be returned after jumping to another interface operation, which is data return.
1. The first activity, use startactivityforresult to jump.
The first parameter is the intent, and the second parameter is the request code

Intent intent = new Intent(MainActivity.this,MainActivity2.class);
             startActivityForResult(intent,1);

Second, the second activity returns data after the completion of the operation and closes the current page.
Instantiate an intent to
send data
with the setresult method. Two parameters, the first is the result code, the second is the intent

Intent intent = new Intent();
                intent.putExtra("result","结果为:"+result);
                setResult(2,intent);
                finish();

Third, rewrite the onActivityResult method in the first activity.
First, judge the request code. Determine where the logic is for data return.
Then judge the different result codes, and get the corresponding data according to the different result codes returned

@Override
     protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
    
         super.onActivityResult(requestCode, resultCode, data);
         //判断请求码
         if (requestCode==1){
    
    
         //结果码
             if (resultCode==2)
             {
    
    
             //取数据
                 result = data.getStringExtra("result");
             }else if (resultCode==3)
             {
    
    
                 result = data.getStringExtra("result");
             }
             //给控件赋值
             tv.setText(result);
         }
     }

Guess you like

Origin blog.csdn.net/Willow_Spring/article/details/113089921