0

I'm still a bit new to Java and went straight in Android programming so I'm a little bit confused in some programming practices.. I just want to ask how can I call this method from another class to my OnCreate()? My method is in DBFunctions.java. Basically, I will use this in my game's options.

public void checkExistence(Cursor check) {
    String sql = "SELECT * FROM option WHERE id = 1";
    check = db.rawQuery(sql, null);`
}

I want to call this in my OnCreate(). If value exists, I just want first to display "Value exists", else "No Value exists". Please also correct me if the cursor inside the parameter is right..

4

4 回答 4

1

创建一个实例,DBFunctions然后调用checkExistence(). 例如:

DBFunctions dbfunc = new DBFunctions();
    if (dbfunc.checkExistence()) {
        /* do something */
    } else {
       /* do something else */
    }

所以改变你的checkExistence()签名:返回一个布尔值,并且 Cursor 应该是你方法中的一个局部变量:

public boolean checkExistence() {
    boolean exists = false;
    String sql = "SELECT * FROM option WHERE id = 1";
    Cursor cursor = db.rawQuery(sql, null);
    exists =  (cursor.getCount() > 0);
    cursor.close();
    return exists;
}

另一种选择是将static修饰符添加到checkExistence()并按如下方式调用它:

if (DBFunctions.checkExistence()) {
    /* do something */
} else {
   /* do something else */
}
于 2012-04-05T18:14:45.680 回答
0

要从另一个类调用此方法,您首先必须创建DBFunctions. 然后这个方法调用的语法看起来像这样:

Cursor mycursor = ...;

DBFunctions myFunctions = new DBFunctions();
myFunctions.checkExistence(mycursor);

或者,如果您想避免创建 的实例DBFunctions,可以将 static 关键字添加到方法声明中,例如:

public static void checkExistence(Cursor check) {
    String sql = "SELECT * FROM option WHERE id = 1";
    check = db.rawQuery(sql, null);
}

然后,您可以在没有实例的情况下调用静态方法DBFunctions

DBFunctions.checkExistence(mycursor);
于 2012-04-05T18:10:02.363 回答
0

首先,您应该在方法中将 Cursor 声明为局部变量。获得 Cursor 后,检查该值是否存在并返回一个布尔值。方法原型应如下所示:

public boolean checkExistence()

在 onCreate 方法中,您将调用它,如下所示:

if (new DBFunctions().checkExistence()) {
    // do something
} else {
   // do something else
}
于 2012-04-05T18:07:57.060 回答
0

如果你想调用任何属于其他类的方法,你可以通过引用它的类名来调用它,如下所示:::(使该函数成为静态的)

ClassName.FunctionName() 就是这样......

即使你可以从你的函数返回值,如果 void 使用你的返回类型......

于 2012-04-05T18:08:06.000 回答