Main navigation

Android SQLite Database Tutorial – CRUD Operations

adsense


DataBase is one of the ways of storing data. However we should prefer using a DB only if the data we are dealing with is structured data like Employee details of an organization.

Android SDK comes with built in support for SQLite Database. Android SQLite Database is a light weight database mainly useful for embedded applications, it reads and writes directly to disk files.

In this tutorial we will be creating Employees Management System needed for every company. We will create a simple employees database which will be used for storing employee information. We will perform the SQLite CRUD(Create, Read, Update and Delete) operation.

All the classes and interfaces that are required to work with Android SQLite Database are available in the package,android.database.sqlite. The SQLite Database class represents a file on the Android device. You can control the name of the file which contains the DB and it will be a single file rather than multiple scattered files.

Let’s review some of the important classes that we’ll use when working with an SQLite database.

ClassDescription
SQLiteDatabaserepresents the Android SQLite database
SQLiteOpenHelpera helper class that manages the Android SQLite DB
SQLiteQueryrepresents an Android SQLite DB query
SQLite Statementrepresents an Android SQLite statement
SQLiteCursorexposes the results from a query, use to iterate through the results from the query.
SQLiteQueryBuildera helper class to build and manage queries
SQLiteExceptionrepresents an Android SQLite Exceptions

We will use the following structure to create the SQLite database in android. For now, we will be creating a single table named the employee.

Table Name : employee

FieldTypeKey
empIdINTPRIMARY
firstnameTEXT 
lastnameTEXT 
genderTEXT 
hiredateTEXT 
deptTEXT

The primary key column will be an integer and it will auto-increment and then there are five text columns.

Pre-requisites for Creating Android SQLite Database App

1) Android Studio installed on your PC (Unix or Windows). You can learn how to install it here .
2) A real time android device (Smartphone or Tablet) configured with Android Studio. .
3) A basic knowledge of Android lifecycle and different classes & functions used in Android Studio.

Create new Android Project and name it EmployeeManagement System. Next follow the below steps.

Creating a Model Class

Since we are dealing with employee information let’s create Employee.java class which will act as model for our application. Create a package named Model, create a java class Employee.java and put the following code.

Employee.java

package com.androidtutorialpoint.employeemanagementsystem.Model;

public class Employee {
    private long empId;
    private String firstname;
    private String lastname;
    private String gender;
    private String hiredate;
    private String dept;

    public Employee(long empId, String firstname, String lastname, String gender, String hiredate, String dept){
        this.empId = empId;
        this.firstname = firstname;
        this.lastname = lastname;
        this.gender = gender;
        this.hiredate = hiredate;
        this.dept = dept;

    }

    public Employee(){

    }

    public long getEmpId() {
        return empId;
    }

    public void setEmpId(long empId) {
        this.empId = empId;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getHiredate() {
        return hiredate;
    }

    public void setHiredate(String hiredate) {
        this.hiredate = hiredate;
    }

    public String getDept() {
        return dept;
    }

    public void setDept(String dept) {
        this.dept = dept;
    }

    public String toString(){
        return "Emp id: "+getEmpId()+ "\n" +
                "Name: "+getFirstname() + " " + getLastname() + "\n" +
                "Hire Date: "+getHiredate() + "\n" +
                "Department : "+getDept();


    }
}

We are Overriding the toString() method in order to get a proper output when we print an Employee.

Creating Employee DB

We will create a class EmployeeDBHandler, a helper class that manages the Android SQLite Database EmployeeDB. It will extend SQLiteOpenHelper class. Create a new package DB. In that package create a new class, name it EmployeeDBHandler
and put the following code. We will explain everything in moment.

EmployerDBHandler.java

package com.androidtutorialpoint.employeemanagementsystem.DB;

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


public class EmployeeDBHandler extends SQLiteOpenHelper{


    private static final String DATABASE_NAME = "employees.db";
    private static final int DATABASE_VERSION = 1;

    public static final String TABLE_EMPLOYEES = "employees";
    public static final String COLUMN_ID = "empId";
    public static final String COLUMN_FIRST_NAME = "firstname";
    public static final String COLUMN_LAST_NAME = "lastname";
    public static final String COLUMN_GENDER = "gender";
    public static final String COLUMN_HIRE_DATE= "hiredata";
    public static final String COLUMN_DEPT= "dept";

    private static final String TABLE_CREATE =
            "CREATE TABLE " + TABLE_EMPLOYEES + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    COLUMN_FIRST_NAME + " TEXT, " +
                    COLUMN_LAST_NAME + " TEXT, " +
                    COLUMN_GENDER + " TEXT, " +
                    COLUMN_HIRE_DATE + " NUMERIC, " +
                    COLUMN_DEPT + " TEXT " +
                    ")";


    public EmployeeDBHandler(Context context){
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
        
    }

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

       db.execSQL("DROP TABLE IF EXISTS "+TABLE_EMPLOYEES);
       db.execSQL(TABLE_CREATE);
    }
}

We have defined some constants. First there’s constant for the name of the database, then there are constants for the version and columns we will be creating and finally, there’s a constant named Table Create that defines an SQL statement to create employee table. The version for the Android SQLite Database is required, it starts from 1 and every time DB structure is changed, we increment it by 1. There is constructor that receives the context and calls the super class constructor along with the db version.

The onCreate() and onUpgrade() methods are be called by the Android OS. onCreate() method is called in case Android SQLite Database doesn’t exist and we want to get a connection to the database. However if the database already exists, but the database version is changed the onUpgrade method is invoked.

In the onCreate()method, we add the code to create the employee table. The execSQL() method will execute the sqlite create table query.

