отобразить значения базы данных sqlite в Android Listview - PullRequest
0 голосов
/ 20 марта 2012

Я использую следующий код для отображения значений, хранящихся в базе данных 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;
    }
}

Здесь моя проблема заключается в том, что при отображении значений базы данных в режиме просмотра списка она умножалась при каждом выполнении.При создании таблицы я использовал «Создать таблицу, если она не существует», но таблица создавалась при каждом выполнении.Как я могу решить это?

Ответы [ 2 ]

2 голосов
/ 20 марта 2012

Это строки из onCreate() метода вашего 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()!

//...
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);
}
0 голосов
/ 20 марта 2012

удалить

 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 .. эти строки выполняются каждый раз, когда вы запускаете ваше приложение .. поэтому они умножаются при каждом запуске

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...