简体   繁体   中英

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)

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.

this is the 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 oper.loop(Looper.java:216) at an

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.

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.' 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

String question22= questionGet();

Try to debug this method or move it to onCreate. My opinion is bad practice to use any blocked requests in constructors or in onCreate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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