In the onUpgrade() method, we simply drop the existing table, and create the new with updated version number. After dropping we recreate it using the same query as in onCreate()

Create, Read, Update and Delete operation for Employees

Create a class EmployeeOperations.java under DB package and put the following code.

EmployeeOperations.java

package com.androidtutorialpoint.employeemanagementsystem.DB;

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


import com.androidtutorialpoint.employeemanagementsystem.Model.Employee;
import java.util.ArrayList;
import java.util.List;


public class EmployeeOperations {
    public static final String LOGTAG = "EMP_MNGMNT_SYS";

    SQLiteOpenHelper dbhandler;
    SQLiteDatabase database;

    private static final String[] allColumns = {
            EmployeeDBHandler.COLUMN_ID,
            EmployeeDBHandler.COLUMN_FIRST_NAME,
            EmployeeDBHandler.COLUMN_LAST_NAME,
            EmployeeDBHandler.COLUMN_GENDER,
            EmployeeDBHandler.COLUMN_HIRE_DATE,
            EmployeeDBHandler.COLUMN_DEPT

    };

    public EmployeeOperations(Context context){
        dbhandler = new EmployeeDBHandler(context);
    }

    public void open(){
        Log.i(LOGTAG,"Database Opened");
        database = dbhandler.getWritableDatabase();


    }
    public void close(){
        Log.i(LOGTAG, "Database Closed");
        dbhandler.close();

    }
    public Employee addEmployee(Employee Employee){
        ContentValues values  = new ContentValues();
        values.put(EmployeeDBHandler.COLUMN_FIRST_NAME,Employee.getFirstname());
        values.put(EmployeeDBHandler.COLUMN_LAST_NAME,Employee.getLastname());
        values.put(EmployeeDBHandler.COLUMN_GENDER, Employee.getGender());
        values.put(EmployeeDBHandler.COLUMN_HIRE_DATE, Employee.getHiredate());
        values.put(EmployeeDBHandler.COLUMN_DEPT, Employee.getDept());
        long insertid = database.insert(EmployeeDBHandler.TABLE_EMPLOYEES,null,values);
        Employee.setEmpId(insertid);
        return Employee;

    }

    // Getting single Employee
    public Employee getEmployee(long id) {

        Cursor cursor = database.query(EmployeeDBHandler.TABLE_EMPLOYEES,allColumns,EmployeeDBHandler.COLUMN_ID + "=?",new String[]{String.valueOf(id)},null,null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Employee e = new Employee(Long.parseLong(cursor.getString(0)),cursor.getString(1),cursor.getString(2),cursor.getString(3),cursor.getString(4),cursor.getString(5));
        // return Employee
        return e;
    }

    public List<Employee> getAllEmployees() {

        Cursor cursor = database.query(EmployeeDBHandler.TABLE_EMPLOYEES,allColumns,null,null,null, null, null);

            List<Employee> employees = new ArrayList<>();
        if(cursor.getCount() > 0){
            while(cursor.moveToNext()){
                Employee employee = new Employee();
                employee.setEmpId(cursor.getLong(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_ID)));
                employee.setFirstname(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_FIRST_NAME)));
                employee.setLastname(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_LAST_NAME)));
                employee.setGender(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_GENDER)));
                employee.setHiredate(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_HIRE_DATE)));
                employee.setDept(cursor.getString(cursor.getColumnIndex(EmployeeDBHandler.COLUMN_DEPT)));
                employees.add(employee);
            }
        }
        // return All Employees
        return employees;
    }




    // Updating Employee
    public int updateEmployee(Employee employee) {

        ContentValues values = new ContentValues();
        values.put(EmployeeDBHandler.COLUMN_FIRST_NAME, employee.getFirstname());
        values.put(EmployeeDBHandler.COLUMN_LAST_NAME, employee.getLastname());
        values.put(EmployeeDBHandler.COLUMN_GENDER, employee.getGender());
        values.put(EmployeeDBHandler.COLUMN_HIRE_DATE, employee.getHiredate());
        values.put(EmployeeDBHandler.COLUMN_DEPT, employee.getDept());

        // updating row
        return database.update(EmployeeDBHandler.TABLE_EMPLOYEES, values,
                EmployeeDBHandler.COLUMN_ID + "=?",new String[] { String.valueOf(employee.getEmpId())});
    }

    // Deleting Employee
    public void removeEmployee(Employee employee) {

        database.delete(EmployeeDBHandler.TABLE_EMPLOYEES, EmployeeDBHandler.COLUMN_ID + "=" + employee.getEmpId(), null);
    }



}

This class consists of methods to perform all the four operations(CRUD) on the employee table of our Android SQLite Database. We have a constuctor that will instantiate the database handler. The open() method is used to get a writeable database object and close() do disconnect it. Using these two methods we can open or close the database connection anytime from anywhere.

Then we have the method addEmployee() for android sqlite insert. It will add an employee to the Android SQLite database. We put the values of all the required fields into ContentValues object and then insert into DB. The insert operation will return the autogenerated empId.

Next we have, getEmployee() function that takes in empId and returns an Employee object. This is sqlite SELECT query, here we get the result of query into a cursor and then return the first row.

The getAllEmployees() function is similar to getEmployee() however it returns a list of Employees.

The updateEmployee function is similar to addEmployee here we put new values in the ContentValues object and then update it in the database. This represents sqlite update query.

At last we have removeEmployee() function for sqlite delete query. It is used to remove an employee based upon the given employee object.

All the queries are really simple, so no neet to explain them in detail. Please leave comments below if you don’t understand anything.

Creating a User Interace

