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..
Create an instance of DBFunctions
and then call checkExistence()
. For example:
DBFunctions dbfunc = new DBFunctions();
if (dbfunc.checkExistence()) {
/* do something */
} else {
/* do something else */
}
So change your checkExistence()
signature: return a boolean and Cursor should be a local variable in your method:
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;
}
Another option is add the static
modifier to checkExistence()
and call it as follows:
if (DBFunctions.checkExistence()) {
/* do something */
} else {
/* do something else */
}
checkExistence()
- Enrique Marcos 2012-04-05 20:39
First of all you should declare the Cursor as a local variable in your method. After you obtain the Cursor check if the value exists and return a boolean. The method prototype should look like:
public boolean checkExistence()
From the onCreate method you will call this as follows:
if (new DBFunctions().checkExistence()) {
// do something
} else {
// do something else
}
If you want to call any method that is been other class you can call it by reference to its class name like below:::(Make that function static)
ClassName.FunctionName() thats all....
even you can return value from your function just instead if void use your return type...
To call this method from another class, you first have to create an instance of the DBFunctions
. Then the syntax for this method call would look something like this:
Cursor mycursor = ...;
DBFunctions myFunctions = new DBFunctions();
myFunctions.checkExistence(mycursor);
Alternatively, if you would like to avoid creating an instance of DBFunctions
, you can add the static keyword to your method declaration, such as:
public static void checkExistence(Cursor check) {
String sql = "SELECT * FROM option WHERE id = 1";
check = db.rawQuery(sql, null);
}
You can then call the static method without a DBFunctions
instance:
DBFunctions.checkExistence(mycursor);
check
, it should work. You are probably getting a NullPointerException
after this method is called - Phil 2012-04-05 19:26