-4

I guys, i'm doing an excercise on android where a button when clicked retrive all name of WIFI in the zone. I need to save some information on database but when i run the project, stop with a NullPointerException qhen open the database

LOGCAT

03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime: FATAL EXCEPTION: main
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime: java.lang.RuntimeException: Error receiving broadcast Intent { act=android.net.wifi.SCAN_RESULTS flg=0x8000010 } in com.example.davide.prova.DisplayMessageActivity$WifiScanReceiver@42465e28
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:765)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:615)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:4867)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:  Caused by: java.lang.NullPointerException
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at com.example.davide.prova.DisplayMessageActivity$WifiScanReceiver.onReceive(DisplayMessageActivity.java:89)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:755)
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:615) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:4867) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774) 
03-04 18:44:16.225 12670-12670/com.example.davide.prova E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

This is the class where I declare the DB:

public class DBAdapter {

    private static final String LOG_TAG = "DatabaseUtil";

    /*NOME DEL DATABASE*/

    private static final String DB_NAME = "DB_WIFIdiscover";

    private static final int DB_VERSION = 1;

    /*NOMI TABELLE*/

    private static final String DB_TABLE_WIFI_INFO = "Table_stato_wifi";
    private static final String DB_TABLE_LOCATION = "Table_dove_sei";

    /*DATABASE INFORMAZIONI RELATIVE AL WIFI TROVATO*/

    /*DATABASE COORDINATE*/

    public static final String COLUMN_LOCATION_ID = "LocationID";
    public static final String COLUMN_LATITUDINE = "Longitudine";
    public static final String COLUMN_LONGITUDINE = "Latitudine";

    private static final String SQL_CREATE_ENTRIES = "create table " //
            + DB_TABLE_LOCATION + " (" //
            + COLUMN_LOCATION_ID + "  integer primary key autoincrement, " //
            + COLUMN_LATITUDINE + " DOUBLE NOT NULL, " //
            + COLUMN_LONGITUDINE + " DOUBLE NOT NULL);";

    private final Context mCtx;

    private FROpenHelper dbHelper;

    private SQLiteDatabase mDb;

    private String TAG = this.getClass().getCanonicalName();

    //private SQLiteDatabase db;      //si riferisce al database
    //private FROpenHelper dbHelper;  //si riferisce all'OpenHelper

    private static class FROpenHelper extends SQLiteOpenHelper {

        public FROpenHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) throws SQLException {
            Log.w(LOG_TAG, "Creating database.");
            try {
                db.execSQL(SQL_CREATE_ENTRIES);
            } catch (SQLException e) {
                Log.e(LOG_TAG, e.getMessage());
                throw e;
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(LOG_TAG, "Upgrading from version " + oldVersion + " to " + newVersion
                    + ", which will destroy all old data");

            // Create a new one.
            onCreate(db);
        }
    }

    public DBAdapter(Context context) {
        this.mCtx = context;
    }
    public DBAdapter open() throws SQLException {
        try {
            dbHelper = new FROpenHelper(mCtx);
            mDb = dbHelper.getWritableDatabase();
        } catch (SQLiteException e) {
            Log.e(TAG, e.getMessage());
            throw e;
        }
        return this;
    }

    /**
     * Close the DB.
     */
    public void close() {
        dbHelper.close();
    } 

And this is the class where I call the method open:

    public class DisplayMessageActivity extends AppCompatActivity {
    ListView lv;
    WifiManager wifi;
    String wifis[];
    WifiScanReceiver wifiReciever;
    public DBAdapter dbAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);
        //
        lv = (ListView)findViewById(R.id.listView);
        wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        wifiReciever = new WifiScanReceiver();
        wifi.startScan();

        //layout dell'activity

        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();
            }
        });
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    protected void onPause() {
        unregisterReceiver(wifiReciever);
        super.onPause();
    }

    protected void onResume() {
        registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
        super.onResume();
    }

    @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;
    }

    private class WifiScanReceiver extends BroadcastReceiver {
        @TargetApi(Build.VERSION_CODES.M)
        public void onReceive(Context c, Intent intent) {
            List<ScanResult> wifiScanList = wifi.getScanResults();//lista degli hotspot trovati
            wifis = new String[wifiScanList.size()];//array di stringhe della lunghezza del numeri di hotspot trovati

            //for(int i = 0; i < wifiScanList.size(); i++){
                    //if(wifiScanList.get(i).is80211mcResponder() == true){//controlla se è un canale 802.11, se lo è lo salva nel database
                       // wifis[i] = ((wifiScanList.get(i).SSID).toString());
                        //Inserisco nel DB i valori della rete wireless
                        //long idpos = dbAdapter.insertDB();
                        //if(idpos == -1){
                        //}
                        dbAdapter.open();
                        dbAdapter.insertDB();//passa valori della rete
                        dbAdapter.close();

                    //}

                //SSID nome della rete, BSSID modalità di funzionamento wifi, frequency, level(dbm)
            //}
            lv.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,wifis));//reference to an built-in XML layout document that is part of the Android OS
        }
    }
}

Please help me because i don't know where the problem is !

Daniele Segato
  • 12,314
  • 6
  • 62
  • 88
dvdLucka
  • 51
  • 7

1 Answers1

1

You need to learn how to read a Java stacktrace

Nullpointers are the most easy error to fix usually.

Caused by: java.lang.NullPointerException
     at com.example.davide.prova.DisplayMessageActivity$WifiScanReceiver.onReceive(DisplayMessageActivity.java:89)

You always want to look for the first cause of you error (Caused By) This has nothing to do with Android or the database.

Look at line 89 of your file. Something in that line is null and you call a method on it. Understand why that is null / when can it be will lead to fixing the exception.

Daniele Segato
  • 12,314
  • 6
  • 62
  • 88
  • At line 89 I call dbAdapter.open(), but the DB isn't null – dvdLucka Mar 04 '16 at 18:02
  • Is dbAdapter itself NULL? I see DBAdapter has a constructor that takes context, but I don't see any instantiation of the dbAdapter object. – BryanT Mar 04 '16 at 18:05