Question

I have an embedded database file(Macs.db in assets directory) of MAC addresses in my application.The database is a very simple sqlite database with just one table. The table named mactoname has two columns: 1. macaddress, 2.name. There are some preloaded mac addresses and names in this embedded database file. I have a wifi analyzer tool to detect mac addresses in a place. The code for this analyzer is given below(from marakana.com):

public class WiFiScanner extends Activity {

            TextView name;
            TextView textView;
            WifiManager wifi;
            BroadcastReceiver receiver;
            Button buttonScan,updatemacdb;

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                setContentView(R.layout.scannerwifi);

                textView = (TextView) this.findViewById(R.id.wifitext);
                buttonScan = (Button) findViewById(R.id.buttonScan);
                updatemacdb=(Button) findViewById(R.id.buttonupdatezoneDB);
                wifi = (WifiManager) this.getSystemService(WIFI_SERVICE);
                name=(TextView) this.findViewById(R.id.edittextname);

                buttonScan.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        wifi.startScan();

                    }
                });
                updatemacdb.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {


                    }
                });
                if (receiver == null)
                    receiver = new WiFiScanReceiver(this);

                registerReceiver(receiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));

                populate();

            }

            private void populate() {
                String text = "";
                List<ScanResult> access_points = wifi.getScanResults();
                for(int i = 0 ; i < access_points.size() ; i++){
                    ScanResult ap = access_points.get(i);
                    text += "#SSID: " + ap.SSID + "/MAC: " + ap.BSSID + "\n\n";
                }
                textView.setText(text);
                Log.d("Wifi Display", text);

            }


            class WiFiScanReceiver extends BroadcastReceiver {

                WiFiScanner wifiScanner;

                public WiFiScanReceiver(WiFiScanner wifisc) {
                super();
                this.wifiScanner = wifisc;
                }

                @Override
                public void onReceive(Context c, Intent intent) {
                    wifiScanner.populate();
                }
            }
            public void onBackPressed() {
                unregisterReceiver(receiver);
            }   
        }

now, as i detect the mac addresses i want to update the Macs.db by putting the detected mac addresses into the Macs.db file. the update should be done on following button click:

updatemacdb.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {


            }
        });

if a mac address already exists then it will not be put in Macs.db again. Together with detected new mac addresses in the macaddress coulmn, the name typed by user in the edittext view will be updated in the name column of mactoname table in Macs.db, too. I have an implementation of SQLiteOpenHelper class. What codes do i need inside this helper class and inside OnClickListener of updatemacdb button in order to update the database with new mac addreses and names ?

my SQLiteOpenHelper class is given below.Which methods do i need to modify in this class?

public class DbAdapternew {
    private static final String TAG = DbAdapter.class.getName();
    private DatabaseHelper mDbHelper;
    public static SQLiteDatabase myDb;
    public static String DATABASE_NAME;
    public static String DATABASE_TABLE;
    public static String DATABASE_PATH;
    public static String LOCAL_DATABASE_NAME;
    private static final int DATABASE_VERSION = 2;
    private static Context myContext;

    private static class DatabaseHelper extends SQLiteOpenHelper {


        Context helperContext;

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            helperContext = context;
        }


        @Override
        public void onCreate(SQLiteDatabase db) {
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database!!!!!");
            onCreate(db);
        }

        public void createDataBase() throws IOException {
            Log.i(TAG,"DB NAME : "+DATABASE_NAME);
            Log.i(TAG,"DB PATH : "+DATABASE_PATH);
            Log.i(TAG,"LOCAL DB NAME : "+LOCAL_DATABASE_NAME);


            boolean dbExist = checkDataBase();
            if (dbExist) {
            } else {
                this.getReadableDatabase();
                try {
                    copyDataBase();
                } catch (IOException e) {
                    //throw new Error("Error copying database");
                }
            }
        }

        public SQLiteDatabase getDatabase() {
            String myPath = DATABASE_PATH + DATABASE_NAME;
            return SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);
        }

        private boolean checkDataBase() {
            SQLiteDatabase checkDB = null;
            try {
                String myPath = DATABASE_PATH + DATABASE_NAME;
                checkDB = SQLiteDatabase.openDatabase(myPath, null,
                        SQLiteDatabase.OPEN_READONLY);
            } catch (SQLiteException e) {
            }
            if (checkDB != null) {
                checkDB.close();
            }
            return checkDB != null ? true : false;
        }

        private void copyDataBase() throws IOException {

            Log.i(TAG,"LOCAL DB NAME : "+LOCAL_DATABASE_NAME);
            // Open your local db as the input stream
            InputStream myInput = myContext.getAssets().open(LOCAL_DATABASE_NAME);

            // Path to the just created empty db
            String outFileName = DATABASE_PATH + DATABASE_NAME;

            // Open the empty db as the output stream
            OutputStream myOutput = new FileOutputStream(outFileName);

            // transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }

            // Close the streams
            myOutput.flush();
            myOutput.close();
            myInput.close();
        }

        public void openDataBase() throws SQLException {
            // Open the database
            String myPath = DATABASE_PATH + DATABASE_NAME;
            myDb = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READWRITE);
        }

        @Override
        public synchronized void close() {

            if (myDb != null)
                myDb.close();

            super.close();

        }
    }


    public DbAdapternew(Context ctx) {
        this.myContext = ctx;
    }

    public DbAdapternew open() throws SQLException {
        mDbHelper = new DatabaseHelper(myContext);

        try {
            mDbHelper.createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }

        try {
            mDbHelper.openDataBase();
            mDbHelper.copyDataBase();
        } catch (SQLException sqle) {
            throw sqle;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return this;

    }

    public void close() {
        mDbHelper.close();
    }

    public Cursor fetchAllData(String table) {

        try {
            myDb.rawQuery("SELECT * FROM " + table, null);
            Log.i(TAG, "Row Collected");
        } catch (SQLiteException e) {
            myDb.execSQL("CREATE TABLE IF NOT EXISTS " + table
                    + " (mac_add VARCHAR)");
            Log.i(TAG, "TABLE Not Found");
        }
        return myDb.rawQuery("SELECT * FROM " + table, null);
    }

    public Cursor fetchData(String sqlQuery) {

        try {
            myDb.rawQuery(sqlQuery, null);
            Log.i(TAG, "Query Executed");
        } catch (SQLiteException e) {
            Log.i(TAG, e.toString());
        }
        return myDb.rawQuery(sqlQuery, null);
    }

    public void executeQuery(String sql) {
        myDb.execSQL(sql);
    }
     public static SQLiteDatabase getWritableDatabase() {
         String myPath = DATABASE_PATH + DATABASE_NAME;
         return SQLiteDatabase.openDatabase(myPath, null,
                 SQLiteDatabase.OPEN_READONLY);
     }
}
Was it helpful?

Solution

It should be something like this:

updatemacdb.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {

                String sqlInsert = "INSERT INTO ...";
                String sqlUpdate = "UPDATE ... WHERE ...";

                try{            
                    mSQLiteOpenHelperObject.getWritableDatabase().execSQL(sqlInsert);
                }                
                catch (SQLiteExeption e) {
                    mSQLiteOpenHelperObject.getWritableDatabase().execSQL(sqlUpdate);
                }
            }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top