简体   繁体   English

Android Studio 空对象参考

[英]Android Studio Null object Reference

Creating an question/answer test application that scores you based on how many attempts it took to get it right (ie on the first attempt 5 points, 2nd attempt 4 points... and so on)创建一个问答测试应用程序,根据正确尝试的次数为您评分(即第一次尝试 5 分,第二次尝试 4 分......等等)

the questions are stored in a .DB file in asset folder and after testing the scoring logic I'm now trying to draw from the database.问题存储在资产文件夹中的 .DB 文件中,在测试评分逻辑后,我现在试图从数据库中提取。

this is the DatabaseOpener这是 DatabaseOpener

package com.example.teambasedlearningapp;

import android.content.Context;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DatabaseOpenHelper extends SQLiteAssetHelper {
  private static final String DATABASE_NAME = "TBLData.db";
  private static final int DATABASE_VERSION = 1;

public DatabaseOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
   }
}

this is the DatabaseAccessor这是数据库访问器

package com.example.teambasedlearningapp;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class DatabaseAccess {
    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    private static DatabaseAccess instance;

    /**
     *      * Private constructor to aboid object creation from outside classes.
     *      *
     *      * @param context
     *      
     */
    public DatabaseAccess(Context context) {
        this.openHelper = new DatabaseOpenHelper(context);
    }

    /**
     *      * Return a singleton instance of DatabaseAccess.
     *      *
     *      * @param context the Context
     *      * @return the instance of DabaseAccess
     *      
     */
    public static DatabaseAccess getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseAccess(context);
        }
        return instance;
    }

    /**
     *      * Open the database connection.
     *      
     */
    public void open() {
        this.database = openHelper.getWritableDatabase();
    }

    /**
     *      * Close the database connection.
     *      
     */
    public void close() {
        if (database != null) {
            this.database.close();
        }
    }

    /**
     *      * Read all modules from the database.
     *      *
     *      * @return a List of modules
     *      
     */
    public ArrayList<String> getModules() {
        ArrayList<String> list = new ArrayList<>();
        Cursor cursor = database.rawQuery("SELECT moduleName FROM Module", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            list.add(cursor.getString(0));
            cursor.moveToNext();
        }
        cursor.close();
        return list;
    }

    public ArrayList<String> getQuestions() {
        ArrayList<String> list = new ArrayList<>();
        Cursor cursor = database.rawQuery("SELECT question FROM Question ", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            list.add(cursor.getString(0));
            cursor.moveToNext();
        }
        cursor.close();
        return list;
    }
}

and the main question page that answers the question以及回答问题的主要问题页面

package com.example.teambasedlearningapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.*;

public class GroupAnswering extends AppCompatActivity implements View.OnClickListener{
    private TextView question;
    private TextView message;
    private Button option1;
    private Button option2;
    private Button option3;
    private Button option4;
    private Button next;
    static ArrayList<String> questions2 = new ArrayList<String>();
    static int overall = 0;
    String answer = "Red";
    int grade = 4;
    String question22= questionGet();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_answering);

        question = (TextView) findViewById(R.id.question);
        message = (TextView) findViewById(R.id.message);
        option1 = (Button) findViewById(R.id.option1);
        option2 = (Button) findViewById(R.id.option2);
        option3 = (Button) findViewById(R.id.option3);
        option4 = (Button) findViewById(R.id.option4);
        next = (Button) findViewById(R.id.next);

        option1.setOnClickListener(this);
        option2.setOnClickListener(this);
        option3.setOnClickListener(this);
        option4.setOnClickListener(this);
        next.setOnClickListener(this);

        questions2.add(question2);

        question.setText(questions22.get(0));
        next.setVisibility(View.GONE);
    }
    public void onClick(View v){

        if (v.getId() == option1.getId()) {
            int gradef = Score(grade,"Red",answer);
        }
        else if (v.getId() == option2.getId()) {
            int gradef = Score(grade,"Blue",answer);
        }
        else if (v.getId() == option3.getId()) {
            int gradef = Score(grade,"Black",answer);
        }
        else if (v.getId() == option4.getId()) {
            int gradef = Score(grade,"White",answer);
        }
        else if (v.getId() == next.getId()) {
            openActivity2();
        }
    }
    public int Score (int score, String choice, String answer){
        int finalScore = score;

        if(grade == 0){
            overall=+grade;
            message.setText("Your score is: "+grade+" move on to the next question");
            option1.setVisibility(View.GONE);
            option2.setVisibility(View.GONE);
            option3.setVisibility(View.GONE);
            option4.setVisibility(View.GONE);
            next.setVisibility(View.VISIBLE);
            next.setText("Next Question");
        }
        else if( choice.equals(answer)) {
            finalScore=-0;
            overall=+grade;
            message.setText("Your score is: "+grade+" move on to the next question");
            option4.setVisibility(View.GONE);
            option2.setVisibility(View.GONE);
            option3.setVisibility(View.GONE);
            next.setVisibility(View.VISIBLE);
            next.setText("Next Question");
        }
        else {
            finalScore=-1;
            grade--;
            message.setText("Your score is: "+grade);
        }

        return finalScore;
    }
    public void openActivity2() {
        Intent intent = new Intent(this, GroupAnswering.class);
        startActivity(intent);
    }
    public String questionGet(){
        DatabaseAccess newDB = new DatabaseAccess(this);
        newDB.open();
        ArrayList<String> questionsArray = newDB.getQuestions();
        newDB.close();
        String question2 = questionsArray.get(0);
        return question2;
    }
}

error being错误是

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.teambasedlearningapp, PID: 7433 java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.teambasedlearningapp/com.example.teambasedlearningapp.GroupAnswering}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3268) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3488) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Lo E/AndroidRuntime:致命异常:主进程:com.example.teambasedlearningapp,PID:7433 java.lang.RuntimeException:无法实例化活动 ComponentInfo{com.example.teambasedlearningapp/com.example.teambasedlearningapp.GroupAnswering}:java.lang。 NullPointerException:尝试在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3268) 的空对象引用上调用虚拟方法“android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()”。 ActivityThread.handleLaunchActivity(ActivityThread.java:3488) at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) at android.app.servertransaction .TransactionExecutor.execute(TransactionExecutor.java:95) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Lo oper.loop(Looper.java:216) at an oper.loop(Looper.java:216) 在

So I am asking what is causing this error and how do I solve it所以我问是什么导致了这个错误,我该如何解决它

It might seen you are calling questionGet() method to soon.它可能会看到您很快就会调用questionGet()方法。

String question22= questionGet(); // right here

On this way questionGet() is called when an instance of the activity is created when the context is not created yet that's why it throws 'android.content.Context.getApplicationInfo() on a null object reference.'通过这种方式,在尚未创建上下文的情况下创建活动的实例时,会调用questionGet() ,这就是它在空对象引用上抛出“android.content.Context.getApplicationInfo()”的原因。 because the context is null and it is required in:因为上下文为空并且在以下情况下是必需的:

DatabaseAccess newDB = new DatabaseAccess(this); // in questionGet() method

Try calling this on creation, with:尝试在创建时调用它,使用:

@override
onCreate(){ //in this point context isn't null

...//your ui references
...//your preview logic

question22 = questionGet();

}

It looks that you got exception in constructor.看起来你在构造函数中遇到了异常。

This code calls DB in constructor此代码在构造函数中调用 DB

String question22= questionGet();

Try to debug this method or move it to onCreate.尝试调试此方法或将其移至 onCreate。 My opinion is bad practice to use any blocked requests in constructors or in onCreate我认为在构造函数或 onCreate 中使用任何被阻止的请求是不好的做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM