0

I'm following a beginner tutorial of SQLite for a mobile application and still I'm having a problem with the output. The data will be shown on a ListView but everytime I run it from my Eclipse to my phone the data is being added instead of having a list of 3 everytime I run the application from the Eclipse it will then have an output with a list of 6, 9, 12, 15 and so on. I guess the old table is not being drop by the SQLite upgrade.

I'm having the following codes in my database:

    public class DatabaseHandler extends SQLiteOpenHelper
    {
        //all static variables; database version
        private static final int DATABASE_VERSION = 1;

        //database name
        private static final String DATABASE_NAME = "devicesqlite.db";

        //Tag for Logcat
        private static final String LOGCAT = null;

    //for the switch //same in ControllerTab
        private final static Integer[] ids = { R.id.switch1, R.id.switch2, R.id.switch3 };

        public DatabaseHandler(Context applicationContext) {
            //super(context, name, factory, version);
            super(applicationContext, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            //String CREATE_DEVICES_TABLE = " CREATE TABLE " + TABLE_DEVICES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT" + ")";
            String createQuery = "CREATE TABLE devices ( deviceID INTEGER PRIMARY KEY, deviceName TEXT)";
            db.execSQL(createQuery);
            Log.d(LOGCAT, "TABLE devices CREATED");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            //drop older table if existed
            String dropQuery = ("DROP TABLE IF EXISTS devices");
            db.execSQL(dropQuery);
            onCreate(db); //create tables again
        }

        //adding new device
        public void addDevice(Device device) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("deviceName", device.getName());
            db.insert("devices", null, values); //inserting row
            db.close();
        }

            //getting all devices
        public ArrayList<HashMap<String, String>> getAllDevices() {
            ////ArrayList<Device> deviceList = new ArrayList<Device>();
            ArrayList<HashMap<String, String>> deviceList;
            deviceList = new ArrayList<HashMap<String, String>>();

            //Select All query
            String selectQuery = "SELECT * FROM devices";
            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            //looping through all rows and adding to list
            if (cursor.moveToFirst()) {
                do
                {
                             HashMap<String, String> map = new HashMap<String, String>();
                    map.put("deviceID", cursor.getString(0));
                    map.put("deviceName", cursor.getString(1));
                    deviceList.add(map);

                }
                while (cursor.moveToNext());
            }

            return deviceList;
        }

    //updating single device
        //this method accepts Device class object as parameter
        public int updateDevice(HashMap<String, String> queryValues) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues values = new ContentValues();
            values.put("deviceName", queryValues.get("deviceName"));

            //updating row
            return db.update("devices", values, "deviceID" + " = ?", new String[] { queryValues.get("deviceID")});
        }

    public HashMap<String, String> getDeviceInfo(String id) {
            HashMap<String, String>

 wordList = new HashMap<String, String>();
        SQLiteDatabase db = this.getReadableDatabase();
        String selectQuery = "SELECT * FROM devices WHERE deviceID ='" + id + "'";
        //Cursor cursor = db.rawQuery(sql, selectionArgs)
        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                //wordList.put("deviceName", cursor.getString(1));
                wordList.put("deviceID", cursor.getString(1));
            } while (cursor.moveToNext());
        }
        return wordList;
    }

And I'm having these in my ControllerTab class to have the output:

DatabaseHandler db = new DatabaseHandler(this);


        // Inserting Devices
        Log.d("Insert: ", "Inserting .."); 
        db.addDevice(new Device(1, "DB Device 1"));        
        db.addDevice(new Device(2, "DB Device 2"));
        db.addDevice(new Device(3, "DB Device 3"));

ArrayList<HashMap<String, String>> deviceList = db.getAllDevices();
        if(deviceList.size()!=0) {
            ListView list = getListView();
            list.setOnItemClickListener(new OnItemClickListener() {
                  @Override 
                  public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
                      deviceID = (TextView) view.findViewById(R.id.deviceId);
                      String valdeviceID = deviceID.getText().toString();                     
                      Intent  objIndent = new Intent(getApplicationContext(),EditDeviceName.class);
                      objIndent.putExtra("deviceID", valdeviceID); 
                      startActivity(objIndent); 
                  }
            }); 
            ListAdapter adapter = new SimpleAdapter( ControllerTab.this, deviceList, R.layout.activity_main_view, new String[] { "deviceId","deviceName"}, new int[] {R.id.deviceId, R.id.deviceName}); 
            setListAdapter(adapter);

Any help or suggestions will be very appreciated. THANK YOU.

itsJane
  • 15
  • 5
  • did you change your version from 1 to 2 ?? – Ranjit Feb 23 '14 at 09:01
  • OnUpdate is called when the Database Version changes, you can use it when updating you app to make proper changes. In your example you add 3 devices everything you display the list, so it's normal to have 3 more each time. – Stephane Mathis Feb 23 '14 at 09:03
  • I didn't change anything in my version. Should I change it evrytime I run the app from eclipse? – itsJane Feb 23 '14 at 09:08
  • Also change `CREATE TABLE devices` to 'CREATE TABLE IF NOT EXISTS devices` for good practices :) – Suzon Feb 23 '14 at 09:14

1 Answers1

0

onUpgrade() is only called when the version number you passed to the SQLiteOpenHelper superclass constructor is greater than that stored in the database file. Your DATABASE_VERSION is 1 so it does not get called. See also: When is SQLiteOpenHelper onCreate() / onUpgrade() run?

If you need to prepopulate your database with data, do it in the database helper onCreate(). It is only run the first time the database is created.

Community
  • 1
  • 1
laalto
  • 150,114
  • 66
  • 286
  • 303
  • So I'm going to incresingly change the value of `DATABASE_VERSION` everytime I run it again? – itsJane Feb 23 '14 at 09:07
  • @Vanessa No, just move the insert code you don't want to repeat from activity `onCreate()` to database helper `onCreate()`. – laalto Feb 23 '14 at 09:09