Search code examples
androidandroid-intentbundleintentservice

Activity cant find Bundle in Intent


I am using an IntentService (for the first time), and I intend to return the result of this service by using a Bundle. However, when I do this, the main activity does not find the Bundle, returning null. What could cause this? The string keys match!

The code bellow outputs:

I/System.out: It's null

Main Activity:

public class MainMenu extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        //Some stuff here...

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(StorageHandler.TRANSACTION_DONE);
        registerReceiver(broadcastReceiver, intentFilter);
        Intent i = new Intent(this, StorageHandler.class);
        startService(i);
    }



    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle extra = getIntent().getBundleExtra("bundle");

            if(extra == null){
                System.out.println("It's null");
            }
            else {
                ArrayList<String> objects = (ArrayList<String>) extra.getSerializable("objects");
                System.out.println(objects.get(0));
            } 
        }
    };

}

IntentService:

public class StorageHandler extends IntentService{

    public static final String TRANSACTION_DONE = "xx.xxxxx.xxxxxx.TRANSACTION_DONE";

    public StorageHandler() {
        super("StorageHandler");
    }

    public void onCreate(){
        super.onCreate();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        notifyFinished();
    }

    private void notifyFinished(){
        ArrayList<String> objects = new ArrayList<String>();
        objects.add("Resulting Array here");

        Bundle extra = new Bundle();
        extra.putSerializable("objects", objects);

        Intent i = new Intent();
        i.setAction(xx.xxxxx.xxxxxx.StorageHandler.TRANSACTION_DONE);
        i.putExtra("bundle", extra);

        StorageHandler.this.sendBroadcast(i);
    }

Solution

  • You're attempting to retrieve the data from the wrong Intent.

    Change:

    Bundle extra = getIntent().getBundleExtra("bundle");
    

    To:

    Bundle extra = intent.getBundleExtra("bundle");
    

    The Intent that contains your data is supplied as one of the parameters of the BroadcastReceiver's onReceive() method.