致命异常:main,尝试在Null对象引用上调用Virtual方法

时间:2017-10-30 07:56:00

标签: java android sqlite nullpointerexception

启动应用程序时出现问题。我遇到此问题,尝试在空对象引用上调用虚方法。我认为它因为我没有正确地创建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());

  }
}

LogCat

[ 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 

        ComponentInfo{com.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) {
        }
    }

db file

2 个答案:

答案 0 :(得分:2)

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

///创建db helper和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 = 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 的对象,因此它为空。

答案 1 :(得分:1)

初始化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());

   }
}