致命异常: main ,尝试在空对象引用上调用虚拟方法 [重复]

Posted

技术标签:

【中文标题】致命异常: main ,尝试在空对象引用上调用虚拟方法 [重复]【英文标题】:Fatal Exception: main , Attempt to invoke Virtual method on a Null Object Reference [duplicate] 【发布时间】:2018-04-11 03:26:43 【问题描述】:

我在启动应用程序时遇到问题。我得到了这个问题,尝试在空对象引用上调用虚拟方法。我认为是因为我没有正确创建 LoadJobList 的实例,但我不完全确定。

主要活动 [已编辑]

公共类 MainActivity 扩展 AppCompatActivity

IntDataBaseHelper intDataBaseHelper;
ArrayAdapter<String> mAdapter;
ListView lstJob;


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

/// create instance of db helper and jobs

    IntDataBaseHelper myhelper = new IntDataBaseHelper(this);
    lstJob = (ListView)findViewById(R.id.lstJob);
    LoadJobList();

    //  Create the database (only if it doesn't exists)
    //  does so by copying from the assets
    if (CopyDBFromAssets.createDataBase(this,IntDataBaseHelper.DB_NAME)) 


        // Get the data from the database
        ArrayList<String> jobs = intDataBaseHelper.getJobList();
        for (String s : jobs) 
            Log.d("JobList", "Found Job " + s);
        
     else 
        throw new RuntimeException("No Usable Database exists or was copied from the assets.");
    



   // loads job to screen
    private void LoadJobList() 

       ArrayList<String> Joblist = intDataBaseHelper.getJobList();
       if (mAdapter == null) 
           mAdapter = new ArrayAdapter<String>(this,R.layout.header,R.id.header);
           mAdapter = new ArrayAdapter<>(this,R.layout.row,R.id.BtnComplete);
           mAdapter = new ArrayAdapter<>(this, R.layout.row, R.id.Job_name,Joblist);

           lstJob.setAdapter(mAdapter);
        else 
           mAdapter.clear();
           mAdapter.addAll(Joblist);
           mAdapter.notifyDataSetChanged();
       
   


   public void JobComplete(View view)
   View parent = (View)view.getParent();
   TextView taskTextView=(TextView)parent.findViewById(R.id.BtnComplete);
   Log.e("String",(String) taskTextView.getText());

  

日志猫

[ 10-30 07:24:10.779  1506: 1551 D/]
HostConnection::get() New Host Connection established 0x949247c0, tid 1551
    10-30 07:24:11.120 2774-2774/? E/androidRuntime: FATAL EXCEPTION: main
                                                     Process: com.example.joelg.clapp, PID: 2774
                                                     java.lang.RuntimeException: Unable to start activity 

        ComponentInfocom.example.joelg.clapp/com.example.joelg.clapp.MainActivity: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.joelg.clapp.IntDataBaseHelper.getJobList()' on a null object reference
                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                             at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                             at android.os.Handler.dispatchMessage(Handler.java:105)
                                                             at android.os.Looper.loop(Looper.java:164)
                                                             at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                             at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.example.joelg.clapp.IntDataBaseHelper.getJobList()' on a null object reference
                                                             at com.example.joelg.clapp.MainActivity.LoadJobList(MainActivity.java:52)
                                                             at com.example.joelg.clapp.MainActivity.onCreate(MainActivity.java:31)
                                                             at android.app.Activity.performCreate(Activity.java:6975)
                                                             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
                                                             at android.app.ActivityThread.-wrap11(Unknown Source:0) 
                                                             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
                                                             at android.os.Handler.dispatchMessage(Handler.java:105) 
                                                             at android.os.Looper.loop(Looper.java:164) 
                                                             at android.app.ActivityThread.main(ActivityThread.java:6541) 
                                                             at java.lang.reflect.Method.invoke(Native Method) 
                                                             at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 

