我在一个类中编写了此方法,用于检查数据库中是否存在表:
public boolean DoesTableExist(String tableName) {
SQLiteDatabase mDatabase = openOrCreateDatabase("privdb",MODE_PRIVATE,null);
Cursor cursor = mDatabase.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
我现在想在其他 Activity 或类中调用此方法,而无需每次在每个文件中编写相同的代码。 我怎样才能做到这一点?
最佳答案
通常,您可以通过实例化另一个类然后调用该方法来调用该类中的方法。例如,如果该方法所在的类名为 DatabaseUtils
,您将执行以下操作:
DatabaseUtils dbUtils = new DatabaseUtils();
boolean exists = dbUtils.doesTableExist("tablename");
// ^ note that the normal Java convention is to make
// method names start with a lower case letter
但是,这具有“实用”方法的感觉(该对象可能不存储任何状态,因此不需要实例化它),处理这些方法的常见方法是使方法静态,像这样:
public static boolean doesTableExist(String tableName) {
这会导致该方法存在于类定义本身上,而不是存在于类的特定实例上,并允许您执行以下操作:
boolean exists = DatabaseUtils.doesTableExist("tablename");
关于java - 从一个类调用另一个类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54915003/