显示java.lang.NullPointerException ... [英] java.lang.NullPointerException...

查看:669
本文介绍了显示java.lang.NullPointerException ...的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用mobstac sdk在灯塔上制作应用程序。我正在建立一个数据库,当用户进入插座然后它显示存在信标的插座名称。当我运行我的应用程序时,它显示nullpointerexception该怎么办?



BeaconAdapter.java



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

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





DatabaseHelper.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




MainActivity.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详情:



06-23 11:34:51.191 1096-1096 / com.mobstac.beaconstacexample E / AndroidRuntime:FATAL EXCEPTION:main

流程:com.mobstac.beaconstacexample,PID:1096

java.lang.RuntimeException:无法启动活动ComponentInfo {com.mobstac.beaconstacexample / com.mobstac.beaconstacexample.MainActivity}:java.lang.NullPointerException:尝试调用虚方法'int com.mobstac一个空对象引用的.beaconstac.models.MSBeacon.getMajor()'

在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)

在android。 app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)

在android.app.ActivityThread.access $ 800(ActivityThread.java:144)

在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1278)

在android.os上。 Handler.dispatchMessage(Handler.java:102)

在android.os.Looper.loop(Looper.java:135)

在android.app.ActivityThread.main( ActivityThread.java:5221)

at java.lang.reflect.Method.invoke(Native Method)

at java.lang.reflect.Method.invoke(Method.java :372)

com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:899)

at com.android.internal.os.ZygoteInit .main(ZygoteInit.java:694)

引起:java.lang.NullPointerException:尝试在null上调用虚方法'int com.mobstac.beaconstac.models.MSBeacon.getMajor()'对象引用

at com.mobstac.beaconstacexample.DatabaseHelper.getAllTables(DatabaseHelper.java:80)

at com.mobstac.beaconstacexample.MainActivity.onCreate(MainActivity.java: 64)

在android.app.Activity.performCreate(Activity.java:5933)

在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)

在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)

          &n bsp;  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)


}

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)

推荐答案

800(ActivityThread.java:144)

at android.app.ActivityThread
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.jav a: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
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.callActivityOnCre ate(Instrumentation.java:1105)

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)

            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)

            at android.app.ActivityThread.access
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


这篇关于显示java.lang.NullPointerException ...的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