getJobList 方法

  public  ArrayList<String> getJobList() 
        ArrayList<String> JobList = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor =  db.query(DB_TABLE,new String[]
                DB_COLUMN,null,null,null,null,null);
        while(cursor.moveToNext())
            int index = cursor.getColumnIndex(DB_COLUMN);
            JobList.add(cursor.getString(index));
        

        cursor.close();
        db.close();
        return JobList;
    

数据库助手类

package com.example.joelg.clapp;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

/**
 * Created by joelg on 22/10/2017.
 */
public class IntDataBaseHelper extends SQLiteOpenHelper


        public static  String DB_PATH ="//data/data/com.example.joelg.clapp/databases";
        public static final String DB_NAME = "JobList";
        private static final String DB_COLUMN = "jobNM";
        private static final String DB_TABLE = "job";
        public static final String DB_JOB_DETAILS = "jobDetails";
        private static final String DB_ISDONE = "jobIsDone";
        private SQLiteDatabase JobListDatabase;
        private final Context jobContext;


        /**
         * constructor t
         */
        public IntDataBaseHelper (Context context) 

            super (context, DB_NAME,null, 1);
            this.jobContext = context;
            DB_PATH = jobContext.getDatabasePath(DB_NAME).getPath();
        


        public void openDataBase() 
            // open the database
            String JobListPath = DB_PATH;
            JobListDatabase = SQLiteDatabase.openDatabase(
                    JobListPath,null,SQLiteDatabase.OPEN_READONLY);
        

        // Getting Job Count
        public  ArrayList<String> getJobList() 
            ArrayList<String> JobList = new ArrayList<>();
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor =  db.query(DB_TABLE,new String[]
                    DB_COLUMN,null,null,null,null,null);
            while(cursor.moveToNext())
                int index = cursor.getColumnIndex(DB_COLUMN);
                JobList.add(cursor.getString(index));
            

            cursor.close();
            db.close();
            return JobList;
        


        // Gets the job state if it has been competed or not
        public ArrayList<String> getIsDone() 
            ArrayList<String>  IsDone = new ArrayList<>();
            SQLiteDatabase db = this.getReadableDatabase();
            Cursor cursor = db.query(DB_TABLE,new String[]DB_ISDONE,null,null,null,null,null);
               while(cursor.moveToFirst())
                   int index = cursor.getColumnIndex(DB_ISDONE);
                   IsDone.add(cursor.getString(index));
               

               cursor.close();
               db.close();
               return IsDone;
         




        @Override
        public synchronized void close()

            if(JobListDatabase !=null)
                JobListDatabase.close();

                super.close();
            
        
        @Override
        public  void onCreate(SQLiteDatabase db) 

        
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
        
    

【问题讨论】:

名为intDataBaseHelper的对象从未初始化,所以它是null 【参考方案1】:
public class MainActivity extends AppCompatActivity 

IntDataBaseHelper intDataBaseHelper;
ArrayAdapter<String> mAdapter;
ListView lstJob;


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

/// 创建数据库助手和作业的实例

    intDataBaseHelper = new IntDataBaseHelper(this);
    lstJob = (ListView)findViewById(R.id.lstJob);
    LoadJobList();

    //  Create the database (only if it doesn't exists)
    //  does so by copying from the assets
    if (CopyDBFromAssets.createDataBase(this,IntDataBaseHelper.DB_NAME)) 


        // Get the data from the database
        ArrayList<String> jobs = myhelper.getJobList();
        for (String s : jobs) 
            Log.d("JobList", "Found Job " + s);
        
     else 
        throw new RuntimeException("No Usable Database exists or was copied from the assets.");
    



   // loads job to screen
    private void LoadJobList() 

       ArrayList<String> Joblist = intDataBaseHelper.getJobList();
       if (mAdapter == null) 
           mAdapter = new ArrayAdapter<String>(this,R.layout.header,R.id.header);
           mAdapter = new ArrayAdapter<>(this,R.layout.row,R.id.BtnComplete);
           mAdapter = new ArrayAdapter<>(this, R.layout.row, R.id.Job_name,Joblist);

           lstJob.setAdapter(mAdapter);
        else 
           mAdapter.clear();
           mAdapter.addAll(Joblist);
           mAdapter.notifyDataSetChanged();
       
   


   public void JobComplete(View view)
   View parent = (View)view.getParent();
   TextView taskTextView=(TextView)parent.findViewById(R.id.BtnComplete);
   Log.e("String",(String) taskTextView.getText());

