LocalBroadcastReciever not working in fragment

1.7k views Asked by At

I am trying to display a scanned barcode inside of an editText field (which is inside a fragment) using local broadcast receiver.

This is my code:

OnActivityResult in MainActivity.java

public void onActivityResult(int requestCode, int resultCode, Intent intent){
    Log.d("onActivityResultCalled", "yes");
    if(requestCode == IntentIntegrator.REQUEST_CODE){
        if (resultCode == RESULT_OK){
            String contents = intent.getStringExtra("SCAN_RESULT");
            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
            Log.d("content", contents);
            Log.d("format", format);
            Log.d("sender", "Broadcasting message");
            Intent scanIntent = new Intent("scanEvent");
            scanIntent.putExtra("isbn",contents);
            LocalBroadcastManager.getInstance(this).sendBroadcast(scanIntent);



        }else if(resultCode == RESULT_CANCELED){
            Log.e("MainActivity","Scan cancelled?");
        }
    }
}

Code for recieving broadcast and displaying the isbn:

@Override
public void onResume()
{
    super.onResume();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMessageReceiver,
            new IntentFilter("scanEvent"));
}

// Our handler for received Intents. This will be called whenever an Intent
// with an action named "scanEvent" is broadcasted.

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Get extra data included in the Intent
        isbnData = intent.getStringExtra("isbn");
        Log.d("receiver", "Got message: " + isbnData);
        isbn.setText(isbnData);
    }
};


@Override
public void onPause() {
    // Unregister since the activity is about to be closed.
    LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mMessageReceiver);
    super.onDestroy();
}

The scanning of the barcode itself works successfully. The issue is being able to display that barcode in the edittext.

1

There are 1 answers

0
loadedion On BEST ANSWER

It looks like you're unregistering your broadcast receiver.

Taking a look at this question regarding onResume and onActivityResult, onActivityResult gets called before onResume, so by the time your fragment registers as a receiver it's too late.

Try moving your broadcast receiver registration to onCreate and onDestroy instead.