How to manage activity with startActivityForResult

无人久伴 提交于 2020-01-20 08:51:10

问题


I got a situation like this:

Activity A --> B --> C --> D, when D finished, I have to refresh ActivityA to display what I input in ActivityB , ActivityC and ActivityD.Here is my code:

ActivityA

    @OnClick(R.id.btn_one)
    public void toActivityB(){
        Intent intent = new Intent();
        intent.setClass(this, ActivityB.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK){
            String b = data.getStringExtra("b");
            String c = data.getStringExtra("c");
            String d = data.getStringExtra("d");
            tvAll.setText(etOne.getText().toString() + "\n" + b + "\n" + c + "\n" + d);
        }
    }

ActivityB

    @OnClick(R.id.btn_two)
    public void toActivityC(){
        Intent intent = new Intent();
        intent.setClass(this, ActivityC.class);
        startActivityForResult(intent, 2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2 && resultCode == RESULT_OK){
            data.putExtra("b", etTwo.getText().toString());
            setResult(RESULT_OK, data);
            finish();
        }
    }

ActivityC code just like ActivityB, the last ActivityD as follow:

    @OnClick(R.id.btn_four)
    public void returnToActivityA(){
        Intent intent = new Intent();
        intent.putExtra("d", etFour.getText().toString());
        setResult(RESULT_OK, intent);
        finish();
    }

In this way, I can get the input value in ActivityB,ActivityC,ActivityD.but I have to override the method onActivityResult at every Activity and handle the data one by one.Is there any another easy way for me to handle this situation?Any good suggestion I'll be appreciate.


回答1:


I would suggest you to use a single activity and use fragments as forms to enter the data and once all the data is collected you can either save it in shared preference or SQLITE database depending upon the data to be saved then start a new activity to display the data stored
OR
create a parceleble object and send this object to new Activity and display it there.




回答2:


You can pass on the "target" Activity for the required results from one Activity to the next with Intent.FLAG_ACTIVITY_FORWARD_RESULT. If you start ActivityC for example:

@OnClick(R.id.btn_two)
public void toActivityC(){
    Intent intent = new Intent();
    intent.setClass(this, ActivityC.class);
    intent.setFlag( Intent.FLAG_ACTIVITY_FORWARD_RESULT );
    startActivityForResult(intent, 2);
}

This way the new activity can call setResult(int) and have that result sent back to the reply target of the original activity.

(quoted from Intent documentation)

In your case this means also that each Activity (B and C) has to pass the data which has been collected so far along with the Intent used for starting the next Activity. Finally, ActivityD can call setResult() to transmit the data to ActivityA.

EDIT (1) I'm adding some code to demonstrate how to react if the user presses the BACK key. For simplicity's sake, let's assume that the user would only decide to press BACK while in ActivityD.

EDIT (2) Note that Intent.putExtra() can take a Bundle, so you can pass a whole Bundle with all your data along instead of transferring all the values one by one to the new Intent. Using one Bundle extra instead of several other extras can result in less lines of code.

The xml files

activity_a.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
    <TextView
        android:text="Results:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"/>

    <TextView
        android:id="@+id/tv_result1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="---"/>

    <TextView
        android:id="@+id/tv_result2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="---"/>

    <TextView
        android:id="@+id/tv_result3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="---"/>

    <Button
        android:id="@+id/btn_get_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get results!"/>

</LinearLayout>

activity_b.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    <TextView
        android:text="The following text will be sent as result:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff0000"
        android:text="Forwarding Results"/>

    <Button
        android:id="@+id/btn_get_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get more results!"/>

</LinearLayout>

activity_c.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    <TextView
        android:text="The following text will be sent as result:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff00ff"
        android:text="is"
        android:checked="true"
        android:id="@+id/cb_result"/>

    <Button
        android:id="@+id/btn_get_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get more results!"/>

</LinearLayout>

activity_d.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:orientation="vertical">
    <TextView
        android:text="The following text will be sent as result:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0000ff"/>

    <Button
        android:id="@+id/btn_send_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send all results!"/>

</LinearLayout>

The activities

ActivityA