We will be creating a user interface for our Employee Management System. On completion it will look like as shown below.

Employee Management System Main Screen in Android SQLite Database Tutorial
Open the layout for the MainActivity and add the following code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:orientation="vertical"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:gravity="center_horizontal">

    <TextView android:text="@string/choose_menu" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/header_margin"
        android:paddingRight="@dimen/header_margin"
        android:paddingLeft="@dimen/header_margin"
        android:paddingBottom="@dimen/header_bottom_margin"
        android:textSize="@dimen/text_size"
        android:fontFamily="sans-serif"
        android:textStyle="bold"
        android:gravity="clip_horizontal" />
    <Button
        android:id="@+id/button_add_employee"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/add_employee"/>

    <Button
        android:id="@+id/button_edit_employee"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/update_employee"/>

    <Button
        android:id="@+id/button_delete_employee"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/remove_employee"/>

    <Button
        android:id="@+id/button_view_employees"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/view_all_employees"/>
</LinearLayout>

The layout is really simple we have a header TextView and four buttons, each for adding,updating,removing a single employee and one listing all employees.

Next, open MainActivity.java and add the following code. We will explain everything in a moment.

MainActivity.java

package com.androidtutorialpoint.employeemanagementsystem;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations;

public class MainActivity extends AppCompatActivity{

    private Button addEmployeeButton;
    private Button editEmployeeButton;
    private Button deleteEmployeeButton;
    private Button viewAllEmployeeButton;
    private EmployeeOperations employeeOps;
    private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId";
    private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        addEmployeeButton = (Button) findViewById(R.id.button_add_employee);
        editEmployeeButton = (Button) findViewById(R.id.button_edit_employee);
        deleteEmployeeButton = (Button) findViewById(R.id.button_delete_employee);
        viewAllEmployeeButton = (Button)findViewById(R.id.button_view_employees);



        addEmployeeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
                i.putExtra(EXTRA_ADD_UPDATE, "Add");
                startActivity(i);
            }
        });
        editEmployeeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getEmpIdAndUpdateEmp();
            }
        });
        deleteEmployeeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getEmpIdAndRemoveEmp();
            }
        });
        viewAllEmployeeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, ViewAllEmployees.class);
                startActivity(i);
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.employee_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_item_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void getEmpIdAndUpdateEmp(){

        LayoutInflater li = LayoutInflater.from(this);
        View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_emp_id.xml to alertdialog builder
        alertDialogBuilder.setView(getEmpIdView);

        final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // get user input and set it to result
                                // edit text
                                Intent i = new Intent(MainActivity.this,AddUpdateEmployee.class);
                                i.putExtra(EXTRA_ADD_UPDATE, "Update");
                                i.putExtra(EXTRA_EMP_ID, Long.parseLong(userInput.getText().toString()));
                                startActivity(i);
                            }
                        }).create()
                .show();

    }


    public void getEmpIdAndRemoveEmp(){

        LayoutInflater li = LayoutInflater.from(this);
        View getEmpIdView = li.inflate(R.layout.dialog_get_emp_id, null);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        // set dialog_get_emp_id.xml to alertdialog builder
        alertDialogBuilder.setView(getEmpIdView);

        final EditText userInput = (EditText) getEmpIdView.findViewById(R.id.editTextDialogUserInput);

        // set dialog message
        alertDialogBuilder
                .setCancelable(false)
                .setPositiveButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // get user input and set it to result
                        // edit text
                        employeeOps = new EmployeeOperations(MainActivity.this);
                        employeeOps.removeEmployee(employeeOps.getEmployee(Long.parseLong(userInput.getText().toString())));
                        Toast t = Toast.makeText(MainActivity.this,"Employee removed successfully!",Toast.LENGTH_SHORT);
                        t.show();
                    }
                }).create()
                .show();

    }

    @Override
    protected void onResume() {
        super.onResume();
        employeeOps.open();
    }

    @Override
    protected void onPause() {
        super.onPause();
        employeeOps.close();

    }
}
  • First, we define two constant we will be using to as EXTRA while starting the addUpdateActivity
  • private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId";
    
    private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update";
    
  • Next, we setOnClickListener() for the addEmployeeButton. Here we invoke AddUpdateEmployee activity, another activity where we are getting employee information from the user, we will talk about this activity in a moment. Please Note that we are using a common activity to Add as well as update employee information, so we are passing an extra EXTRA_ADD_UPDATE. This extra will have a value “Add” if we want to add a new employee, and a value “Update” when we click on Update employee button.
  • Similarly, we setOnClickListener() for the editEmployeeButton, Here we want the user to input his employee Id. So we are calling getEmpIdAndUpdateEmp() function. Let’s review the function code. We will using an AlertDialog to get user input, so we have to create a layout for aour alertDialog. Create a new layout file and name it dialog_get_emp_id.xml and put the folowing code.The alert Dialog will look like this.
    Enter Employee Id.

    Please refer to the following tutorial to read more about Android Alert Dialogs Tutorial

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:id="@+id/layout_root"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:padding="@dimen/view_padding" >
    
        <TextView
            android:id="@+id/text_view_emp_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/enter_employee_id"
            android:layout_gravity="center"
            android:textSize="@dimen/text_size"
            android:textStyle="bold" />
    
        <EditText
            android:id="@+id/editTextDialogUserInput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>
    

    We are using a LinearLayout with a TextView and an EditText to take employee Id from user. Then we are inflating this layout and creating an AlertDialog.Builder object and when user presses “OK”, we call the AddUpdateEmployee class and pass in the EXTRA_ADD_UPDATE as “Update” so that it works in Update Mode and then pass empId in the EXTRA_EMP_ID.

  • For the removeEmployeeButton we have created a similar function getEmpIdAndRemoveEmp(), however instead of calling any activity we are simply creating a employeeOperations object and then calling removeEmployee and pass in the Employee object.
  • Then we set setOnClickListener for the viewAllEmployeeButton and call another activity ViewAllEmployees which will list all the employees. We will discuss about this activity in a while.
  • At last we are overriding the onResume() and onPause() method for the MainActivity.
    @Override
        protected void onResume() {
            super.onResume();
            employeeOps.open();
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            employeeOps.close();
    
        }
    

    These are Activity lifecycle methods which are called by Android SDK automatically.When the activity appears on the screen, it’s onResume() method is called. So we open a connection to database in this method so that we always have a writable database handy. Similarly, we will close the database connection explicitly in case the activity pauses, which is when the onPause() is called.

