创建一个单独的Database类android

时间:2014-12-16 06:27:30

标签: android android-sqlite

我是android的新手。在我的应用程序中,我需要创建4-5个表。我想知道我是否可以为所有表创建一个单独的数据库类和单独的类?因为这个我的代码我看起来很干净而不是使用

public DbAdapter extends SqliteOpenHelper{


//All the CRUD operations for 4-5 tables in same class

}

你能否建议如何分别启动数据库并将其用于不同表类的CRUD操作?

2 个答案:

答案 0 :(得分:0)

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

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 = "contactsManager";

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

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
    private static final String KEY_EMAIL = "email";
    private final ArrayList<Contact> contact_list = new ArrayList<Contact>();

    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 " + TABLE_CONTACTS + "("
        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
        + KEY_PH_NO + " TEXT," + KEY_EMAIL + " 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
    public void Add_Contact(Contact contact) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName()); // Contact Name
    values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
    values.put(KEY_EMAIL, contact.getEmail()); // Contact Email
    // Inserting Row
    db.insert(TABLE_CONTACTS, null, values);
    db.close(); // Closing database connection
    }

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

    Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
        KEY_NAME, KEY_PH_NO, KEY_EMAIL }, 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));
    // return contact
    cursor.close();
    db.close();

    return contact;
    }

    // Getting All Contacts
    public ArrayList<Contact> Get_Contacts() {
    try {
        contact_list.clear();

        // 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.setName(cursor.getString(1));
            contact.setPhoneNumber(cursor.getString(2));
            contact.setEmail(cursor.getString(3));
            // Adding contact to list
            contact_list.add(contact);
        } while (cursor.moveToNext());
        }

        // return contact list
        cursor.close();
        db.close();
        return contact_list;
    } catch (Exception e) {
        // TODO: handle exception
        Log.e("all_contact", "" + e);
    }

    return contact_list;
    }

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

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, contact.getName());
    values.put(KEY_PH_NO, contact.getPhoneNumber());
    values.put(KEY_EMAIL, contact.getEmail());

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

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

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

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

}

答案 1 :(得分:0)

这是您的数据访问者:

public class CategoryDataAccessor {

  private SQLiteDatabase database;
  private DbHelper dbHelper;
  private String[] allColumns = { Cat_Table.Cat_id,Cat_Table.Cat_Name};
  private static Context con;
//constructor
  public CategoryDataAccessor(Cntext cont){
     this.con = cont;
     dbHelper = new DbHelper(con);

 }

 public void Open() throws SQLException{
     database = dbHelper.getWritableDatabase();
 }

 public void Close(){
    dbHelper.close();   
}

 public Category CreateCategory(String CatName,String CatInfo, int recur_id){

    ContentValues values = new ContentValues();

    values.put(Cat_Table.Cat_Name, CatName);
    values.put(Cat_Table.Cat_Info, CatInfo);

    long insertId = database.insert(Cat_Table.Cat_Table, null,values);

    Cursor cursor =database.query(Cat_Table.Cat_Table, allColumns, 
            Cat_Table.Cat_id+ " = " +
             insertId, null, null, null, null, null);

    cursor.moveToFirst();
    //to return back the category just inserted
    Category newCat = RetrieveCategory(cursor);
    cursor.close();

    return newCat;
 }

 public void deleteCategory(String id) {

    database.delete(Cat_Table.Cat_Table, Cat_Table.Cat_id
            + " = " + id, null); 
   }

 public List<Category> getAllCategories() {

     List<Category> cats = new ArrayList<Category>();

     Cursor cursor = database.query(Cat_Table.Cat_Table,
         allColumns, null, null, null, null, null);
     cursor.moveToFirst();

    while (!cursor.isAfterLast()) {

      Category cat = RetrieveCategory(cursor);

      //adding category to the list
      cats.add(cat);
      cursor.moveToNext();
    }
    // make sure to close the cursor
    cursor.close();

    return cats;
  }



private Category RetrieveCategory(Cursor cursor) {
    Category cat = new Category();

    String KEY_ID = "_id";
    String KEY_NAME = "cat_name";
    String KEY_INFO = "cat_info";

    //while(cursor.moveToFirst()){
    cat.setId(cursor.getLong(cursor.getColumnIndex(KEY_ID)));
    cat.setCategoryName(cursor.getString(cursor.getColumnIndex(KEY_NAME)).toString());
    cat.setCategoryInfo(cursor.getString(cursor.getColumnIndex(KEY_INFO)).toString());     

    return cat;
  }


}

DBHelper:

public class DbHelper extends SQLiteOpenHelper {

public DbHelper(Context context) {

    super(context, Cat_Table.DbName, null, Cat_Table.Version);

}

@Override
public void onCreate(SQLiteDatabase db) {

    db.execSQL(Cat_Table.CREATE_CATEGORY_TABLE);
    db.execSQL(Notes_Table.CREATE_NOTES_TABLE);
    System.out.println(Notes_Table.CREATE_NOTES_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXISTS '" + Cat_Table.Cat_Table + "'");

    onCreate(db);
}

}

表格信息:

public class TableData {

public static abstract class Cat_Table implements BaseColumns{

    public static final String Cat_id = "_id";
    public static final String Cat_Name = "cat_name";

    public static final String Cat_Table = "Category";

    public static final String DbName = "YOURDBNAME.db";
    public static final int Version =3;

    //For creating Category Table
     public static final String CREATE_CATEGORY_TABLE =
             "create table "+ Cat_Table +"(" + 
              Cat_id + " integer primary key autoincrement, " +
              Cat_Name + " text not null);";    
}

我已经在3个课程中实现了它。