Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

android - Really not getting setResult and onActivityResult

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...