Really not getting setResult and onActivityResult

2020-02-12 09:25发布

Alright, here I am again. Still learning. Now I need to pass integer values back and forth from 2 activities. First activity passes a counter value to the second (which keeps track of player stats). Second activity has ability to reset stats to zero, hence passing the number back. But I just can't get my head around it. Here's what I have so far...

First activity (Main):

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_settings:
            Intent i = new Intent(this, Options.class);
            Bundle counters = new Bundle();
            counters.putInt("plWin", plWin);
            counters.putInt("plLoss", plLoss);
            counters.putInt("plDraw", plDraw);
            i.putExtras(counters);
            startActivityForResult(i, ?);
            return true;

please fill in the "?"

second activity (Options):

public void onBackPressed() {
    super.onBackPressed();
    Intent i = new Intent();
    Bundle counters = new Bundle();
    counters.putInt("Wins", wins);
    counters.putInt("Losses", losses);
    counters.putInt("Draws", draws);
    i.putExtras(counters);
    setResult(?, i);
    finish();
}

again, can't figure out the "?".

And going back to my first activity, I don't know what goes after:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

Dying to figure this out. Thanks in advance.

1条回答
叼着烟拽天下
2楼-- · 2020-02-12 10:01

Do like this

startActivityForResult(i, 100);  

For setResult

setResult(RESULT_OK);

You can use setresult for more advanced sending of results something like

intent = new Intent();
intent.putExtra("key", "I am done");
setResult(1001, intent);

And in onActivityResult

protected void onActivityResult(int requestCode, int resultCode, Intent data) {    
   if(requestCode == 100)
   {
    String key = data.getStringExtra("key");
    if(resultcode == 1001 && key!= null && key.equals("I am done"){
       //do something
    }else{
       //do something else
    }

   }
} 

You dont have to use setResult, if all you need to check is whether you returned from the activity then dont set it and dont check in onActivityResult

查看更多
登录 后发表回答