1. Download our Official Android App: Forums for Android!

Apps NullPointerException when using database object

Discussion in 'Android Development' started by Julius_J, Jun 11, 2016.

  1. Julius_J

    Julius_J Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    3
    Joined:
    Jun 11, 2016

    Jun 11, 2016
    3
    0
    5
    Male
    I'm new to Android, and i've got some issues. It looks like it's saying that's having an null object passed to it, but I'm not sure. Where I missed a step? Any help is appreciated.

    Thanks in advance.

    Logcat:
    Code (Java):
    1. 06-11 14:58:37.786 7537-7537/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
    2. Process: com.androidtutorialpoint.employeemanagementsystem, PID: 7537
    3. java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
    4. at com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.getEmployee(EmployeeOperations.java:63)
    5. at com.androidtutorialpoint.employeemanagementsystem.MainActivity$6.onClick(MainActivity.java:135)
    6. at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
    7. at android.os.Handler.dispatchMessage(Handler.java:102)
    8. at android.os.Looper.loop(Looper.java:135)
    9. at android.app.ActivityThread.main(ActivityThread.java:5294)
    10. at java.lang.reflect.Method.invoke(Native Method)
    11. at java.lang.reflect.Method.invoke(Method.java:372)
    12. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    13. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
    EmployeeOperations:
    Code (Java):
    1.  
    2. package com.androidtutorialpoint.employeemanagementsystem.DB;
    3.  
    4. import android.content.ContentValues;
    5. import android.content.Context;
    6. import android.database.Cursor;
    7. import android.database.sqlite.SQLiteDatabase;
    8. import android.database.sqlite.SQLiteOpenHelper;
    9. import android.util.Log;
    10.  
    11.  
    12. import com.androidtutorialpoint.employeemanagementsystem.Model.Employee;
    13. import java.util.ArrayList;
    14. import java.util.List;
    15.  
    16.  
    17. public class EmployeeOperations {
    18.     public static final String LOGTAG = "EMP_MNGMNT_SYS";
    19.  
    20.     SQLiteOpenHelper dbhandler;
    21.     SQLiteDatabase database;
    22.  
    23.     private static final String[] allColumns = {
    24.             EmployeeDBHandler.COLUMN_ID,
    25.             EmployeeDBHandler.COLUMN_FIRST_NAME,
    26.             EmployeeDBHandler.COLUMN_LAST_NAME,
    27.             EmployeeDBHandler.COLUMN_GENDER,
    28.             EmployeeDBHandler.COLUMN_HIRE_DATE,
    29.             EmployeeDBHandler.COLUMN_DEPT
    30.  
    31.     };
    32.  
    33.     public EmployeeOperations(Context context){
    34.         dbhandler = new EmployeeDBHandler(context);
    35.     }
    36.  
    37.     public void open(){
    38.         Log.i(LOGTAG,"Database Opened");
    39.         database = dbhandler.getWritableDatabase();
    40.  
    41.  
    42.     }
    43.     public void close(){
    44.         Log.i(LOGTAG, "Database Closed");
    45.         dbhandler.close();
    46.  
    47.     }
    48.     public Employee addEmployee(Employee Employee){
    49.         ContentValues values  = new ContentValues();
    50.         values.put(EmployeeDBHandler.COLUMN_FIRST_NAME,Employee.getFirstname());
    51.         values.put(EmployeeDBHandler.COLUMN_LAST_NAME,Employee.getLastname());
    52.         values.put(EmployeeDBHandler.COLUMN_GENDER, Employee.getGender());
    53.         values.put(EmployeeDBHandler.COLUMN_HIRE_DATE, Employee.getHiredate());
    54.         values.put(EmployeeDBHandler.COLUMN_DEPT, Employee.getDept());
    55.         long insertid = database.insert(EmployeeDBHandler.TABLE_EMPLOYEES,null,values);
    56.         Employee.setEmpId(insertid);
    57.         return Employee;
    58.  
    59.     }
    60.  
    61.     // Getting single Employee
    62.     public Employee getEmployee(long id) {
    63.  
    64.         Cursor cursor = database.query(EmployeeDBHandler.TABLE_EMPLOYEES,allColumns,EmployeeDBHandler.COLUMN_ID + "=?",new String[]{String.valueOf(id)},null,null, null, null);
    65.         if (cursor != null)
    66.             cursor.moveToFirst();
    67.  
    68.         Employee e = new Employee(Long.parseLong(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5));
    69.         // return Employee
    70.         return e;
    71.     }
    72.  
    73.     public List<Employee> getAllEmployees() {
    74.  
    75.         Cursor cursor = database.query(EmployeeDBHandler.TABLE_EMPLOYEES,allColumns,null,null,null, null, null);
    76.  
    77.             List<Employee> employees = new ArrayList<>();
    78.         if(cursor.getCount() > 0){
    79.             while(cursor.moveToNext()){
    80.                 Employee employee = new Employee();
    81.                 employee.setEmpId(cursor.getLong(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_ID)));
    82.                 employee.setFirstname(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_FIRST_NAME)));
    83.                 employee.setLastname(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_LAST_NAME)));
    84.                 employee.setGender(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_GENDER)));
    85.                 employee.setHiredate(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_HIRE_DATE)));
    86.                 employee.setDept(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_DEPT)));
    87.                 employees.add(employee);
    88.             }
    89.         }
    90.         // return All Employees
    91.         return employees;
    92.     }
    93.  
    94.  
    95.  
    96.  
    97.     // Updating Employee
    98.     public int updateEmployee(Employee employee) {
    99.  
    100.         ContentValues values = new ContentValues();
    101.         values.put(EmployeeDBHandler.COLUMN_FIRST_NAME, employee.getFirstname());
    102.         values.put(EmployeeDBHandler.COLUMN_LAST_NAME, employee.getLastname());
    103.         values.put(EmployeeDBHandler.COLUMN_GENDER, employee.getGender());
    104.         values.put(EmployeeDBHandler.COLUMN_HIRE_DATE, employee.getHiredate());
    105.         values.put(EmployeeDBHandler.COLUMN_DEPT, employee.getDept());
    106.  
    107.         // updating row
    108.         return database.update(EmployeeDBHandler.TABLE_EMPLOYEES, values,
    109.                 EmployeeDBHandler.COLUMN_ID + "=?",new String[] { String.valueOf(employee.getEmpId())});
    110.     }
    111.  
    112.     // Deleting Employee
    113.     public void removeEmployee(Employee employee) {
    114.  
    115.         database.delete(EmployeeDBHandler.TABLE_EMPLOYEES, EmployeeDBHandler.COLUMN_ID + "=" + employee.getEmpId(), null);
    116.     }
    117.  
    118.  
    119.  
    120. }
    121.  
    MainActivity:
    Code (Java):
    1. public class MainActivity extends AppCompatActivity{
    2.  
    3.     private Button addEmployeeButton;
    4.     private Button editEmployeeButton;
    5.     private Button deleteEmployeeButton;
    6.     private Button viewAllEmployeeButton;
    7.     private EmployeeOperations employeeOps;
    8.     private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId";
    9.     private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update";
    10.     @Override
    11.     protected void onCreate(Bundle savedInstanceState) {
    12.         employeeOps = new EmployeeOperations(MainActivity.this);
    13.         super.onCreate(savedInstanceState);
    14.  
    15.         setContentView(R.layout.activity_main);
    16.         addEmployeeButton = (Button) findViewById(R.id.button_add_employee);
    17.         editEmployeeButton = (Button) findViewById(R.id.button_edit_employee);
    18.         deleteEmployeeButton = (Button) findViewById(R.id.button_delete_employee);
    19.         viewAllEmployeeButton = (Button)findViewById(R.id.button_view_employees);
    20.  
    21.  
    22.  
    23.         addEmployeeButton.setOnClickListener(new View.OnClickListener() {
    24.             @Override
    25.             public void onClick(View v) {
    26.                 Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
    27.                 i.putExtra(EXTRA_ADD_UPDATE, "Add");
    28.                 startActivity(i);
    29.             }
    30.         });
    31.         editEmployeeButton.setOnClickListener(new View.OnClickListener() {
    32.             @Override
    33.             public void onClick(View v) {
    34.                 getEmpIdAndUpdateEmp();
    35.             }
    36.         });
    37.         deleteEmployeeButton.setOnClickListener(new View.OnClickListener() {
    38.             @Override
    39.             public void onClick(View v) {
    40.                 getEmpIdAndRemoveEmp();
    41.             }
    42.         });
    43.         viewAllEmployeeButton.setOnClickListener(new View.OnClickListener() {
    44.             @Override
    45.             public void onClick(View v) {
    46.                 Intent i = new Intent(MainActivity.this, ViewAllEmployees.class);
    47.                 startActivity(i);
    48.             }
    49.         });
    50.  
    51.     }
    52.  
    53.  
    54.     @Override
    55.     public boolean onCreateOptionsMenu(Menu menu) {
    56.         getMenuInflater().inflate(R.menu.employee_menu, menu);
    57.         return true;
    58.     }
    59.  
    60.     @Override
    61.     public boolean onOptionsItemSelected(MenuItem item) {
    62.         int id = item.getItemId();
    63.         if (id == R.id.menu_item_settings) {
    64.             return true;
    65.         }
    66.         return super.onOptionsItemSelected(item);
    67.     }
    68.  
    69.  
    70.     public void getEmpIdAndUpdateEmp(){
    71.  
    72.         LayoutInflater li = LayoutInflater.from(this);
    73.         View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
    74.  
    75.         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    76.         // set dialog_get_emp_id.xml to alertdialog builder
    77.         alertDialogBuilder.setView(getEmpIdView);
    78.  
    79.         final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
    80.  
    81.         // set dialog message
    82.         alertDialogBuilder
    83.                 .setCancelable(false)
    84.                 .setPositiveButton("OK",new DialogInterface.OnClickListener() {
    85.                             public void onClick(DialogInterface dialog,int id) {
    86.                                 // get user input and set it to result
    87.                                 // edit text
    88.                                 Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
    89.                                 i.putExtra(EXTRA_ADD_UPDATE, "Update");
    90.                                 i.putExtra(EXTRA_EMP_ID, Long.parseLong(userInput.getText().toString()));
    91.                                 startActivity(i);
    92.                             }
    93.                         }).create()
    94.                 .show();
    95.  
    96.     }
    97.  
    98.  
    99.     public void getEmpIdAndRemoveEmp(){
    100.  
    101.         LayoutInflater li = LayoutInflater.from(this);
    102.         View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);
    103.  
    104.         AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    105.         // set dialog_get_emp_id.xml to alertdialog builder
    106.         alertDialogBuilder.setView(getEmpIdView);
    107.  
    108.         final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);
    109.  
    110.         // set dialog message
    111.         alertDialogBuilder
    112.                 .setCancelable(false)
    113.                 .setPositiveButton("OK",new DialogInterface.OnClickListener() {
    114.                     public void onClick(DialogInterface dialog,int id) {
    115.                         // get user input and set it to result
    116.                         // edit text
    117.                         employeeOps = new EmployeeOperations(MainActivity.this);
    118.                         employeeOps.removeEmployee(employeeOps.getEmployee(Long.parseLong(userInput.getText().toString())));
    119.                         Toast t = Toast.makeText(MainActivity.this,"Employee removed successfully!",Toast.LENGTH_SHORT);
    120.                         t.show();
    121.                     }
    122.                 }).create()
    123.                 .show();
    124.  
    125.     }
    126.  
    127.  
    128.  
    129.     @Override
    130.     protected void onResume() {
    131.         super.onResume();
    132.         employeeOps.open();
    133.     }
    134.  
    135.     @Override
    136.     protected void onPause() {
    137.         super.onPause();
    138.         employeeOps.close();
    139.  
    140.     }
    141. }
    142.  
    143.  
    144.  
     

    Advertisement

    #1 Julius_J, Jun 11, 2016
    Last edited: Jun 11, 2016
  2. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,311
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,311
    10,431
    1,988
    Male
    Software developer
    South West of England
    Variable 'database'is null.
    Rest of Employee class not shown, but you didn't initialise it properly.
     
  3. Julius_J

    Julius_J Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    3
    Joined:
    Jun 11, 2016

    Jun 11, 2016
    3
    0
    5
    Male
    I edited the Employee class. Could you point me what's wrong, please?
    Thanks for your reply.
     
  4. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,311
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,311
    10,431
    1,988
    Male
    Software developer
    South West of England
    Question for you: Do you understand what causes a NullPointerException?
     
  5. Julius_J

    Julius_J Lurker
    Thread Starter
    Rank:
    None
    Points:
    5
    Posts:
    3
    Joined:
    Jun 11, 2016

    Jun 11, 2016
    3
    0
    5
    Male
    Yeah, I know, java is trying to access a memory object that has not been instantiated, but I didn't found it.
    But now I found that I was creating a new instance of EmployeeOperations, but never call its open().

    Solved that, I got other exception.

    Code (Java):
    1.  
    2. 06-11 20:17:16.544 32506-32506/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
    3. Process: com.androidtutorialpoint.employeemanagementsystem, PID: 32506
    4. java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
    5. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2358)
    6. at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
    7. at android.app.ActivityThread.access$900(ActivityThread.java:154)
    8. at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
    9. at android.os.Handler.dispatchMessage(Handler.java:102)
    10. at android.os.Looper.loop(Looper.java:135)
    11. at android.app.ActivityThread.main(ActivityThread.java:5294)
    12. at java.lang.reflect.Method.invoke(Native Method)
    13. at java.lang.reflect.Method.invoke(Method.java:372)
    14. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    15. at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
    16. at
    17. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.query(java.lang.String, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
    18. at com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.getEmployee(EmployeeOperations.java:63)
    19. at com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee.initializeEmployee(AddUpdateEmployee.java:142)
    20. at com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee.onCreate(AddUpdateEmployee.java:68)
    21. at android.app.Activity.performCreate(Activity.java:5990)
    22. at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    23. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
    24. at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2420)
    25. at android.app.ActivityThread.access$900(ActivityThread.java:154)
    26. at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
    27. at android.os.Handler.dispatchMessage(Handler.java:102)
    28. at android.os.Looper.loop(Looper.java:135)
    29. at android.app.ActivityThread.main(ActivityThread.java:5294)
    30. at java.lang.reflect.Method.invoke(Native Method)
    31. at java.lang.reflect.Method.invoke(Method.java:372)
    32. at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
    33.  
     
  6. LV426

    LV426 I say we take off and nuke this place from orbit
    Moderator
    Rank:
     #11
    Points:
    1,988
    Posts:
    7,311
    Joined:
    Oct 16, 2015

    Oct 16, 2015
    7,311
    10,431
    1,988
    Male
    Software developer
    South West of England
    No you haven't solved it. You're getting exactly the same exception, at the same point in your code.
     
  7. RAJESH20K

    RAJESH20K Lurker
    Rank:
    None
    Points:
    5
    Posts:
    1
    Joined:
    Mar 25, 2018

    Mar 25, 2018
    1
    0
    5
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    employeeOps = new EmployeeOperations(this);
    setContentView(R.layout.activity_main);

    --- initialise database helper

    employeeOps = new EmployeeOperations(this);
     

Share This Page

Loading...