0

I have a JSONParser class where I have this:

Database db = new Database(/* Need context here! */);

In the Database class I have this:

public Database(Context context) {
    super(context, DATABASE_NAME, null, 1);
    SQLiteDatabase db = this.getWritableDatabase();
}

How am I supposed to give a context in the Database constructor?

Thanks for any help...

Laklam
  • 19
  • 3
  • 1
    Unfortunately, the shortest answer is that you shouldn’t do that. You should have the Json parser pass the parsed object back to your Activity or Service, and then use the Context available there – Ben P. Sep 21 '18 at 22:48
  • You may use ApplicationContext. Show this answer https://stackoverflow.com/questions/2002288/static-way-to-get-context-in-android – Ivan Sep 21 '18 at 22:49
  • But how am I supposed to pass anything to my Database class if I cant call any method from Database because I have no "new"? Should I make the method static and then Database.setData("VALUES")? – Laklam Sep 21 '18 at 22:50

1 Answers1

0

Have your JSONParser class constructor take a Context parameter. In the activity/fragment where you instantiate the JSONParser, pass the context. Pass this context to the Database class. This is the clean way of doing it. You could also use the application context like @Ivan commented.

nupadhyaya
  • 1,909
  • 1
  • 14
  • 14