0

I created a new Android project in Android Studio 1.4 beta 4. I just added the org.altbeacon:android-beacon-library:2.5.1 to Gradle, and added the line:

private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);

to the onCreate() as follow:

public class MainActivity extends AppCompatActivity {
    protected static final String TAG = "BeaconActivity";
    private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }
}

After adding this and Run, the following RuntimeException has occurred and the App has crashed:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference

I didn't use the above codes obviously. How can I resolve the issue?

Raptor
  • 53,206
  • 45
  • 230
  • 366

1 Answers1

1

your mistake are here :

 private BeaconManager beaconManager = BeaconManager.getInstanceForApplication(this);

you tried to make a object from BeaconManager by "this" , but this activity is not created by the system but by you. So this InstalledApp object does not have Context object bounded to system.

just try this :

private BeaconManager beaconManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    beaconManager = BeaconManager.getInstanceForApplication(this);
    beaconManager.bind(this);
}
Saeid
  • 2,261
  • 4
  • 27
  • 59