Click here to Skip to main content
15,936,122 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
I make an app on beacon using mobstac sdk. I am making an database when an user go into the outlet then it shows the outlet name in which beacon is present.When i run my app it show an nullpointerexception what to do ?

BeaconAdapter.java

Java
public class BeaconAdapter extends BaseAdapter {

       private ArrayList<msbeacon> beacons;
       private Context ctx;
       private LayoutInflater myInflator;

       public BeaconAdapter(ArrayList<msbeacon> arr, Context c) {
           super();
           beacons = arr;
           ctx = c;
           myInflator = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       }

       public void addBeacon(MSBeacon beacon) {
           if(!beacons.contains(beacon)) {
               beacons.add(beacon);
           }
       }

       public void removeBeacon(MSBeacon beacon) {
           if(beacons.contains(beacon)) {
               beacons.remove(beacon);
           }
       }

       public void clear() {
           beacons.clear();
       }

       @Override
       public int getCount() {
           return beacons.size();
       }

       @Override
       public MSBeacon getItem(int position) {
           return beacons.get(position);
       }

       @Override
       public long getItemId(int position) {
           return position;
       }

       @Override
       public void notifyDataSetChanged() {
           Collections.sort(beacons, new Comparator<msbeacon>() {
               @Override
               public int compare(MSBeacon lhs, MSBeacon rhs) {
                   if (lhs.getIsCampedOn())
                       return -1;
                   else if (rhs.getIsCampedOn())
                       return 1;
                   else
                       return 0;
               }
           });

           super.notifyDataSetChanged();
       }

       @Override
       public View getView(int position, View view, ViewGroup parent) {

           if (view == null) {
               view = myInflator.inflate(R.layout.beacon_view, parent, false);
           }
           MSBeacon beacon = beacons.get(position);

           TextView name = (TextView) view.findViewById(R.id.device_name);
           name.setText(beacon.getBeaconUUID().toString());

           TextView key = (TextView) view.findViewById(R.id.device_address);
           key.setText("Major: " + beacon.getMajor() + "\t\t\t Minor: " + beacon.getMinor() +
                   " \t\t\t  Mean RSSI: " + beacon.getMeanRSSI());

           if (beacon.getIsCampedOn() == true) {
               view.setBackgroundResource(android.R.color.holo_green_light);
           } else {
               view.setBackgroundResource(android.R.color.background_light);
           }

           return view;

       }

   }


DatabaseHelper.java

Java
public class DatabaseHelper extends SQLiteOpenHelper {
        private static final String LOG = DatabaseHelper.class.getName();
        private static String DB_PATH = "/data/data/com.mobstac.Beaconstacexample/databases/";
        private static final int DATABASE_VERSION = 1;
        private static final String DATABASE_NAME = "OutletManager.db";
        private static final String TABLE_Table = "mytable";
        private static final String ID = "id";
        private static final String Beacon_MajorID = "beacon_Majorid";
        private static final String Beacon_MinorID = "beacon_Minorid";
        private static final String OUTLET_KEY_Name = "outlet_Name";
        private static int a;
        private static int b;
    
    
        private MSBeacon beacon;
        private Table table;
        private ArrayList<table> tablelist;
        private static final String CREATE_TABLE_Table = "CREATE TABLE " + TABLE_Table
                + "("
                + ID + " INTEGER PRIMARY KEY,"
                +  Beacon_MajorID + " INTEGER ,"
                + Beacon_MinorID + " INTEGER ,"
                +OUTLET_KEY_Name + " Text);";
    
    
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
    
