使用外部数据库在getApplicationContext上引用空对象

时间:2019-07-17 13:15:28

标签: java android database

使用外部数据库时遇到问题。 该数据库位于资产字典中。

我正在使用https://github.com/jgilfelt/android-sqlite-asset-helper打开数据库。

下面是Logcat

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.koziol.nukaang, PID: 2433
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.koziol.nukaang/com.example.koziol.nukaang.QuizActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3195)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3405)
        at android.app.ActivityThread.-wrap12(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994)
        at android.os.Handler.dispatchMessage(Handler.java:108)
        at android.os.Looper.loop(Looper.java:166)
        at android.app.ActivityThread.main(ActivityThread.java:7523)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
     Caused by: 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:109)
        at com.example.koziol.nukaang.QuizActivity.<init>(QuizActivity.java:23)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1178)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3185)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3405) 
        at android.app.ActivityThread.-wrap12(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1994) 
        at android.os.Handler.dispatchMessage(Handler.java:108) 
        at android.os.Looper.loop(Looper.java:166) 
        at android.app.ActivityThread.main(ActivityThread.java:7523) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 

        E/MemoryLeakMonitorManager: MemoryLeakMonitor.jar is not exist!
        E/Minikin: Could not get cmap table size!
下面的

是应用程序代码。 DbOpener.java

package com.example.koziol.nukaang;

import android.content.Context;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DbOpener extends SQLiteAssetHelper {

    private static final String DataBase_Name="EngDb.db";
    private static final int DataBase_Version = 5;

    public DbOpener(Context context){
        super(context,DataBase_Name,null,DataBase_Version);
    }
}

DbHelper.java

package com.example.koziol.nukaang;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import android.support.annotation.RequiresApi;
import com.example.koziol.nukaang.Contract.QuestionTable;
import java.util.ArrayList;
import java.util.List;
import static com.example.koziol.nukaang.Contract.QuestionTable.QUESTION;
public class DbHelper  {

    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase db;
    public List<Question> getQuestion;
    public String[] Flashcard;
    private static DbHelper instance;
    private Context ctx;

    public DbHelper(Context context) {
        this.openHelper=new DbOpener(context);
    }

    public static DbHelper getInstance(Context context){
        if(instance==null){
            instance=new DbHelper(context);
        }
        return instance;
    }

    public void open(){
        this.db=openHelper.getWritableDatabase();
    }

    public void close(){
        if(db!=null){
            this.db.close();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    public List<Question> getQuestion(){

        List<Question> QuestionList = new ArrayList<>();
        Cursor QuestionCursor = db.rawQuery("SELECT "+QuestionTable.ANSWER+", "+ QUESTION +" FROM "+ QuestionTable.TABLE_NAME + " ORDER BY RANDOM() LIMIT 10", null);

        if (QuestionCursor.moveToFirst()){
            do {
                Question question = new Question();
                question.setAnswer(QuestionCursor.getString((QuestionCursor.getColumnIndex(QuestionTable.ANSWER))));
                question.setQuestion(QuestionCursor.getString(QuestionCursor.getColumnIndex(QUESTION)));
                QuestionList.add(question);
            } while (QuestionCursor.moveToNext());
        }
    QuestionCursor.close();
    return QuestionList;
    }
}

QuizActivity.java

package com.example.koziol.nukaang;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import static com.example.koziol.nukaang.R.id.QuestionNr;
import static com.example.koziol.nukaang.R.id.QuizAnswer;
import static com.example.koziol.nukaang.R.id.QuizQuestion;

public class QuizActivity extends AppCompatActivity {

    TextView textViewQuestion;
    TextView textViewQuestionCount;
    EditText editTextAnswer;
    Button buttonConfirm;
    DbHelper dbHelper = DbHelper.getInstance(getApplicationContext());

    private List<Question> QuestionList;
    private int QuestionCount;
    private int QuestionNumber;
    private Question AskedQuestion;
    private boolean QuestionAnswer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz_activty);

        dbHelper.open();
        textViewQuestion = findViewById(QuizQuestion);
        textViewQuestionCount = findViewById(QuestionNr);
        editTextAnswer = findViewById(QuizAnswer);
        buttonConfirm = findViewById(R.id.Button_Confirm);

        DbHelper dbHelper = new DbHelper(this);
        QuestionList = dbHelper.getQuestion();
        QuestionNumber = QuestionList.size();

        NextQuestion();
    }

    private void CloseActivity() {
        Intent intent;
        intent = new Intent(QuizActivity.this, StartActivity.class);
        startActivity(intent);
        dbHelper.close();
    }

    private void NextQuestion(){
        int i=0;

            String TextAnswer = editTextAnswer.getText().toString();
            String ThisQuestion = QuestionList.get(i).toString();

            if (TextAnswer.equalsIgnoreCase(ThisQuestion) == true) {
                Toast.makeText(this, "Dobrze", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Źle", Toast.LENGTH_SHORT).show();
            }
            i++;
            if(i>=10)
            {
                CloseActivity();
            }
    }
}

数据库不为空,它具有近1000条记录。

当该值应该更高时,我曾经有一次将Database_version更改为1,如果可以的话,该如何解决?

1 个答案:

答案 0 :(得分:0)

您打电话给getApplicationContext()太早了。在线:

DbHelper dbHelper = DbHelper.getInstance(getApplicationContext());

您正在将其定义为类成员定义的一部分,这与在类构造函数中对其进行初始化相同。此时Activity Lifecycle尚未开始,因此尚未创建活动的Context。要解决此问题,请将dbHelper的初始化移至生命周期方法,例如onCreate()

DbHelper dbHelper;

...

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_quiz_activty);

    dbHelper = DbHelper.getInstance(getApplicationContext());
    dbHelper.open();


    ...
}