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

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

这是我的两个类的代码片段:

数据库

 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代替this.getApplicationContext()我正在追随错误

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

最佳答案

然后尝试以下方法:

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

10-07 19:41
查看更多