0

I'm using the following code to display the values stored in Android sqlite database.

AndroidSQLiteTutorialActivity.java

public class AndroidSQLiteTutorialActivity extends Activity {
    /** Called when the activity is first created. */
    ArrayList alarmList = new ArrayList();
    List<Contact> contacts;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        ListView mListView = (ListView) findViewById(R.id.listView1);
        ArrayAdapter mAdapter = new ArrayAdapter<String>(
                AndroidSQLiteTutorialActivity.this,
                android.R.layout.simple_list_item_1, alarmList);
        mListView.setAdapter(mAdapter);

        DatabaseHandler db = new DatabaseHandler(this);

        /**
         * CRUD Operations
         * */
        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addContact(new Contact("10", "00", "0", "0", "0", "0", "0", "0"));
        db.addContact(new Contact("04, "00", "0", "0", "0", "0", "0", "0"));
        db.addContact(new Contact("05", "00", "0", "0", "0", "0", "0", "0"));
        db.addContact(new Contact("07", "00", "0", "0", "0", "0", "0", "0"));

        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        contacts = db.getAllContacts();

        for (Contact cn : contacts) {
            String log = "Id: " + cn.getID() + " ,Hours: " + cn.get_hours()
                    + " ,Minutes: " + cn.get_minutes() + " ,DaysOfWeeks: "
                    + cn.get_daysofweek() + " ,AlarmTime: "
                    + cn.get_alramTime() + " ,Enabled: " + cn.get_enabled()
                    + " ,Vibrate: " + cn.get_vibrate() + " ,Message: "
                    + cn.get_message() + " ,Alert: " + cn.get_alert();
            // Writing Contacts to log
            String timeDisplay = cn.get_hours() + ":" + cn.get_minutes();
            alarmList.add(timeDisplay);
            Log.d("Name: ", log);

        }
    }
}

DatabaseHandler.java

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 3;

    // Database Name
    private static final String DATABASE_NAME = "contactsManager";

    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    public static final String KEY_HOUR = "hours";
    public static final String KEY_MINUTES = "minutes";
    public static final String KEY_DAYSOFWEEK = "daysofweek";
    public static final String KEY_ALARMTIME = "alramtime";
    public static final String KEY_ENABLED = "enabled";
    public static final String KEY_VIBRATE = "vibrate";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_ALERT = "alert";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS "
                + TABLE_CONTACTS + "(" + KEY_ID + " INTEGER PRIMARY KEY,"
                + KEY_HOUR + " TEXT," + KEY_MINUTES + " TEXT," + KEY_DAYSOFWEEK
                + " TEXT," + KEY_ALARMTIME + " TEXT," + KEY_ENABLED + " TEXT,"
                + KEY_VIBRATE + " TEXT," + KEY_MESSAGE + " TEXT," + KEY_ALERT
                + " TEXT" + ")";

        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        // Create tables again
        onCreate(db);
    }

    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_HOUR, contact.get_hours());
        values.put(KEY_MINUTES, contact.get_minutes());
        values.put(KEY_DAYSOFWEEK, contact.get_daysofweek());
        values.put(KEY_ALARMTIME, contact.get_alramTime());
        values.put(KEY_ENABLED, contact.get_enabled());
        values.put(KEY_VIBRATE, contact.get_vibrate());
        values.put(KEY_MESSAGE, contact.get_message());
        values.put(KEY_ALERT, contact.get_alert());

        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }

    // Getting single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_HOUR, KEY_MINUTES, KEY_DAYSOFWEEK, KEY_ALARMTIME,
                KEY_ENABLED, KEY_VIBRATE, KEY_MESSAGE, KEY_ALERT }, KEY_ID
                + "=?", new String[] { String.valueOf(id) }, null, null, null,
                null);
        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2), cursor.getString(3),
                cursor.getString(4), cursor.getString(5), cursor.getString(6),
                cursor.getString(7), cursor.getString(8));
        // return contact
        return contact;
    }

    // Getting All Contacts
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.set_hours(cursor.getString(1));
                contact.set_minutes(cursor.getString(2));
                contact.set_daysofweek(cursor.getString(3));
                contact.set_alramTime(cursor.getString(4));
                contact.set_enabled(cursor.getString(5));
                contact.set_vibrate(cursor.getString(6));
                contact.set_message(cursor.getString(7));
                contact.set_alert(cursor.getString(8));

                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }

    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_HOUR, contact.get_hours());
        values.put(KEY_MINUTES, contact.get_minutes());
        values.put(KEY_DAYSOFWEEK, contact.get_daysofweek());
        values.put(KEY_ALARMTIME, contact.get_alramTime());
        values.put(KEY_ENABLED, contact.get_enabled());
        values.put(KEY_VIBRATE, contact.get_vibrate());
        values.put(KEY_MESSAGE, contact.get_message());
        values.put(KEY_ALERT, contact.get_alert());

        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }

    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }

    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}

Contact.java

public class Contact {



    public String get_alramTime() {
        return this._alramTime;
    }

    public void set_alramTime(String _alramTime) {
        this._alramTime = _alramTime;
    }

    public String get_enabled() {
        return this._enabled;
    }

    public void set_enabled(String _enabled) {
        this._enabled = _enabled;
    }

    public String get_vibrate() {
        return this._vibrate;
    }

