'Can't acces a public method from a public class outside the class in Android Studio
I'm building a SQlite database for a android quiz app. In Helper class I created a public method getAllQuestions(), but for some reason I can't access this method(or any other method in the helper class) in MainActivity. BTW I imported this class to Main but it doesn't help.
this is the code:
public class DB_Helper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "PRO_QUIZ";
public static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;
public ArrayList<QuestionsDataBase> getAllQuestions() {
ArrayList<QuestionsDataBase> questionsList = new ArrayList<>();
db = getReadableDatabase();
String Projection [] ={
QuestionTable._ID,
QuestionTable.Column_Question,
QuestionTable.Column_Option1,
QuestionTable.Column_Option2,
QuestionTable.Column_Option3,
QuestionTable.Column_Option4,
QuestionTable.Column_Correct_Ans
};
Cursor c = db.query(QuestionTable.Table_Name, Projection, null, null, null, null, null);
if (c.moveToFirst()) {
do {
QuestionsDataBase questions = new QuestionsDataBase();
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Question)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option1)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option2)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option3)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Option4)));
questions.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.Column_Correct_Ans)));
questionsList.add(questions);
} while (c.moveToNext());
}
c.close();
return questionsList;
}
However, when I type in Main: DB_Helper. I cant see any methods.
Solution 1:[1]
The method getAllQuestions() is not static. That means that you need an instance of DB_Helper to access that method (you get an instance of an object with the keyword new). So do this:
DB_Helper dbHelper = new DB_Helper();
dbHelper.getAllQuestions();
or alternatively you can declare the method as static this way:
public static ArrayList getAllQuestions(){
...
}
And then access it as you wanted in the first palce:
DB_Helper.getAllQuestions();
But beware that in this case (doing it static) you will also need to declare all class variables used in that method as static too:
private static SQLiteDatabase db;
Recommended further reading: Difference between Static methods and Instance methods
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
