-3

I'm getting a problem when I launch my App. I get this issue, Attempt to invoke a virtual method on a null object reference. I think its Because I didn't create the instance of LoadJobList Correctly but I'm not entirely sure.

Main Activity [EDITED]

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 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 method

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

DB helper class

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

Joel Geri
  • 47
  • 9

2 Answers2

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

/// 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 = 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());

} }

The object called intDataBaseHelper is never initialized, so it is null.

Sardar Khan
  • 729
  • 6
  • 16
  • isnt that what "intDataBaseHelper = new IntDataBaseHelper(this);" does ? – Joel Geri Oct 30 '17 at 08:11
  • it initialized the databaseHelper because ArrayList Joblist = intDataBaseHelper.getJobList(); at this line you call database function that is not initialized yet. – Sardar Khan Oct 30 '17 at 10:00
  • ok so i changed the line to " intDataBaseHelper = new IntDataBaseHelper(this); " and its now throwing "android.database.sqlite.SQLiteException: no such table: job (code 1):" any ideas ? – Joel Geri Oct 30 '17 at 10:29
  • i accepted his response it solved the first issue but it caused this one . and i cant ask any more questions for a few days because I have apparently asked too many – Joel Geri Oct 30 '17 at 10:32
  • this issue might be with the database that table not exist in database that you are trying to access.post the code for getJobList() method. – Sardar Khan Oct 30 '17 at 10:35
  • ok cool so i just added the getjoblist method – Joel Geri Oct 30 '17 at 10:40
  • i mean i added the getjoblist code to my post – Joel Geri Oct 30 '17 at 10:58
  • my bad i readded it – Joel Geri Oct 30 '17 at 11:06
  • ok i added the db handler – Joel Geri Oct 31 '17 at 06:12
  • check the database file that if there is a table with name "job" exists or not. – Sardar Khan Oct 31 '17 at 06:32
  • ok i think i fixed that it wasnt finding the DB file so that's, why it was throwing that only problem now, is im getting " java.lang.OutOfMemoryError: Failed to allocate a 83070912 byte allocation with 6291456 free bytes and 13MB until OOM, max allowed footprint 394558944, growth limit 402653184" – Joel Geri Oct 31 '17 at 06:54
  • add large heap true in manifest in application tag..see this post..https://stackoverflow.com/questions/32244851/androidjava-lang-outofmemoryerror-failed-to-allocate-a-23970828-byte-allocatio – Sardar Khan Oct 31 '17 at 06:58
  • it seems its not closing the db and it just fills up and crashes so that didnt help – Joel Geri Oct 31 '17 at 07:23
  • yes it might be this issue.There are two approaches you can open and close the database for every operation. Or you can open the database and wehen going to next activity close the database. – Sardar Khan Oct 31 '17 at 07:47
  • but at the end of both getJobList and GetIs done it does db.close(); so shouldn't that be closing it? – Joel Geri Oct 31 '17 at 07:51
  • yes its closing the db. – Sardar Khan Oct 31 '17 at 07:52
  • then why would it be crashing ?? – Joel Geri Oct 31 '17 at 07:52
  • yeah i did but it the app just creates a bunch of garbage then crashes – Joel Geri Oct 31 '17 at 08:00
  • paste the whole logcat exception .. – Sardar Khan Oct 31 '17 at 08:01
  • i removed the app to try and clear out all the data and now it cant even find the db file .. back to square 1 – Joel Geri Oct 31 '17 at 08:03
  • what error it was throwing..?? change the databaseversion from 1 to 2 in super (context, DB_NAME,null, 1); and also check that you have open the database or not.. – Sardar Khan Oct 31 '17 at 08:10
  • why are you trying to read the pre-built database..? you can create the database using android standard and then insert data into the database and then read the database.. – Sardar Khan Oct 31 '17 at 08:12
  • " E/SQLiteLog: (1) no such table: job 10-31 08:16:18.736 28857-28857/com.example.joelg.clapp D/AndroidRuntime: Shutting down VM 10-31 08:16:18.739 28857-28857/com.example.joelg.clapp E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.joelg.clapp, PID: 28857 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.joelg.clapp/com.example.joelg.clapp.MainActivity}: android.database.sqlite.SQLite" – Joel Geri Oct 31 '17 at 08:17
  • i want to use a preloaded db file as a template file – Joel Geri Oct 31 '17 at 08:17
  • is there is any data in this db file.? – Sardar Khan Oct 31 '17 at 08:18
  • can you share the database file .? – Sardar Khan Oct 31 '17 at 08:19
  • this exception shows that there is no such table with name job..same as previous. – Sardar Khan Oct 31 '17 at 08:20
  • i added a picture of the db file – Joel Geri Oct 31 '17 at 08:24
  • why not use the standard database structure ..? using pre-built database is not good.have a look at this link..https://developer.android.com/training/basics/data-storage/databases.html – Sardar Khan Oct 31 '17 at 09:44
  • why is it not good ? i want to use it as a templated file witch means i still need to have another place to get the information from or i need to download it witch i don't want the app to do apart from on major updates – Joel Geri Oct 31 '17 at 09:49
  • because this approach is not used by google developers.and not appreciated by them. – Sardar Khan Oct 31 '17 at 09:50
  • what ? in an ideal situation that would be good but i dont want to do that . also google developers have no involvement in this project and just because the download on the fly doesn't mean i have to – Joel Geri Oct 31 '17 at 09:55
  • ok.as you wish. – Sardar Khan Oct 31 '17 at 10:31
  • i have also faced some serious issue after using this approach. now i am using standard approach. – Sardar Khan Oct 31 '17 at 10:53
1

Initialize intDataBaseHelper and use it , like following

So the method will be .

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

   }
}
Mithun Sarker Shuvro
  • 3,479
  • 6
  • 28
  • 54