0

I have a Service which I start from my MainActivity. Then in the onStartCommand() I register to Broadcast Receivers. But I pass String value to both the broadcast receivers from the Service through Bundle. But I am getting NullpointerException in onReceiver() of the Broadcast receiver. Here is my Activity code.

@Override
protected void onStart() {
    super.onStart();
    if (bluetoothService == null) {
        kolamDeviceDialog();
    } else {
        Log.e("MenuBluetoothService", bluetoothService.getStatus() + "");
        if (!bluetoothService.getStatus()) {
            kolamDeviceDialog();
        }
    }
}

private void kolamDeviceDialog() {
    MaterialDialog.Builder builder = new MaterialDialog.Builder(MenuActivity.this)
            .title("Select Bot")
            .items(scanTypes)
            .itemsCallback(new MaterialDialog.ListCallback() {
                @Override
                public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
                    if (position == 0) {
                        isSmallBot = false;
                        KolamDevice kolamDevice = new KolamDevice();
                        Intent intent = new Intent(MenuActivity.this, BluetoothService.class);
                        intent.putExtra("Address", kolamDevice.getBigBotAddress());
                        intent.putExtra("Name", kolamDevice.getBigBotName());
                        startService(intent);
                        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
                    } else {
                        isSmallBot = true;
                        KolamDevice kolamDevice = new KolamDevice();
                        Intent intent = new Intent(MenuActivity.this, BluetoothService.class);
                        intent.putExtra("Address", kolamDevice.getSmallBotAddress());
                        intent.putExtra("Name", kolamDevice.getSmallBotName());
                        startService(intent);
                        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
                    }
                }
            });
    builder.show();
}

@Override
protected void onStop() {
    super.onStop();
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

Here is my Service code.

public class BluetoothService extends Service {

private final IBinder mBinder = new MyBinder();
private SmoothBluetooth smoothBluetooth;
private static Device device;
String address, name;
private List<Integer> mBuffer = new ArrayList<>();
private List<String> mResponseBuffer = new ArrayList<>();

public BluetoothService() {
}

@Override
public void onCreate() {
    super.onCreate();
    Log.e("BluetoothService", "onCreated");
    // startForeground(1, new Notification());
}

@Override
public void onDestroy() {
    super.onDestroy();
    Log.e("BluetoothService", "Killed");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("BluetoothService", "Started");
    startForeground(1, new Notification());
    Bundle extras = intent.getExtras();
    if (extras != null) {
        address = extras.getString("Address");
        name = extras.getString("Name");
    }
    Log.e("Address", address);
    Log.e("name", name);
    smoothBluetooth = new SmoothBluetooth(this);
    smoothBluetooth.setListener(mListener);

    startScheduleReceiver();
    startBootReceiver();

    if (smoothBluetooth.isBluetoothEnabled()) {
        if (!smoothBluetooth.isConnected()) {
            device = new Device(name, address, true);
            smoothBluetooth.tryConnection();
        }
    } else {
        device = new Device(name, address, true);
        smoothBluetooth.tryConnection();

    }
    return Service.START_NOT_STICKY;
}

private void startBootReceiver() {
    Intent broadcastIntent = new Intent(this, MyStartServiceReceiver.class);
    Bundle bundle = new Bundle();
    broadcastIntent.setAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    bundle.putString("BotType", name);
    broadcastIntent.putExtras(bundle);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager service = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar cal = Calendar.getInstance();
    // start 1 second after boot completed
    cal.add(Calendar.SECOND, 1);
    // fetch every 1 second
    // InexactRepeating allows Android to optimize the energy consumption
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
}

private void startScheduleReceiver() {
    Intent broadcastIntent = new Intent(this, MyScheduleReceiver.class);
    Bundle bundle = new Bundle();
    broadcastIntent.setAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    bundle.putString("BotType", name);
    broadcastIntent.putExtras(bundle);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager service = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Calendar cal = Calendar.getInstance();
    // start 1 second after boot completed
    cal.add(Calendar.SECOND, 1);
    // fetch every 1 second
    // InexactRepeating allows Android to optimize the energy consumption
    service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, sender);
}


@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

public class MyBinder extends Binder {
    BluetoothService getService() {
        return BluetoothService.this;
    }
}


public boolean getStatus() {
    Log.e("BluetoothServiceStatus", smoothBluetooth.isConnected() + "");
    return smoothBluetooth.isConnected();
}

Here is my 1st Broadcast receiver code.

public class MyStartServiceReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    Log.e("BootReceiver", "Started");
    Bundle bundle = intent.getExtras();
    String name = bundle.getString("BotType");
    if (name.equalsIgnoreCase("TEAMRED1")) {
        KolamDevice kolamDevice = new KolamDevice();
        Intent bigBotIntent = new Intent(context, BluetoothService.class);
        bigBotIntent.putExtra("Address", kolamDevice.getBigBotAddress());
        bigBotIntent.putExtra("Name", kolamDevice.getBigBotName());
        context.startService(bigBotIntent);
    } else {
        KolamDevice kolamDevice = new KolamDevice();
        Intent smallBotIntent = new Intent(context, BluetoothService.class);
        smallBotIntent.putExtra("Address", kolamDevice.getSmallBotAddress());
        smallBotIntent.putExtra("Name", kolamDevice.getSmallBotName());
        context.startService(smallBotIntent);
    }
}

}

