Android Studio Null 对象参考

Posted

技术标签:

【中文标题】Android Studio Null 对象参考【英文标题】:Android Studio Null object Reference 【发布时间】:2020-06-11 12:11:42 【问题描述】:

创建一个问答测试应用程序,根据您尝试正确的次数(即第一次尝试获得 5 分,第二次尝试获得 4 分……等等)对您进行评分

问题存储在资产文件夹中的 .DB 文件中,在测试评分逻辑后,我现在尝试从数据库中提取。

这是数据库打开器

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);
   

这是数据库访问器

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;
    

以及回答问题的主问题页面

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;
    

错误是

E/AndroidRuntime: 致命异常: main 进程:com.example.teambasedlearningapp,PID:7433 java.lang.RuntimeException:无法实例化活动 ComponentInfocom.example.teambasedlearningapp/com.example.teambasedlearningapp.GroupAnswering: java.lang.NullPointerException:尝试调用虚拟方法 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' 在一个空对象上 参考 在 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3268) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3488) 在 android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 在 android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 在 android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 在 android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049) 在 android.os.Handler.dispatchMessage(Handler.java:106) 在 android.os.Looper.loop(Looper.java:216) 在一个

所以我想问是什么导致了这个错误以及我该如何解决它

【问题讨论】:

你有什么问题? 我无法解决错误,是什么原因造成的,我该如何解决 【参考方案1】:

看起来你在构造函数中遇到了异常。

此代码在构造函数中调用 DB

String question22= questionGet();

尝试调试此方法或将其移至 onCreate。我认为在构造函数或 onCreate 中使用任何被阻止的请求是不好的做法

【讨论】:

【参考方案2】:

您可能很快就会调用questionGet() 方法。

String question22= questionGet(); // right here

通过这种方式,questionGet() 在上下文尚未创建时创建活动实例时被调用,这就是它在空对象引用上抛出“android.content.Context.getApplicationInfo()”的原因。因为上下文是空的,它是必需的:

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

尝试在创建时调用它,使用:

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

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

question22 = questionGet();


【讨论】:

以上是关于Android Studio Null 对象参考的主要内容,如果未能解决你的问题,请参考以下文章

Android studio关于界面跳转问题

如何在android studio中建立一个html文件

android studio edit text 输入完成后键盘如何退出

Android studio 中如何批量引入图片。一大堆图片!

Map返回Null或空Android Studio

安装失败,原因是:'null' - Android Studio 3.5