上下文“空对象引用上的getApplicationContext()”的问题

时间:2019-06-16 17:37:58

标签: java android

我制作了nonActivity类,并在那里使用了其他nonActivity数据库类。当我从第一类调用方法时,出现错误

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

这是我这两个类的代码的一部分:

DataBase.java

 public DataBase(Context context) {
        super(context, DATABASE_NAME, null, TABLE_VERSION);
   }

和ObliczPodatki.java

public class ObliczPodatki extends Application
.
.
.
myDb = new DataBase(this.getApplicationContext());

和完整的错误消息:

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)

如果我使用它而不是this.getApplicationContext(),我将追随错误

Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference 

4 个答案:

答案 0 :(得分:0)

然后尝试:

 @Override 
 public void onCreate() {
  super.onCreate() 
  SQLiteHandler db = new SQLiteHandler(getApplicationContext());
  ....rest of db calls..
}

答案 1 :(得分:0)

使用:

 myDb = new DataBase(getApplicationContext());

或者

 myDb = new DataBase(Activityname.this);

答案 2 :(得分:0)

getApplicationContext不是您应该使用的上下文,

改为使用

myDb = new DataBase(this);

答案 3 :(得分:0)

您必须在myDb类的onCreate()方法中初始化ObliczPodatki变量。

   myDb = new DataBase(getApplicationContext());