Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send value through intent after finishing an activity

I have an activity that shows a gridview of items. when I click in any of them, I move to another activity showing the information of the item. I also have the option to go back (gridview activity) or delete it.

If I delete it, I need to refresh the gridview, so I need to send a variable saying "eey, I have deleted an item. you need to refresh".

I guess I need to open the second activity with startActivityForResult, but I don't know how should I set the value.

option 1 (back arrow): finishes the activity. no result back. option 2 (delete item): finishes the activity and sets a result back.

Thanks in advance!

like image 924
trumpetero Avatar asked Jul 11 '13 09:07

trumpetero


2 Answers

You can set your custom result. Like DELETE_ITEM.

On your delete button do something like this :

public static int DELETE_ITEM = 1234;

Intent intent = new Intent();
intent.putExtra("ITEM_ID", YOUR ITEM ID);
setResult(DELETE_ITEM , intent);

Now on your activity result do something like this :

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  if (resultCode == DELETE_ITEM) {
    // CODE TO DELETE ITEM
    super.onActivityResult(requestCode, resultCode, intent);
  }
} 
like image 121
Vipul Purohit Avatar answered Nov 07 '22 11:11

Vipul Purohit


Hope this helps

First class

Intent i = new Intent(this, Second.class);
startActivityForResult(i, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {

        if (resultCode == RESULT_OK) {
            String result = data.getStringExtra("result");
                             //your code

        }
        if (resultCode == RESULT_CANCELED) {
            // Write your code if there's no result
        }
    }
}

Second class

Intent returnIntent = new Intent();
returnIntent.putExtra("result", "your message");
setResult(RESULT_OK, returnIntent);
finish();
like image 13
Benil Mathew Avatar answered Nov 07 '22 09:11

Benil Mathew