Add or Update Employe

As discussed we have created a separate Activity to add or update an employee, create a new layout file named activity_add_update_employee.xml and put the following code. The layout will look like this on the device.

Add/Update Employee Form

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="30dp">
    <EditText
        android:id="@+id/edit_text_first_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/add_first_name"
        android:padding="@dimen/view_padding"
        android:textSize="@dimen/add_edit_textsize"/>
    <EditText
        android:id="@+id/edit_text_last_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/add_last_name"
        android:padding="@dimen/view_padding"
        android:textSize="@dimen/add_edit_textsize"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="@dimen/view_padding">

    <TextView
            android:id="@+id/text_view_gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/gender"
            android:textSize="@dimen/add_edit_textsize"
            android:paddingRight="25dp"/>
        <RadioGroup
            android:id="@+id/radio_gender"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingRight="25dp"
            >


            <RadioButton
                android:id="@+id/radio_male"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/string_male"
                android:textSize="@dimen/add_edit_textsize"
                android:checked="true"/>

            <RadioButton
                android:id="@+id/radio_female"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/string_female"
                android:textSize="@dimen/add_edit_textsize"/>

         </RadioGroup>

    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/view_padding">

    <EditText
            android:id="@+id/edit_text_hire_date"
            android:hint="@string/add_date"
            android:layout_width="wrap_content"
            android:layout_weight="8"
            android:layout_height="wrap_content"
        android:gravity="left" />
        <ImageView
            android:id="@+id/image_view_hire_date"
            android:src="@android:drawable/ic_menu_my_calendar"
            android:layout_weight="5"
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
    </LinearLayout>
    <EditText
        android:id="@+id/edit_text_dept"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/add_dept"
        />
    <Button
        android:id="@+id/button_add_update_employee"
        android:layout_width="@dimen/button_width"
        android:layout_height="@dimen/button_height"
        android:layout_marginTop="@dimen/button_padding"
        android:text="@string/add_employee"
        android:layout_gravity="center"/>
</LinearLayout>

In the layout we have EditText for FirstName, LastName, HireDate and Department. For Gender we are using a RadioGroup and for the HireDate the user can even click on the calender icon to select from a date picker.

To add the functionality, create a new java class and name it AddUpdateEmployee and put the following code in it.

AddUpdateEmployee.java

package com.androidtutorialpoint.employeemanagementsystem;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.androidtutorialpoint.employeemanagementsystem.Model.Employee;
import com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations;

import java.text.SimpleDateFormat;
import java.util.Date;

public class AddUpdateEmployee extends AppCompatActivity implements DatePickerFragment.DateDialogListener{