            db.execSQL(CREATE_TABLE_Table);
    
        }
    
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_Table);
    
            onCreate(db);
        }
        public int createTable(Table table) {
            SQLiteDatabase db = this.getWritableDatabase();
    
            ContentValues values = new ContentValues();
    
            values.put(Beacon_MajorID, table.getTableName());
            values.put(Beacon_MinorID, table.getTableName());
            values.put(OUTLET_KEY_Name, table.getTableName());
    
    
            // insert row
             db.insert(TABLE_Table, null, values);
    
    return 0;
    
        }
    
        /**
         * getting all tables
         * */
        public List<table> getAllTables() {
            a=beacon.getMajor();
            b=beacon.getMinor();
            List<table> tables = new ArrayList<table>();
            String selectQuery = "SELECT OUTLET_KEY_Name FROM " +TABLE_Table + " WHERE " + Beacon_MajorID +
            "=a'" + Beacon_MinorID + "=b'" ;
    
            Log.e(LOG, selectQuery);
    
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor c = db.rawQuery(selectQuery, null);
    
            // looping through all rows and adding to list
            if (c.moveToFirst()) {
                do {
                    Table t = new Table();
                    t.setId(c.getInt((c.getColumnIndex(ID))));
                    t.setId(c.getInt((c.getColumnIndex(Beacon_MajorID))));
                    t.setId(c.getInt((c.getColumnIndex(Beacon_MinorID))));
                    t.setTableName(c.getString(c.getColumnIndex(OUTLET_KEY_Name)));
    
                    // adding to tags list
                    tables.add(t);
                } while (c.moveToNext());
            }
            return tables;
        }
    
        /**
         * Updating a tag
         */
        public int updateTable(Table table) {
            SQLiteDatabase db = this.getWritableDatabase();
    
            ContentValues values = new ContentValues();
            values.put(ID, table.getTableName());
            values.put(Beacon_MajorID, table.getTableName());
            values.put(Beacon_MinorID, table.getTableName());
            values.put(OUTLET_KEY_Name, table.getTableName());
    
            // updating row
            return db.update(TABLE_Table, values, ID + " = ?",
                    new String[] { String.valueOf(table.getId()) });
        }
    
        /**
         * Deleting a tag
         */
        public void deleteTable(Table table) {
            SQLiteDatabase db = this.getWritableDatabase();
    
    
    
            // now delete the tag
            db.delete(TABLE_Table, ID + " = ?",
                    new String[] { String.valueOf(table.getId()) });
        }
    
        public void closeDB() {
            SQLiteDatabase db = this.getReadableDatabase();
            if (db != null && db.isOpen())
                db.close();
        }
    
    }

MainActivity.java

Java
public class MainActivity extends Activity {
       DatabaseHelper db;
       private static final String TAG = MainActivity.class.getSimpleName();
       Bundle extras;
       private ArrayList<msbeacon> beacons = new ArrayList<msbeacon>();

       private BeaconAdapter beaconAdapter;
       private ListView beaconList;
       private TextView bCount;

       private TextView testCamped;

       private BluetoothAdapter mBluetoothAdapter;
       private static final int REQUEST_ENABLE_BT = 1;

       private boolean registered = false;
      private int beacon_Majorid3;
       private int beacon_Majorid2;
       private int beacon_Majorid1;



       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           db = new DatabaseHelper(getApplicationContext());
          Table outlet1 = new Table("Outlet1");
          Table outlet2 = new Table("Outlet2");
          Table outlet3 = new Table("Outlet3");


          // Inserting beacon_ids in db
           beacon_Majorid1 = db.createTable(outlet1);
           beacon_Majorid2 = db.createTable(outlet2);
          beacon_Majorid3 = db.createTable(outlet3);

          Log.d("Table Count", "Table Count: " + db.getAllTables(null).size());
          Log.d("Get Tables", "Getting All Tables");

          List<table> allTables = db.getAllTables(null);
          for (Table table : allTables) {
              Log.d("Outlet Name", table.getTableName());

                  Toast.makeText(MainActivity.this,"OUTLET_KEY_Name",Toast.LENGTH_LONG);



          }
          db.closeDB();
           // Use this check to determine whether BLE is supported on the device.
           if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
               Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
           }

           // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
           // BluetoothAdapter through BluetoothManager.
           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
               BluetoothManager mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
               mBluetoothAdapter = mBluetoothManager.getAdapter();
           }

           // Checks if Bluetooth is supported on the device.
           if (mBluetoothAdapter == null) {
               Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
               Toast.makeText(this, "Unable to obtain a BluetoothAdapter", Toast.LENGTH_LONG).show();
           } else {
               if (!mBluetoothAdapter.isEnabled()) {
                   Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                   startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
               }
           }



               if (savedInstanceState == null) {
               initList();
           }
           startService(new Intent(this, MSBLEService.class));
       }





       private void initList() {
           beaconList      = (ListView) findViewById(R.id.beaconListView);
           beaconAdapter   = new BeaconAdapter(beacons, this);
           beaconList.setAdapter(beaconAdapter);

           bCount = (TextView) findViewById(R.id.beaconCount);
           testCamped = (TextView) findViewById(R.id.CampedView);
           registerBroadcast();
       }

       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
           // Inflate the menu; this adds items to the action bar if it is present.
           getMenuInflater().inflate(R.menu.menu_main, menu);
           return true;
       }

       @Override
       protected void onPause() {
           super.onPause();
           beaconAdapter.clear();
           beaconAdapter.notifyDataSetChanged();
           bCount.setText("" + beacons.size());
           unregisterBroadcast();
       }

       @Override
       protected void onStart() {
           super.onStart();
       }

       @Override
       protected void onResume() {
           super.onResume();
           initList();
           bCount.setText("" + beacons.size());
           registerBroadcast();
       }

       @Override
       protected void onDestroy() {
           super.onDestroy();
           unregisterBroadcast();
       }

       // Callback intent results
       @Override
       protected void onActivityResult(int requestCode, int resultCode, Intent data) {
           if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
               finish();
               return;
           }
           super.onActivityResult(requestCode, resultCode, data);
       }

       private void registerBroadcast() {
           if (!registered) {
               IntentFilter intentFilter = new IntentFilter();
               intentFilter.addAction(MSConstants.BEACONSTAC_INTENT_RANGED);
               intentFilter.addAction(MSConstants.BEACONSTAC_INTENT_CAMPED);
               intentFilter.addAction(MSConstants.BEACONSTAC_INTENT_EXITED);
               registerReceiver(myBroadcastReceiver, intentFilter);
               registered = true;
           }
       }

       private void unregisterBroadcast() {
           if (registered) {
               unregisterReceiver(myBroadcastReceiver);
               registered = false;
           }
       }

       BeaconstacReceiver myBroadcastReceiver = new BeaconstacReceiver() {
           @Override
           public void exitedBeacon(Context context, MSBeacon beacon) {
               testCamped.setText("Exited: " + beacon.getMajor() + ":" + beacon.getMinor());
               beaconAdapter.notifyDataSetChanged();
           }
           @Override
           public void rangedBeacons(Context context, ArrayList<msbeacon> rangedBeacons) {
               bCount.setText("" + rangedBeacons.size());
               beaconAdapter.clear();
               beacons.addAll(rangedBeacons);
               beaconAdapter.notifyDataSetChanged();

                   }


           @Override
                   public void campedOnBeacon (Context context, MSBeacon beacon){
                       testCamped.setText("Camped: " + beacon.getMajor() + ":" + beacon.getMinor());
                       beaconAdapter.addBeacon(beacon);
                       beaconAdapter.notifyDataSetChanged();
                   }
               } ;

}