名为 intDataBaseHelper 的对象从未初始化,因此为 null。

【讨论】:

这不是什么“intDataBaseHelper = new IntDataBaseHelper(this);”有吗? 它初始化了 databaseHelper 因为 ArrayList Joblist = intDataBaseHelper.getJobList();在这一行,您调用尚未初始化的数据库函数。 好的,所以我将行更改为“ intDataBaseHelper = new IntDataBaseHelper(this); ”,现在抛出“android.database.sqlite.SQLiteException: no such table: job (code 1):” any想法? 我接受了他的回复,它解决了第一个问题,但它导致了这个问题。这几天我不能再问任何问题了,因为我显然问得太多了 此问题可能与您尝试访问的数据库中不存在该表的数据库有关。发布 getJobList() 方法的代码。【参考方案2】:

初始化intDataBaseHelper并使用它,如下所示

所以方法将是 .

public class MainActivity extends AppCompatActivity 

    IntDataBaseHelper intDataBaseHelper;
    ArrayAdapter<String> mAdapter;
    ListView lstJob;


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

/// create instance of db helper and jobs

        intDataBaseHelper = new IntDataBaseHelper(this);
        lstJob = (ListView)findViewById(R.id.lstJob);
        LoadJobList();

        //  Create the database (only if it doesn't exists)
        //  does so by copying from the assets
        if (CopyDBFromAssets.createDataBase(this,IntDataBaseHelper.DB_NAME)) 


            // Get the data from the database
            ArrayList<String> jobs = intDataBaseHelper.getJobList();
            for (String s : jobs) 
                Log.d("JobList", "Found Job " + s);
            
         else 
            throw new RuntimeException("No Usable Database exists or was copied from the assets.");
        
    


       // loads job to screen
        private void LoadJobList() 

           ArrayList<String> Joblist = intDataBaseHelper.getJobList();
           if (mAdapter == null) 
               mAdapter = new ArrayAdapter<String>(this,R.layout.header,R.id.header);
               mAdapter = new ArrayAdapter<>(this,R.layout.row,R.id.BtnComplete);
               mAdapter = new ArrayAdapter<>(this, R.layout.row, R.id.Job_name,Joblist);

               lstJob.setAdapter(mAdapter);
            else 
               mAdapter.clear();
               mAdapter.addAll(Joblist);
               mAdapter.notifyDataSetChanged();
           
       


       public void JobComplete(View view)
       View parent = (View)view.getParent();
       TextView taskTextView=(TextView)parent.findViewById(R.id.BtnComplete);
       Log.e("String",(String) taskTextView.getText());

   

【讨论】:

这会抛出无法解析符号“myhelper” @JoelGeri 检查编辑 我已经编辑了我的帖子以显示您的更改,但我仍然遇到同样的错误 @JoelGeri,你做得不对。还有 IntDataBaseHelper myhelper = new IntDataBaseHelper(this); ,应该是 intDataBaseHelper = new IntDataBaseHelper(this);和 谢谢

以上是关于致命异常: main ,尝试在空对象引用上调用虚拟方法 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

从 AsyncTask 更新视图

尝试在空对象引用上调用虚拟方法 com.google.firebase.iid.FirebaseInstanceId.getInstanceId()'

NullPointerException 错误尝试在空对象引用上调用虚拟方法错误

回收站视图 - 在空对象引用上

Android错误尝试在空对象引用上调用虚拟方法[重复]

AsyncTask +数据库尝试在空对象引用上调用虚拟方法[重复]