0

Created java class DBOperations i android project to realize database operations but found that some operations need Context object. Couldn't get it with this or getapplicationcontext method. I decided to pass context object as a paramether,e.g.

Mymdhod(this);

Is it correct way or there are other methods to get application context?

Ilqar Rasulov
  • 169
  • 1
  • 2
  • 10

3 Answers3

0

Yeah, if you need the context in your own classes, the best way is to pass it in like you are doing.

Buddy
  • 10,874
  • 5
  • 41
  • 58
0

Using parameters of the method calls , you can pass the context of activity and use them in another classes. For instance: Obj.methodName(context)

And method

  public methodName(Context context){
 // do something with context

 }
0

If all things you need the context for can be done in the constructor, consider passing the context as a parameter to the constructor and immediately initialize everything you need the context for.

Otherwise, if you need the context in a public method, pass the context as a parameter to this method.

What you shouldn't be doing is keeping a reference to the context as a member variable. The reference you are holding might be invalidated upon traversal through the activity lifecycle and holding the reference might cause memory leaks as further described in this article.

marktani
  • 7,578
  • 6
  • 37
  • 60