    private static final String EXTRA_EMP_ID = "com.androidtutorialpoint.empId";
    private static final String EXTRA_ADD_UPDATE = "com.androidtutorialpoint.add_update";
    private static final String DIALOG_DATE = "DialogDate";
    private ImageView calendarImage;
    private RadioGroup radioGroup;
    private RadioButton maleRadioButton,femaleRadioButton;
    private EditText firstNameEditText;
    private EditText lastNameEditText;
    private EditText deptEditText;
    private EditText hireDateEditText;
    private Button addUpdateButton;
    private Employee newEmployee;
    private Employee oldEmployee;
    private String mode;
    private long empId;
    private EmployeeOperations employeeData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_update_employee);
        newEmployee = new Employee();
        oldEmployee = new Employee();
        firstNameEditText = (EditText)findViewById(R.id.edit_text_first_name);
        lastNameEditText = (EditText)findViewById(R.id.edit_text_last_name);
        hireDateEditText = (EditText) findViewById(R.id.edit_text_hire_date);
        radioGroup = (RadioGroup) findViewById(R.id.radio_gender);
        maleRadioButton = (RadioButton) findViewById(R.id.radio_male);
        femaleRadioButton = (RadioButton) findViewById(R.id.radio_female);
        calendarImage = (ImageView)findViewById(R.id.image_view_hire_date);
        deptEditText = (EditText)findViewById(R.id.edit_text_dept);
        addUpdateButton = (Button)findViewById(R.id.button_add_update_employee);
        employeeData = new EmployeeOperations(this);
        employeeData.open();


        mode = getIntent().getStringExtra(EXTRA_ADD_UPDATE);
        if(mode.equals("Update")){

            addUpdateButton.setText("Update Employee");
            empId = getIntent().getLongExtra(EXTRA_EMP_ID,0);

            initializeEmployee(empId);

        }

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // find which radio button is selected
                if (checkedId == R.id.radio_male) {
                    newEmployee.setGender("M");
                    if(mode.equals("Update")){
                        oldEmployee.setGender("M");
                    }
                } else if (checkedId == R.id.radio_female) {
                    newEmployee.setGender("F");
                    if(mode.equals("Update")){
                        oldEmployee.setGender("F");
                    }

                }
            }

        });

        calendarImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentManager manager = getSupportFragmentManager();
                DatePickerFragment dialog = new DatePickerFragment();
                dialog.show(manager, DIALOG_DATE);
            }
        });


        addUpdateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

               if(mode.equals("Add")) {
                   newEmployee.setFirstname(firstNameEditText.getText().toString());
                   newEmployee.setLastname(lastNameEditText.getText().toString());
                   newEmployee.setHiredate(hireDateEditText.getText().toString());
                   newEmployee.setDept(deptEditText.getText().toString());
                   employeeData.addEmployee(newEmployee);
                   Toast t = Toast.makeText(AddUpdateEmployee.this, "Employee "+ newEmployee.getFirstname() + "has been added successfully !", Toast.LENGTH_SHORT);
                   t.show();
                   Intent i = new Intent(AddUpdateEmployee.this,MainActivity.class);
                   startActivity(i);
               }else {
                   oldEmployee.setFirstname(firstNameEditText.getText().toString());
                   oldEmployee.setLastname(lastNameEditText.getText().toString());
                   oldEmployee.setHiredate(hireDateEditText.getText().toString());
                   oldEmployee.setDept(deptEditText.getText().toString());
                   employeeData.updateEmployee(oldEmployee);
                   Toast t = Toast.makeText(AddUpdateEmployee.this, "Employee "+ oldEmployee.getFirstname() + " has been updated successfully !", Toast.LENGTH_SHORT);
                   t.show();
                   Intent i = new Intent(AddUpdateEmployee.this,MainActivity.class);
                   startActivity(i);

               }


            }
        });


    }

    private void initializeEmployee(long empId) {
        oldEmployee = employeeData.getEmployee(empId);
        firstNameEditText.setText(oldEmployee.getFirstname());
        lastNameEditText.setText(oldEmployee.getLastname());
        hireDateEditText.setText(oldEmployee.getHiredate());
        radioGroup.check(oldEmployee.getGender().equals("M") ? R.id.radio_male : R.id.radio_female);
        deptEditText.setText(oldEmployee.getDept());
    }


    @Override
    public void onFinishDialog(Date date) {
        hireDateEditText.setText(formatDate(date));

    }

    public String formatDate(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String hireDate = sdf.format(date);
        return hireDate;
    }

}

Let’s quickly review the activity code.

  • Here first we declared all the EXTRA’s which we will be needed to get info from the calling activity.
  • In the onCreate method we reference the EditText‘s RadioGroup,RadioButton and all other views.

    Then we get the mode information from the calling activity, as we discussed earlier mode will be “Add” if we want to add a new employee and “Edit” if want to update an existing employee.

    In case the mode is Update we have to initialize the form with the existing data of the employee and get the empId from the calling Activity.

  • Then we set the onCheckedChangeListener on our radioGroup and set the employee’s gender accordingly.
  • The user can enter the hireDate or select by clicking on the caledar image. We have created a DatePickerFragment for this purpose. Create a new java class named DatePickerFragment and put the following code.
    package com.androidtutorialpoint.employeemanagementsystem;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.Dialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.DialogFragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.DatePicker;
    
    import java.lang.reflect.AccessibleObject;
    import java.util.Date;
    import java.util.GregorianCalendar;
    
    
    public class DatePickerFragment extends DialogFragment {
    
        private DatePicker datePicker;
        private static final int REQUEST_DATE = 1;
    
        public static final String EXTRA_DATE =
                "com.androidtutorialpoint.date";
    
        public interface DateDialogListener {
            void onFinishDialog(Date date);
        }
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState){
    
            View v = LayoutInflater.from(getActivity())
                    .inflate(R.layout.dialog_date,null);
    
            datePicker = (DatePicker) v.findViewById(R.id.dialog_date_date_picker);
    
    
            return new android.support.v7.app.AlertDialog.Builder(getActivity())
                    .setView(v)
                    .setTitle(R.string.date_picker_title)
                    .setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    int year = datePicker.getYear();
                                    int mon = datePicker.getMonth();
                                    int day = datePicker.getDayOfMonth();
                                    Date date = new GregorianCalendar(year,mon,day).getTime();
                                    DateDialogListener activity = (DateDialogListener) getActivity();
                                    activity.onFinishDialog(date);
                                    dismiss();
                                }
                            })
                    .create();
        }
    
    
    }
    
    

    Please note that the AddUpdateEmployee Activity implements DatePickerFragment.DateDialogListener which is used to pass the selected date to the hireDateEditText

  • Returning back to discussion of AddUpdateEmployee Activity, we finally setOnClickListener() for the addUpdateButton. In case the mode equals “Add” we are setting attributes for the newEmployee, and then adding the employee to the DB. In case of “Update” mode we are setting the attributes to the oldEmployee object and then updating the employee. In both the cases we are finally displaying a success toast and then going back to our MainActivity.

View All Employees

Finally we come to the ViewAllEmployees Activity. For that create a new layout file named activity_view_all_employees.xml and put the following code.

activity_view_all_employee.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".ViewAllEmployees"
    android:gravity="center_horizontal">
    <ListView
            android:id="@android:id/list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/textView1"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"/>

</LinearLayout>

Here we are using a simple ListView inside a LinearLayout. Next create a java class, name it ViewAllEmployees.java and put the following code.

ViewAllEmployees

package com.androidtutorialpoint.employeemanagementsystem;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

import com.androidtutorialpoint.employeemanagementsystem.Model.Employee;
import com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations;

import java.util.List;

