在Android Listview中显示sqlite数据库值

时间:2012-03-20 08:46:37

标签: android sqlite

我正在使用以下代码显示存储在Android sqlite数据库中的值。

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

我的问题是,当我在List-view中显示数据库值时,每次执行时它都会成倍增加。在我的表创建中,我使用了“如果不存在则创建表”,但是每次执行时都会创建表。我该如何解决?

2 个答案:

答案 0 :(得分:2)

这一行来自onCreate()的{​​{1}}方法:

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")); 后,应在onCreate()类的DatabaseHandler方法中将它们插入到数据库中。

编辑:

请勿db.execSQL(CREATE_CONTACTS_TABLE);类的addContact()方法调用onCreate(),而是直接使用DatabaseHandler插入值!

db.insert()

答案 1 :(得分:0)

删除

 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"));

来自oncreate的这些行......每次运行你的应用程序时都会执行这些行..所以每次执行时它都会成倍增加