public class ActivityA extends AppCompatActivity
{
    static final int REQUEST_CODE = 42;

    static final String KEY_RESULT_FROM_B = "result_b";
    static final String KEY_RESULT_FROM_C = "result_c";
    static final String KEY_RESULT_FROM_D = "result_d";

    private TextView tvResult1, tvResult2, tvResult3;
    private Button btnGetResults;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_a);

    tvResult1 = (TextView) findViewById(R.id.tv_result1);
    tvResult2 = (TextView) findViewById(R.id.tv_result2);
    tvResult3 = (TextView) findViewById(R.id.tv_result3);

    btnGetResults = (Button) findViewById(R.id.btn_get_results);
    btnGetResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            startActivityForResult(new Intent(ActivityA.this, ActivityB.class), REQUEST_CODE);
        }
    });

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (REQUEST_CODE == requestCode)
    {
        if (resultCode == RESULT_OK)
        {
            tvResult1.setText(data.getStringExtra(KEY_RESULT_FROM_B));
            tvResult2.setText(data.getStringExtra(KEY_RESULT_FROM_C));
            tvResult3.setText(data.getStringExtra(KEY_RESULT_FROM_D));
            btnGetResults.setEnabled(false);
        }
        else
        {
            Toast.makeText(ActivityA.this, "no result", Toast.LENGTH_SHORT).show();
            // do something else
        }
    }
}
}

ActivityB

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_b);

    TextView tvResult = (TextView) findViewById(R.id.tv_result);
    final String result = tvResult.getText().toString();

    Button btnGetResults = (Button) findViewById(R.id.btn_get_results);
    btnGetResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(ActivityB.this, ActivityC.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);

            intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result);
            startActivity(intent);
            finish();
        }
    });
}

ActivityC

public class ActivityC extends AppCompatActivity
{
    static final String IS ="is";
    static final String IS_NOT = "is not";

    private CheckBox cbResult;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_c);

    cbResult = (CheckBox) findViewById(R.id.cb_result);
    cbResult.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            buttonView.setText(isChecked ? IS : IS_NOT);
        }
    });

    String previousResult = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_C);
    cbResult.setChecked( ! IS_NOT.equals(previousResult) );

    final String result1 = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_B);

    Button btnGetResults = (Button) findViewById(R.id.btn_get_results);
    btnGetResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent(ActivityC.this, ActivityD.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
            intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result1);
            String result2= cbResult.getText().toString();
            intent.putExtra(ActivityA.KEY_RESULT_FROM_C, result2);
            startActivity(intent);
            finish();
        }
    });
}
}

ActivityD

public class ActivityD extends AppCompatActivity
{
    static final String POSSIBLE = "possible :)";
    static final String COMPLICATED = "complicated";

    private String result1, result2;

    private TextView tvResult;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_d);

    tvResult = (TextView) findViewById(R.id.tv_result);
    result1 = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_B);
    result2 = getIntent().getStringExtra(ActivityA.KEY_RESULT_FROM_C);

    if (ActivityC.IS.equals(result2))
    {
        tvResult.setText(POSSIBLE);
    }
    else
    {
        tvResult.setText(COMPLICATED);
    }


    Button btnSendResults = (Button) findViewById(R.id.btn_send_results);
    btnSendResults.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            Intent intent = new Intent();

            intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result1);
            intent.putExtra(ActivityA.KEY_RESULT_FROM_C, result2);
            intent.putExtra(ActivityA.KEY_RESULT_FROM_D,  tvResult.getText().toString());
            setResult(RESULT_OK, intent);
            finish();
        }
    });
}

@Override
public void onBackPressed()
{
    // start ActivityC once more
    Intent intent = new Intent(ActivityD.this, ActivityC.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);

    intent.putExtra(ActivityA.KEY_RESULT_FROM_B, result1);
    // pass this to set the CheckBox like the user left it:
    intent.putExtra(ActivityA.KEY_RESULT_FROM_C, result2);
    startActivity(intent);
    finish();
}
}


来源:https://stackoverflow.com/questions/37186992/how-to-manage-activity-with-startactivityforresult

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!