public class ViewAllEmployees extends ListActivity{

    private EmployeeOperations employeeOps;
    List<Employee> employees;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_all_employees);
        employeeOps = new EmployeeOperations(this);
        employeeOps.open();
        employees = employeeOps.getAllEmployees();
        employeeOps.close();
        ArrayAdapter<Employee> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, employees);
        setListAdapter(adapter);
    }
}



The code for this activity is really simple, our activity extends ListActivity to show a list of all the employees. We create an instance of EmployeeOperations class, then query the DB for all employees and store those employees in the employees list.

At last we create an ArrayAdapter and then use it throught setListAdapter.



Manifest & Resource Files

Since we are using two additional activities, do remember to add these in the manifest file. Here is the our AndroidManifest.xml file.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.androidtutorialpoint.employeemanagementsystem" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".AddUpdateEmployee"></activity>
        <activity android:name=".ViewAllEmployees"></activity>


    </application>

</manifest>

You can also copy the App icon from the drawable folder from the Download Code link at the top of the post.

We have used the following Strings and dimensions. Copy the below resource files in the respective files.

strings.xml

<resources>
    <string name="app_name">EmployeeManagementSystem</string>
    <string name="date_picker_title">Hire Date</string>
    <string name="new_employee">New Employee</string>
    <string name="show_subtitle">Show Subtitle</string>
    <string name="hide_subtitle">Hide Subtitle</string>
    <string name="subtitle_format">%1$s crimes</string>
    <string name="choose_menu">Choose a Menu Option</string>
    <string name="view_all_employees">View All Employees</string>
    <string name="remove_employee">Remove Employee</string>
    <string name="update_employee">Update Employee</string>
    <string name="add_employee">Add Employee</string>
    <string name="gender">Gender</string>
    <string name="add_last_name">Last Name</string>
    <string name="add_first_name">First Name</string>
    <string name="string_male">Male</string>
    <string name="string_female">Female</string>
    <string name="add_date">Hire Date (DD/MM/YYYY)</string>
    <string name="add_dept">Department</string>
    <string name="enter_employee_id">Enter Your Employee Id</string>
    <string name="settings">Settings</string>
</resources>

dimens.xml

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="header_margin">10dp</dimen>
    <dimen name="text_size">20sp</dimen>
    <dimen name="header_bottom_margin">30dp</dimen>
    <dimen name="view_padding">10dp</dimen>
    <dimen name="add_edit_textsize">18dp</dimen>
    <dimen name="button_width">200dp</dimen>
    <dimen name="button_padding">20dp</dimen>
    <dimen name="button_height">50dp</dimen>
</resources>

Now save and run the app, try adding a few employees and then try to update an employee and then view them all using View All Employees Button. Please leave comments in case you like this tutorial and also post your queries :-).

Click on the Download Now button to download the full code.

Android Tutorial Point Download Now

Reader Interactions

