Search code examples
javaandroiddatabasesubclasssqliteopenhelper

Calling subclass method from other class - Android (java)


I have a working trivia game and am now trying to implement a highscores. I created a subclass DatabaseHelper class extending SQLiteOpenHelper. I am trying to call a method in the subclass DatabaseHelper from another class and am getting errors. The classes won't compile so there is no LogCat output. I have commented in the code the errors.

Code structure advice is appreciated as well!

Highscores.java

public class Highscores extends Activity {

    DatabaseHelper dh;
    SQLiteDatabase db;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        dh = new DatabaseHelper(context);
    }

    public class DatabaseHelper extends SQLiteOpenHelper { 

        public DatabaseHelper(Context context) { 
            //code
        }

        public boolean check(long score, int percentage) {
            //code
        }
    }
}

Results.java

public class Results extends Activity {

    DatabaseHelper dh;  //Error:  "DatabaseHelper cannot be resolved to a type."

    public void onCreate(Bundle savedInstanceState) {

        dh = new DatabaseHelper();  //Error:  "DatabaseHelper cannot be resolved to a type."
    }

    public void showResults() {

        if(dh.check(score, percentage) == true) {  //Error:  "DatabaseHelper cannot be resolved to a type."
      dh.insert(score, percentage);  //Error:  "DatabaseHelper cannot be resolved to a type."
        }
    }
}

Solution

  • Sounds like you are missing an import at the top of your Results.java

    It should look something like import com.somepackage.DatabaseHelper;

    Errors like this are typically either a typo in the class name or a missing import.