'problem with Context "getApplicationContext()' on a null object reference"
I made nonActivity class, and I use there other nonActivity Database class. When I call method from 1st class I have Error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Here is a fragment of my code of both classes:
DataBase.java
public DataBase(Context context) {
super(context, DATABASE_NAME, null, TABLE_VERSION);
}
and ObliczPodatki.java
public class ObliczPodatki extends Application
.
.
.
myDb = new DataBase(this.getApplicationContext());
and the full error message:
Process: com.example.nadgraniav01, PID: 11274
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:116)
at com.example.nadgraniav01.ObliczPodatki.obliczPodatki(ObliczPodatki.java:43)
at com.example.nadgraniav01.DodajNadgranieActivity$2.onClick(DodajNadgranieActivity.java:99)
at android.view.View.performClick(View.java:6669)
at android.view.View.performClickInternal(View.java:6638)
at android.view.View.access$3100(View.java:789)
at android.view.View$PerformClick.run(View.java:26145)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
if I use this instead of this.getApplicationContext() I am getting following erroe
Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
Solution 1:[1]
Try this then:
@Override
public void onCreate() {
super.onCreate()
SQLiteHandler db = new SQLiteHandler(getApplicationContext());
....rest of db calls..
}
Solution 2:[2]
Use:
myDb = new DataBase(getApplicationContext());
Or,
myDb = new DataBase(Activityname.this);
Solution 3:[3]
getApplicationContext is not the context that you should use,
Use this instead
myDb = new DataBase(this);
Solution 4:[4]
You have to initialise myDb variable in onCreate() method of ObliczPodatki class.
myDb = new DataBase(getApplicationContext());
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 | Payam Asefi |
| Solution 2 | Heisenberg |
| Solution 3 | Waesz |
| Solution 4 | DHAVAL A. |