Comments

  1. Hi Android Tutorial Team,

    Before I start with my question I really want to thank you for this tutorial.

    I am completely new to Android development and even though I currently can’t get the app to run it still helped me a lot to understand the whole architecture of Android development.

    I followed the whole tutorial and the only things I changed were the fields of the database and the naming of the variables but for some reason I get some errors I don’t understand.

    *1)
    In my MainActivity class I get an error in the following lines:

    * getMenuInflater().inflate(R.menu.calendarEntry_menu, aMenu);
    (Cannot resolve symbol ‘menu’)

    * if (nId = R.id.menu_item_settings) {
    (Cannot resolve symbol ‘menu_item_settings’)

    *2)
    In my DatePickerFragment class I get similiar error in the following lines:

    * View aView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date, null);
    (Cannot resolve symbol ‘dialog_date’)

    * m_aDatePicker = (DatePicker) aView.findViewById(R.id.dialog_date_picker);
    (Cannot resolve symbol ‘dialog_date_picker’)

    The weird part is that I have to import my ‘.R’ class manually. Otherwise I get the error: “Cannot resolve symbol ‘R'”.

    I checked your code and you don’t have to import the “.R” class.

    Dou you maybe have any idea what I gut have done wrong?
    I am using Android Studio 2.0 and the API for Android 4.0.

    Thanks in advance and regards

    Nefetz

    • Hi Nefetz,
      We are glad that you liked our tutorial, and for the errors you are getting Please ensure that you have declared the variables in the activity and also included the layout files we have provided. You can send your code to [email protected] and we will be really happy to help. Do comment below once you send the files.

      Thanks
      AndroidTutorialPoint

      • Hii.. thank you for awesome crud android tutorial.
        I got same error like Bro Nefetz.

        what wrong with our code ?
        please help… now im try to understand java.
        im using android studio 2.23

        thank in advance and regard

      • hy Tutorial Point Team..
        I Follow this tutorial and i got error like Nefetz.

        *1)
        In my MainActivity class I get an error in the following lines:

        * getMenuInflater().inflate(R.menu.calendarEntry_menu, aMenu);
        (Cannot resolve symbol ‘menu’)

        * if (nId = R.id.menu_item_settings) {
        (Cannot resolve symbol ‘menu_item_settings’)

        *2)
        In my DatePickerFragment class I get similiar error in the following lines:

        * View aView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_date, null);
        (Cannot resolve symbol ‘dialog_date’)

        * m_aDatePicker = (DatePicker) aView.findViewById(R.id.dialog_date_picker);
        (Cannot resolve symbol ‘dialog_date_picker’)

        what was wrong ?

        thank you and regard

        joe

  2. Hi Android Tutorial Team,

    Before I start with my question I really want to thank you for this tutorial.

    I am completely new to Android development and even though I currently can’t get the app to run it still helped me a lot to understand the whole architecture of Android development.

    I followed the whole tutorial and the only things I changed were the fields of the database and the naming of the variables but for some reason I get the following error when trying to run the app on my phone:

    04-10 21:51:14.772 27849-27849/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main

    Process: com.androidtutorialpoint.employeemanagementsystem, PID: 27849

    java.lang.RuntimeException: Unable to resume activity {com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()’ on a null object reference

    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4155)

    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4245)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3360)

    at android.app.ActivityThread.access$1100(ActivityThread.java:221)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:158)

    at android.app.ActivityThread.main(ActivityThread.java:7224)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()’ on a null object reference

    at com.androidtutorialpoint.employeemanagementsystem.MainActivity.onResume(MainActivity.java:148)

    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1286)

    at android.app.Activity.performResume(Activity.java:6987)

    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4144)

    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4245)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3360)

    at android.app.ActivityThread.access$1100(ActivityThread.java:221)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)

    at android.os.Handler.dispatchMessage(Handler.java:102)

    at android.os.Looper.loop(Looper.java:158)

    at android.app.ActivityThread.main(ActivityThread.java:7224)

    at java.lang.reflect.Method.invoke(Native Method)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

    I tested it with your example app and with my own one and the error is exactly the same.

    Do you maybe have any idea what I did wrong and how I could fix that?

    Thanks in advance and regards

    Nefetz

  3. Hey,
    Thanks for this tutorial, this is very helpful.
    I got this error, I didn’t have experience in java, I’m learning it.
    Could you help me please?

    06-10 16:10:52.605 17203-17203/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidtutorialpoint.employeemanagementsystem, PID: 17203
    java.lang.RuntimeException: Unable to resume activity {com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()’ on a null object reference
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3019)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
    at android.app.ActivityThread.access$900(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5294)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:134)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.open()’ on a null object reference
    at com.androidtutorialpoint.employeemanagementsystem.MainActivity.onResume(MainActivity.java:148)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
    at android.app.Activity.performResume(Activity.java:6076)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3008)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3050)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2425)
    at android.app.ActivityThread.access$900(ActivityThread.java:154)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5294)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:134)

    • Hi Jack ,

      Make sure you are creating an object of Employee Operations class before using it
      You should have something like this before calling the open() method
      employeeOps = new EmployeeOperations(MainActivity.this);

      Hope, this helps but in case if you still face any error please send us the complete code at [email protected] and don’t forget to subscribe to our blog and also like our page http://www.facebook.com/androidtutorialpoint on facebook.

      Thanks
      Android Tutorial Point

    • Hi Jack ,

      Make sure you are creating an object of Employee Operations class before using it.

      You should have something like this before calling the open() method
      employeeOps = new EmployeeOperations(MainActivity.this);

      Hope, this helps but in case if you still face any error please send us the complete code at [email protected] and don’t forget to subscribe to our blog and also like our page http://www.facebook.com/androidtutorialpoint on facebook.

      Thanks
      Android Tutorial Point Team

      • Hi,

        I committed the same error than Jack, but I am newer than him in Android Studio. Could you please tell me, How do you create the object of Employee Operations class?

        Thank you by the tutorial!

  4. Great tutorial on android sqlite database tutorial.

    You are helping starters and developers which is one of most important task you are doing for android community.

    Thanks for publishing this!

  5. Hye android studio team ,
    I get some errors I don’t understand. which is

    public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.menu_item_settings) {
    return true;
    }
    return super.onOptionsItemSelected(item);
    }

    menu_item_setting stand for ? and i dont where to declare menu_tem_settings.

    syafika

  6. good evening sir i just want to say that your application does not work properly (Unfortunately Your App has stopped )<- when i running to test this app, what should i do?, thank you for your attention in advance

  7. Iam getting error over here.
    Cursor cursor = database.query(PatientDBHandler.TABLE_PATIENTS,allColumns,null,null,null, null, null);

  8. Hi,Android team.I am getting error in this line.pls check the error.
    Cursor cursor = database.query(PatientDBHandler.TABLE_EMPLOYEES,allColumns, EmployeeDBHandler.COLUMN_ID + ” =? “,new String[]{String.valueOf(id)}, null, null, null, null);

  9. Hey Dudes

    Great Tut, Thank you for helping beginners

    Had a OnResume() – NullPointerException error and fixed it like this in MainActivity.java:
    ——————
    protected void onResume() {
    super.onResume();
    if(employeeOps != null)
    employeeOps.open(); }

    protected void onPause() {
    super.onPause();
    if(employeeOps != null)
    employeeOps.close(); }
    ————–
    So now I’m stuck with another NullPointerException in EmployeeOperations at:
    Cursor cursor = database.query(EmployeeDBHandler.TABLE_EMPLOYEES,allColumns,EmployeeDBHandler.COLUMN_ID + “=?”,new String[]{String.valueOf(id)},null,null, null, null);

    This is where it bombs out

    Please help

  10. hello, thank you for ur tutorial. but i have some problem, if i choose update and remove button and input the number empid then program always force close. i check logcat and im getting error in

    Cursor cursor = database.query(EmployeeDBHandler.TABLE_EMPLOYEES,allColumns,EmployeeDBHandler.COLUMN_ID + “=?”,new String[]{String.valueOf(id)},null,null, null, null);
    return database.update(EmployeeDBHandler.TABLE_EMPLOYEES, values,

    EmployeeDBHandler.COLUMN_ID + “=?”,new String[] { String.valueOf(employee.getEmpId())});

    database.delete(EmployeeDBHandler.TABLE_EMPLOYEES, EmployeeDBHandler.COLUMN_ID + “=” + employee.getEmpId(), null);

    please help, thank you…

  11. App crashes every time a button is pressed on mainactivity. says it cannot find activity or intent. please help.

    • Remove the code below:

      @Override
      protected void onResume() {
      super.onResume();
      employeeOps.open();
      }

      @Override
      protected void onPause() {
      super.onPause();
      employeeOps.close();

      }

  12. I used your code, i dont have any errors but when i tried open this app, i get this messege on emulator “EmployeemanagementSystem has stoppped open app again”. How to repair this bug?

  13. I used your code, i dont have anny errors but when i want open this app in emulator i have this message “Emploeyy System mamagement has stopped open app again”. Any one know how to resolve this???

  14. Guys…first open the database connection (in initializeEmployee method) to get rid of null object reference.

  15. Hello there, i am interested in how the edit and delete functions work in your tutorial so i am using the downloaded version directly in AS. I have maned to get the Add and List functions working but the Edit and Delete functions still will not work.
    The error for the Update Function is (this occurs after the id is entered):
    04-28 12:32:31.858 27890-27890/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidtutorialpoint.employeemanagementsystem, PID: 27890
    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
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    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
    at com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.getEmployee(EmployeeOperations.java:63)
    at com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee.initializeEmployee(AddUpdateEmployee.java:143)
    at com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee.onCreate(AddUpdateEmployee.java:68)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
    at android.app.ActivityThread.access$800(ActivityThread.java:151) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

    And the error for the Delete Function (after the id is entered):
    04-28 12:35:15.674 30330-30330/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidtutorialpoint.employeemanagementsystem, PID: 30330
    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
    at com.androidtutorialpoint.employeemanagementsystem.DB.EmployeeOperations.getEmployee(EmployeeOperations.java:63)
    at com.androidtutorialpoint.employeemanagementsystem.MainActivity$6.onClick(MainActivity.java:134)
    at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:157)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

    I would appreciate your help with this.
    Thanks in advance

  16. Hi, I followed the instruction but there is one i might have missed. It says “DEFAULT ACTIVITY NOT FOUND” when i ran it

  17. I used your code, i dont have anny errors but when i want open this app in emulator i have this message “Emploeyy System mamagement has stopped open app again”. Any one know how to resolve this???

  18. Hi,androidtutorialpoint team,

    In activity_main.xml from what should i put instead of @Dimen……..it’s not working for mine

    • oh, sorry….! I didn’t find such as simple thing before that Dimen.xml is written below… solved my issue 🙂

  19. hy, i get error in (MainActivity.java:148)….
    and that is employeeOps.open(); method……
    how can i solved ?

  20. Hey guys, i have one last issue with this and that is the update. I can click on the update button and enter an id but as soon as ok is clicked the app crashes and i get the following error:

    06-18 23:08:04.440 13587-13587/com.androidtutorialpoint.employeemanagementsystem E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidtutorialpoint.employeemanagementsystem, PID: 13587
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidtutorialpoint.employeemanagementsystem/com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee}: java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean java.lang.String.equals(java.lang.Object)’ on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
    at android.app.ActivityThread.access$800(ActivityThread.java:151)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5254)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘boolean java.lang.String.equals(java.lang.Object)’ on a null object reference
    at com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee.initializeEmployee(AddUpdateEmployee.java:150)
    at com.androidtutorialpoint.employeemanagementsystem.AddUpdateEmployee.onCreate(AddUpdateEmployee.java:68)
    at android.app.Activity.performCreate(Activity.java:5990)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
    at android.app.ActivityThread.access$800(ActivityThread.java:151) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:135) 
    at android.app.ActivityThread.main(ActivityThread.java:5254) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

    This is the third time that i have asked for help on this website for this tutorial, please reply…

    • I have just noticed that the update works perfectly but only on female employees. If a male employee is chosen it crashes with the above error. I am not familiar with the line:

      radioGroup.check(oldEmployee.getGender().equals(“M”) ? R.id.radio_male : R.id.radio_female);

      Is this written correctly?

      Thanks

  21. Hi Guys, I have spotted why the app crashes during update of a male employee. When a male employee is added it saves the gender as NULL because the newEmployee code does not add the gender. Therefore when you try to update that same employee it cannot get the gender as it has none. I am looking into how to fix this but so far i am struggling.I think the way forward is to call up:
    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
    // find which radio button is selected
    if (checkedId == R.id.radio_male) {
    newEmployee.setGender(“M”);
    if(mode.equals(“Update”)){
    oldEmployee.setGender(“M”);
    }
    } else if (checkedId == R.id.radio_female) {
    newEmployee.setGender(“F”);
    if(mode.equals(“Update”)){
    oldEmployee.setGender(“F”);
    }

    }
    }

    });
    in the newEmployee code but it will not allow me to do this so far!
    I am happy to hear your suggestions…..

    • I have found and fixed an issue with this tutorial. When you add an Employee the setOnCheckedChangeListener code is looking for a change in the radioGroup buttons. If no change is made it records the gender as NULL. If you try to edit this employee the app will crash as it cannot add NULL to the radioGroup. To fix this i added newEmployee.setGender(“M”); in the onCreate code. This sets the default gender to “M” and therefore will record the gender as “M” if no other gender is chosen. Problem solved.
      Great tutorial, thanks for posting!

  22. hello i am using adroid studio 2.3.3 and this teaches me alot but i got many errors kindly help me to complete my project….. i am sending code to u kindly help me

Leave a Reply

Advertisment ad adsense adlogger