带有内部类的databasehandler

时间:2015-01-27 10:29:10

标签: java

我试图安排我的DatabaseHandler(外部类),以便我的数据库中的每个表都在一个内部类下。我的代码看起来像这样;

公共类DatabaseHandler扩展了SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;

public static final String DATABASE_NAME = "databaseName";

private static SQLiteDatabase db;

private static final String CUSTOMERS_TABLE_NAME = "customers",...;
private static final String USERS_TABLE_NAME = "users",...;
private static final String PRODUCTS_TABLE_NAME = "products",...;
private static final String FORMS_TABLE_NAME = "forms",...;

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

@Override
public void onCreate(SQLiteDatabase db) {
    String SQL_STRING = "CREATE TABLE " + CUSTOMERS_TABLE_NAME + "(" +
    .
    .
    .
    db.execSQL(SQL_STRING);
    SQL_STRING = "CREATE TABLE " + USERS_TABLE_NAME + "(" +
    .
    .
    .
    db.execSQL(SQL_STRING);
    SQL_STRING = "CREATE TABLE " + PRODUCTS_TABLE_NAME + "(" +
    .
    .
    .
    db.execSQL(SQL_STRING);
    SQL_STRING = "CREATE TABLE " + FORMS_TABLE_NAME + "(" +
    .
    .
    .
    db.execSQL(SQL_STRING);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + CUSTOMERS_TABLE_NAME+" AND    "+USERS_TABLE_NAME+" AND "+PRODUCTS_TABLE_NAME+" AND "+FORMS_TABLE_NAME);

    onCreate(db);
    }
}

在这个类中,我想要4个代表4个数据库表的内部类。每个内部类都会使用CRUD方法。内在的课堂;

public class customersHandler{
       public void createCustomer(customerStructure customer){
           .
           .
           .
        }
        public customerStructure getCustomer(String customerName){
           .
           .
           .
        }
        public void deleteCustomer(customerStructure customer){
           .
           .
           .
        }
        public int updateCustomer(customerStructure customer){
           .
           .
           .
        }
        .
        .
        .
}

我该怎么办?我在主要活动中声明如下:

public class MainActivity extande ActionBarActivity(){

DatabaseHandler db;
DatabaseHandler.customersHandler CH;

@Override
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    db=new DatabaseHandler(getApplicationContext());
    CH=db.new customersHandler();
    }
}
那是对的吗?怎么了?

1 个答案:

答案 0 :(得分:0)

在外部类中创建内部类的实例,然后为它们定义getter。

public class DatabaseHandler {
    CustomerHandler ch = new CustomerHandler();

     CustomerHandler getCustomerHandler() {
         return(ch);
     }

然后用户获取句柄并使用它们:

    DatabaseHandler dh = new DatabaseHandler();
    dh.getCustomerHandler().createCustomer(customer);