I am trying to write a app which scans for beacons, when I login to the app, it starts scanning but after some seconds it just crashes. if I turn off my bluetooth it works fine. this is the error I get:
Process: com.noxel.apppaneladmintry2, PID: 11192
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.niloofar.showroom.BeaconsFragment.onScannerClosed()' on a null object reference
at com.example.niloofar.showroom.BeaconScannerFragment.onCancel(BeaconScannerFragment.java:56)
at android.app.Dialog$ListenersHandler.handleMessage(Dialog.java:1260)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
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:921)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:716)
and this is my code,
package com.example.niloofar.showroom;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.UUID;
import no.nordicsemi.android.beacon.Beacon;
import no.nordicsemi.android.beacon.BeaconRegion;
import no.nordicsemi.android.beacon.BeaconServiceConnection;
import no.nordicsemi.android.beacon.Proximity;
import no.nordicsemi.android.beacon.ServiceProxy;
public class drawermenu extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, BeaconServiceConnection.BeaconsListener, BeaconServiceConnection.RegionListener {
public ProfileFragment profileFragment;
private static final String SCANNER_FRAGMENT = "scannerFragment";
public static final String NRF_BEACON_SERVICE_URL = "market://details?id=no.nordicsemi.android.beacon.service";
public static final String OPENED_FROM_LAUNCHER = "no.nordicsemi.android.nrfbeacon.extra.opened_from_launcher";
public static final String EXTRA_OPEN_DFU = "no.nordicsemi.android.nrfbeacon.extra.open_dfu";
public static final int BEACON_COMPANY_ID = 0x0059;
private static final int REQUEST_ENABLE_BT = 1;
private boolean mServiceConnected;
private boolean mFragmentResumed;
private DatabaseHelper mDatabaseHelper;
private BeaconAdapter mAdapter;
private BeaconScannerFragment mScannerFragment;
int minor;
public Fragment fragment=null;
public FragmentA fragmentA;
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(this, "Device dows not support Bluetooth", Toast.LENGTH_LONG);
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
mDatabaseHelper = new DatabaseHelper(this);
getSupportActionBar().setElevation(0);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}catch (Exception ex) {
Log.d("ERROR", ex.getMessage());
}
}
@Override
public void onStart() {
super.onStart();
// final Cursor cursor = mDatabaseHelper.getAllRegions();
bindService();
}
@Override
public void onResume() {
super.onResume();
// startScanning();
if (mFragmentResumed)
return;
mFragmentResumed = true;
// bindService();
onAddOrEditRegion();
}
@Override
public void onPause() {
super.onPause();
// stopScanning();
if (!mFragmentResumed)
return;
mFragmentResumed = false;
unbindService();
}
private BeaconServiceConnection mServiceConnection = new BeaconServiceConnection() {
@Override
public void onServiceConnected() {
try {
mServiceConnected = true;
final BeaconScannerFragment scannerFragment = mScannerFragment;
if (scannerFragment != null) {
startRangingBeaconsInRegion(BEACON_COMPANY_ID, BeaconRegion.ANY_UUID, scannerFragment);
} else {
// final FragmentManager fm = getChildFragmentManager();
// if (fm.getBackStackEntryCount() == 0) {
// Start scan only if there is no any other fragment (Mona Lisa) open
startScanning();
// }
}
} catch (Exception ex) {
Log.d("ERROR", ex.getMessage());
}
}
@Override
public void onServiceDisconnected() {
try {
mServiceConnected = false;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
};
public void onAddOrEditRegion() {
// if (!ensurePermission())
// return;
try {
stopScanning();
// mScannerFragment=null;
final BeaconScannerFragment fragment = mScannerFragment = new BeaconScannerFragment();
fragment.show(getSupportFragmentManager(), SCANNER_FRAGMENT);
// fragment.isHidden();
mServiceConnection.startRangingBeaconsInRegion(BEACON_COMPANY_ID, BeaconRegion.ANY_UUID, fragment);
}
catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void startScanning() {
try {
if (mServiceConnected) {
startScanning(mServiceConnection);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void stopScanning() {
try {
if (mServiceConnected) {
stopScanning(mServiceConnection);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void bindService() {
// if (!ensurePermission())
// return;
try {
final boolean success = ServiceProxy.bindService(this, mServiceConnection);
if (!success) {
new AlertDialog.Builder(this).setTitle(R.string.service_required_title).setMessage(R.string.service_required_message)
.setPositiveButton(R.string.service_required_store, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
final Intent playIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(MainActivity.NRF_BEACON_SERVICE_URL));
startActivity(playIntent);
}
}).setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(final DialogInterface dialog) {
dialog.dismiss();
finish();
}
}).show();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void unbindService() {
try {
if (mServiceConnected) {
// Unbinding service will stop all active scanning listeners
ServiceProxy.unbindService(this, mServiceConnection);
mDatabaseHelper.resetSignalStrength();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void startScanning(final BeaconServiceConnection serviceConnection) {
try {
final Cursor cursor = mDatabaseHelper.getAllRegions();
while (cursor.moveToNext()) {
final UUID uuid = UUID.fromString(cursor.getString(2 /* UUID */));
final int major = cursor.getInt(3 /* MAJOR */);
final int minor = cursor.getInt(4 /* MINOR */);
final int event = cursor.getInt(6 /* EVENT */);
// We must start ranging for all beacons
serviceConnection.startRangingBeaconsInRegion(BEACON_COMPANY_ID, uuid, major, minor, this);
// And additionally start monitoring only for those with these two events set
if (event == BeaconContract.EVENT_IN_RANGE || event == BeaconContract.EVENT_OUT_OF_RANGE)
serviceConnection.startMonitoringForRegion(BEACON_COMPANY_ID, uuid, major, minor, this);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void stopScanning(final BeaconServiceConnection serviceConnection) {
try {
if (serviceConnection != null) {
serviceConnection.stopMonitoringForRegion(this);
serviceConnection.stopRangingBeaconsInRegion(this);
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
@Override
public void onBeaconsInRegion(final Beacon[] beacons, final BeaconRegion region) {
try {
if (beacons.length > 0) {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
// Check and fire events
final int event = cursor.getInt(6 /* EVENT */);
for (final Beacon beacon : beacons) {
if (event == BeaconContract.EVENT_ON_TOUCH && Proximity.IMMEDIATE.equals(beacon.getProximity()) && Proximity.NEAR.equals(beacon.getPreviousProximity())) {
fireEvent(cursor);
break;
}
if (event == BeaconContract.EVENT_GET_NEAR && Proximity.NEAR.equals(beacon.getProximity()) && Proximity.FAR.equals(beacon.getPreviousProximity())) {
fireEvent(cursor);
break;
}
}
// Update signal strength in the database
float accuracy = 5;
for (final Beacon beacon : beacons)
if (Proximity.UNKNOWN != beacon.getProximity() && beacon.getAccuracy() < accuracy)
accuracy = beacon.getAccuracy();
accuracy = -20 * accuracy + 100;
mDatabaseHelper.updateRegionSignalStrength(cursor.getLong(0 /* _ID */), (int) accuracy);
}
} finally {
cursor.close();
}
mAdapter.swapCursor(mDatabaseHelper.getAllRegions());
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
@Override
public void onEnterRegion(final BeaconRegion region) {
try {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
final int event = cursor.getInt(6 /* EVENT */);
if (event == BeaconContract.EVENT_IN_RANGE) {
fireEvent(cursor);
}
}
} finally {
cursor.close();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
@Override
public void onExitRegion(final BeaconRegion region) {
try {
final Cursor cursor = mDatabaseHelper.findRegion(region);
try {
if (cursor.moveToNext()) {
final int event = cursor.getInt(6 /* EVENT */);
if (event == BeaconContract.EVENT_OUT_OF_RANGE) {
fireEvent(cursor);
}
}
} finally {
cursor.close();
}
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
private void fireEvent(final Cursor cursor) {
try {
final boolean enabled = cursor.getInt(9 /* ENABLED */) == 1;
if (!enabled)
return;
final int action = cursor.getInt(7 /* ACTION */);
final String actionParam = cursor.getString(8 /* ACTION PARAM */);
switch (action) {
case BeaconContract.ACTION_MONA_LISA: {
stopScanning();
// final DialogFragment dialog = new MonalisaFragment();
// dialog.show(mParentFragment.getChildFragmentManager(), "JIRNG");
break;
}
case BeaconContract.ACTION_SILENT: {
stopScanning();
// final DialogFragment dialog = new tarh();
// dialog.show(mParentFragment.getChildFragmentManager(), "JIRING");
break;
}
case BeaconContract.ACTION_ALARM: {
stopScanning();
// final DialogFragment dialog = new rest();
// dialog.show(mParentFragment.getChildFragmentManager(), "Jiring");
break;
}
case BeaconContract.ACTION_URL: {
stopScanning();
try {
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(actionParam));
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_application, Toast.LENGTH_SHORT).show();
}
break;
}
case BeaconContract.ACTION_APP: {
stopScanning();
try {
final Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setPackage(actionParam);
startActivity(intent);
} catch (final ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_given_application, Toast.LENGTH_SHORT).show();
}
break;
}
case BeaconContract.ACTION_TASKER:
// switch (TaskerIntent.testStatus(getActivity())) {
// case OK:
// final TaskerIntent i = new TaskerIntent(actionParam);
final BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, final Intent recIntent) {
// if (recIntent.getBooleanExtra(TaskerIntent.EXTRA_SUCCESS_FLAG, false))
Toast.makeText(drawermenu.this, R.string.tasker_success, Toast.LENGTH_SHORT).show();
drawermenu.this.unregisterReceiver(this);
}
};
// getActivity().registerReceiver(br, i.getCompletionFilter());
// Start the task
// getActivity().sendBroadcast(i);
break;
// case NotEnabled:
// Toast.makeText(getActivity(), R.string.tasker_disabled, Toast.LENGTH_SHORT).show();
// break;
// case AccessBlocked:
// Toast.makeText(getActivity(), R.string.tasker_external_access_denided, Toast.LENGTH_SHORT).show();
// break;
// case NotInstalled:
// Toast.makeText(getActivity(), R.string.tasker_not_installed, Toast.LENGTH_SHORT).show();
// break;
default:
Toast.makeText(this, R.string.tasker_error, Toast.LENGTH_SHORT).show();
break;
}
// break;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public void onEditRegion(final long id) {
// final Intent intent = new Intent(this, BeaconsDetailsActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
// intent.putExtra(BeaconsDetailsActivity.ID, id);
// startActivity(intent);
}
public void onScannerClosedWithResult(final Beacon beacon) {
try {
mServiceConnection.stopRangingBeaconsInRegion(mScannerFragment);
mScannerFragment.dismiss();
mScannerFragment = null;
// final Cursor cursor = mDatabaseHelper.findRegionByBeacon(beacon);
minor = beacon.getMinor();
Intent intenta = new Intent(drawermenu.this, FragmentA.class);
switch (minor) {
case 99:
// startActivity(intenta);
popUp();
break;
case 246:
// startActivity(intenta);
// Toast.makeText(MainActivity.this, "246", Toast.LENGTH_LONG).show();
popUp();
break;
case 63:
popUp();
break;
case 104:
popUp();
break;
}
}
catch (Exception ex)
{
Log.e("ERROR", ex.getMessage());
}
}
private void popUp()
{
new Handler().post(new Runnable() {
@Override
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(drawermenu.this,FragmentA.class);
// mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
drawermenu.this.startActivity(mainIntent);
// Splash.this.finish();
}
});
}
public void onScannerClosed() {
try {
mServiceConnection.stopRangingBeaconsInRegion(mScannerFragment);
mScannerFragment = null;
startScanning();
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
public DatabaseHelper getDatabaseHelper() {
return mDatabaseHelper;
}
private boolean ensureBleExists() {
try {
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.no_ble, Toast.LENGTH_LONG).show();
return false;
}
return true;
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
return false;
}
}
private boolean isBleEnabled() {
try {
final BluetoothManager bm = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
final BluetoothAdapter ba = bm.getAdapter();
return ba != null && ba.isEnabled();
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
return false;
}
}
private void enableBle() {
try {
final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
Log.e("ERROR", ex.getMessage());
}
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if (id == R.id.nav_home) {
// Handle the camera action
fragment = new ProfileFragment();
} else if (id == R.id.nav_points) {
fragment = new PointFragment();
} else if (id == R.id.nav_coupons) {
fragment = new CouponFragment();
} else if (id == R.id.nav_about) {
fragment = new AboutFragment();
}
fragmentTransaction.replace(R.id.appbar, fragment,fragment.getClass().getSimpleName());
fragmentTransaction.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
and this is the code which error is referring to:
package com.example.niloofar.showroom;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import no.nordicsemi.android.beacon.Beacon;
import no.nordicsemi.android.beacon.BeaconRegion;
import no.nordicsemi.android.beacon.BeaconServiceConnection;
import no.nordicsemi.android.beacon.Proximity;
/**
* Created by niloofar on 11/9/2016.
*/
public class BeaconScannerFragment extends DialogFragment implements BeaconServiceConnection.BeaconsListener {
// public class BeaconScannerFragment extends DialogFragment implements BeaconServiceConnection.BeaconsListener {
private boolean mCompleted;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCompleted = false;
}
@Override
public void onBeaconsInRegion(final Beacon[] beacons, final BeaconRegion region) {
if (!mCompleted) {
for (final Beacon beacon : beacons)
if (Proximity.IMMEDIATE == beacon.getProximity()) {
mCompleted = true;
final BeaconsFragment parentFragment = (BeaconsFragment) getParentFragment();
parentFragment.onScannerClosedWithResult(beacon);
dismiss();
break;
}
}
}
@NonNull
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
return new AlertDialog.Builder(getContext())
.setView(R.layout.fragment_scan).create();
}
@Override
public void onCancel(final DialogInterface dialog) {
super.onCancel(dialog);
final BeaconsFragment targetFragment = (BeaconsFragment) getParentFragment();
targetFragment.onScannerClosed();
}}
does anyone know how my problem will be solved?
This is the place where your problem occurs:
You initialize
parentFragment
, but theNullPointerException
is thrown when you try to callonScannerClosedWithResult
. This means thatparentFragment
isnull
. To solve this, you have three options. The first option is to usetry
-catch
where you handle theNullPointerException
. The second option is to make sure thatgetParentFragment
will never returnnull
. The third option is to fail gracefully whennull
is returned: