Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 265
Psest328 Avatar asked Dec 11 '22 22:12

Psest328


1 Answers

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

like image 75
nandeesh Avatar answered Jan 06 '23 04:01

nandeesh