2012-03-20 130 views
0

我使用下面的代码来显示存储在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

此行从ActivityonCreate()方法:

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

将到数据库每次运行你的应用程序时插入此值。如果你只想在数据库中使用这个值,那么在你调用db.execSQL(CREATE_CONTACTS_TABLE);之后,你应该把它们插入到DatabaseHandler类的onCreate()方法的数据库中。

编辑:

不要呼叫从DatabaseHandler类的onCreate()方法addContact(),而不是直接与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

如果你不不介意,给我一个例子如何在我的代码中使用db.insert()。 – Aerrow 2012-03-20 09:22:10

+0

从您的活动使用db.insert()..你应该得到一个可写的数据库,而不是这一个.. SQLiteDatabase db = this.getReadableDatabase(); ....使用this.getWritableDatabase() – 5hssba 2012-03-20 09:29:17

+0

@Aerrow按照在addContact方法中所做的操作使用insert。问题是你不能使用这个方法在你的'DatabaseHandler'的'onCreate()'中添加联系人,因为你调用了这个方法'SQLiteDatabase db = this.getWritableDatabase();'这个调用会生成异常递归调用)。我编辑了我的答案。 – Luksprog 2012-03-20 09:33:23

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..these线线执行每次运行你的应用程序的时间。所以它是在你执行的每一次乘以