    public void set_vibrate(String _vibrate) {
        this._vibrate = _vibrate;
    }

    public String get_message() {
        return this._message;
    }

    public void set_message(String _message) {
        this._message = _message;
    }

    public String get_alert() {
        return this._alert;
    }

    public void set_alert(String _alert) {
        this._alert = _alert;
    }

    public String get_hours() {
        return this._hours;
    }

    public void set_hours(String _hours) {
        this._hours = _hours;
    }

    public String get_minutes() {
        return this._minutes;
    }

    public void set_minutes(String _minutes) {
        this._minutes = _minutes;
    }

    public String get_daysofweek() {
        return this._daysofweek;
    }

    public void set_daysofweek(String _daysofweek) {
        this._daysofweek = _daysofweek;
    }

    // private variables
    int _id;
    String _hours;
    String _minutes;
    String _daysofweek;
    String _alramTime;
    String _enabled;
    String _vibrate;
    String _message;
    String _alert;

    // Empty constructor
    public Contact() {

    }

    // constructor
    public Contact(int id, String hours, String minutes, String daysofweek,
            String alarmtime, String enabled, String vibrate, String message,
            String alert) {
        this._id = id;
        this._hours = hours;
        this._minutes = minutes;
        this._daysofweek = daysofweek;
        this._alramTime = alarmtime;
        this._enabled = enabled;
        this._vibrate = vibrate;
        this._message = message;
        this._alert = alert;
    }

    // constructor
    public Contact(String hours, String minutes, String daysofweek,
            String alarmtime, String enabled, String vibrate, String message,
            String alert) {
        this._hours = hours;
        this._minutes = minutes;
        this._daysofweek = daysofweek;
        this._alramTime = alarmtime;
        this._enabled = enabled;
        this._vibrate = vibrate;
        this._message = message;
        this._alert = alert;

    }

    // getting ID
    public int getID() {
        return this._id;
    }

    // setting id
    public void setID(int id) {
        this._id = id;
    }
}

Here my problem is, when I display the database values in List-view, it was multiplied at every time of my execution. In my table creation I used "Create table if not exists" but the table was created at every time of execution. How can I solve it?

2 Answers 2

2

This lines from the onCreate() method of your Activity:

db.addContact(new Contact("10", "00", "0", "0", "0", "0", "0", "0"));
db.addContact(new Contact("04, "00", "0", "0", "0", "0", "0", "0"));
db.addContact(new Contact("05", "00", "0", "0", "0", "0", "0", "0"));
db.addContact(new Contact("07", "00", "0", "0", "0", "0", "0", "0"));

will insert this values in to the database each time you run your app. If you want this values in the database only once then you should insert them in the database in the onCreate() method of your DatabaseHandler class after you've called db.execSQL(CREATE_CONTACTS_TABLE);.

EDIT:

DON'T call the addContact() from the onCreate() method of the DatabaseHandler class instead insert the values directly with db.insert()!

//...
db.execSQL(CREATE_CONTACTS_TABLE);
ArrayList<Contact> toInsert = new ArrayList<Contact>();
toInsert.add(new Contact("10", "00", "0", "0", "0", "0", "0", "0"));
toInsert.add(new Contact("04, "00", "0", "0", "0", "0", "0", "0"));
toInsert.add(new Contact("05", "00", "0", "0", "0", "0", "0", "0"));
toInsert.add(new Contact("07", "00", "0", "0", "0", "0", "0", "0"));
for (int i = 0; i < toInsert.size(); i++) {
       ContentValues values = new ContentValues();
        values.put(KEY_HOUR, toInsert.get(i).get_hours());
        values.put(KEY_MINUTES, toInsert.get(i).get_minutes());
        values.put(KEY_DAYSOFWEEK, toInsert.get(i).get_daysofweek());
        values.put(KEY_ALARMTIME, toInsert.get(i).get_alramTime());
        values.put(KEY_ENABLED, toInsert.get(i).get_enabled());
        values.put(KEY_VIBRATE, toInsert.get(i).get_vibrate());
        values.put(KEY_MESSAGE, toInsert.get(i).get_message());
        values.put(KEY_ALERT, toInsert.get(i).get_alert());
        db.insert(TABLE_CONTACTS, null, values);
}
Sign up to request clarification or add additional context in comments.

3 Comments

if you don't mind, give me an example how to use db.insert() in my code.
to use db.insert() from your activity.. you should get a writable database instead of this one..SQLiteDatabase db = this.getReadableDatabase(); ....use this.getWritableDatabase()
@Aerrow Use insert as you did in the addContact method. The problem is you can't use this method to add contacts in the onCreate() of your DatabaseHandler because you call in that method SQLiteDatabase db = this.getWritableDatabase(); and this call will generate and exception(recursive call). I've edited my answer.
0

remove

 db.addContact(new Contact("10", "00", "0", "0", "0", "0", "0", "0"));
    db.addContact(new Contact("04, "00", "0", "0", "0", "0", "0", "0"));
    db.addContact(new Contact("05", "00", "0", "0", "0", "0", "0", "0"));
    db.addContact(new Contact("07", "00", "0", "0", "0", "0", "0", "0"));

these lines from oncreate..these lines are executed every time you run your app.. so it is being multiplied at every time of your execution

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.