Logcat details:

06-23 11:34:51.191 1096-1096/com.mobstac.beaconstacexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobstac.beaconstacexample, PID: 1096
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobstac.beaconstacexample/com.mobstac.beaconstacexample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.mobstac.beaconstac.models.MSBeacon.getMajor()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.mobstac.beaconstac.models.MSBeacon.getMajor()' on a null object reference
at com.mobstac.beaconstacexample.DatabaseHelper.getAllTables(DatabaseHelper.java:80)
at com.mobstac.beaconstacexample.MainActivity.onCreate(MainActivity.java:64)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Posted
Updated 23-Jun-15 3:04am
v4
Comments
Richard Deeming 22-Jun-15 9:00am    
Debug your code.
Member 11713406 23-Jun-15 7:55am    
Logcat details:

06-23 11:34:51.191 1096-1096/com.mobstac.beaconstacexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.mobstac.beaconstacexample, PID: 1096
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobstac.beaconstacexample/com.mobstac.beaconstacexample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.mobstac.beaconstac.models.MSBeacon.getMajor()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
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:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int com.mobstac.beaconstac.models.MSBeacon.getMajor()' on a null object reference
at com.mobstac.beaconstacexample.DatabaseHelper.getAllTables(DatabaseHelper.java:80)
at com.mobstac.beaconstacexample.MainActivity.onCreate(MainActivity.java:64)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Sergey Alexandrovich Kryukov 22-Jun-15 9:03am    
In what line?
—SA
Member 11713406 22-Jun-15 9:07am    
at com.mobstac.beaconstacexample.DatabaseHelper.getAllTables(DatabaseHelper.java:82)
at com.mobstac.beaconstacexample.MainActivity.onCreate(MainActivity.java:64)
Sergey Alexandrovich Kryukov 22-Jun-15 9:14am    
Use the debugger and inspect all object which are supposed to be not null...
—SA

1 solution

Based on the stack-track in your comments, you've passed a null value to the getAllTables method, which then attempts to call a method on that MSBeacon instance.

Looking at your code, the error appears to be in the following lines within your MainActivity's onCreate method:
Java
Log.d("Table Count", "Table Count: " + db.getAllTables(null).size());
...
List<table> allTables = db.getAllTables(null);
</table>


But you could have found and fixed that error yourself by using the debugger!
 
Share this answer
 
Comments
Member 11713406 23-Jun-15 9:04am    
I changed in databasehelper.java file in getalltables method make field beacon instead of parameter in getalltables. remove null from getalltables in MainActivity.java file but shows same error after run app in Mobile shows The app has Stopped
Richard Deeming 23-Jun-15 9:06am    
If it's showing the same error, then you haven't fixed your code.

Use the debugger to step through the code and find the thing that's null when you don't expect it to be. Then go back and work out why it's null.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900