Here is my 2nd Broadcast receiver code.

public class MyScheduleReceiver extends BroadcastReceiver {

private String name, address;

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Bundle bundle = intent.getExtras();
    String smallBot = bundle.getString("BotType");
    if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
        if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) {
            Log.e("BluetoothCondition", "On");
            Log.e("Bot", smallBot);


        } else if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_OFF) {
            Log.e("BluetoothCondition", "Off");
            Log.e("Bot", smallBot);
        }
    }
}

}

Here is the logcat error also.

java.lang.RuntimeException: Unable to start receiver com.ignite.a01hw909350.kolamdemo.MyScheduleReceiver: java.lang.NullPointerException: println needs a message
                                                                                  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2645)
                                                                                  at android.app.ActivityThread.access$1800(ActivityThread.java:154)
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                  at android.os.Looper.loop(Looper.java:135)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5290)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
                                                                               Caused by: java.lang.NullPointerException: println needs a message
                                                                                  at android.util.Log.println_native(Native Method)
                                                                                  at android.util.Log.e(Log.java:232)
                                                                                  at com.ignite.a01hw909350.kolamdemo.MyScheduleReceiver.onReceive(MyScheduleReceiver.java:28)
                                                                                  at android.app.ActivityThread.handleReceiver(ActivityThread.java:2638)
                                                                                  at android.app.ActivityThread.access$1800(ActivityThread.java:154) 
                                                                                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1399) 
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                  at android.os.Looper.loop(Looper.java:135) 
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5290) 
                                                                                  at java.lang.reflect.Method.invoke(Native Method) 
                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)

Please tell my why I am getting null in the onReceiver() of both the broadcast receivers.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

1 Answers1

0

your passing values from service to Broadcast Receiver is problematic.

use this: Keep it simple

For both the Receiver:

Intent broadcastIntent = new Intent(this, MyStartServiceReceiver.class);
broadcastIntent.setAction(BluetoothAdapter.ACTION_STATE_CHANGED);
broadcastIntent.putExtra("BotType", name);
//sendBroadcast(broadcastIntent);

Now inside onReceive()

 @Override
public void onReceive(Context context, Intent intent) {
  String action = intent.getAction();

  if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
     String smallBot = intent.getExtras().getString("BotType");
     //do your stuff
  }
}

Also add this:

if(smallBot!= null)
    Log.e("Bot", smallBot);
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • `Permission Denial: not allowed to send broadcast android.bluetooth.adapter.action.STATE_CHANGED from pid=23668, uid=10401` getting this error at sendBroadcast(broadcastIntent); –  Mar 25 '17 at 11:22
  • i didn't notice...you do not need this: `sendBroadcast(broadcastIntent);` – rafsanahmad007 Mar 25 '17 at 11:23
  • still getting `nullpointerexception` previous error. –  Mar 25 '17 at 11:26
  • i have showed with one...you need to update `MyScheduleReceiver`+ in your service where u calling `MyScheduleReceiver` update + ...because stacktrace shows problem in `MyScheduleReceiver` . And do a clean build also – rafsanahmad007 Mar 25 '17 at 11:30
  • I have updated for both the broadcasts but still the same `nullpointerexception` did a clean build also. And the error is coming in MyScheduleReceiver currently even after update. –  Mar 25 '17 at 11:38
  • from the log it shows that `smallBot` is null in onReceive() ...do a null check then print the log. i edited it – rafsanahmad007 Mar 25 '17 at 11:45
  • Ok let me check it. Power cut. Will update soon. –  Mar 25 '17 at 11:56
  • It's null only. –  Mar 25 '17 at 11:59
  • that's why you need to check whether it is null or not to avoid the exception... – rafsanahmad007 Mar 25 '17 at 12:37
  • I used another way. instead of passing values. I opened AlertDialog activity from the broadcast to do my desired work. –  Mar 26 '17 at 07:42