Employee Management System

Hi all.. here am posting a code for the employee registration and search employees.
this is having the single user authentication. First to add or search the employees you must login with an administrator account to this application. For my app i used "srikanth" as username and "12345" as password.

Here am using the Table Layouts to register and Display the Employee details. In this we are using sqlite database for storing the details.

AddEmployee.java


public class AddEmployee extends Activity {
EditText txtName;
EditText txtAge;
TextView txtEmps;
EditText txtMob;
EditText txtID;
DatabaseHelper dbHelper;
Spinner spinDept;
EditText et1;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addemployee1);
        txtName=(EditText)findViewById(R.id.txtName);
        txtAge=(EditText)findViewById(R.id.txtAge);
        txtMob=(EditText)findViewById(R.id.mobile);
        txtID=(EditText)findViewById(R.id.txtId);
        txtEmps=(TextView)findViewById(R.id.txtEmps);
        spinDept=(Spinner)findViewById(R.id.spinDept);
        et1=(EditText)findViewById(R.id.designation);
    }

@Override
public void onStart()
{
try
{
super.onStart();
dbHelper=new DatabaseHelper(this);
txtEmps.setText(txtEmps.getText()+String.valueOf(dbHelper.getEmployeeCount()));

Cursor c=dbHelper.getAllDepts();
startManagingCursor(c);



//SimpleCursorAdapter ca=new SimpleCursorAdapter(this,android.R.layout.simple_spinner_item, c, new String [] {DatabaseHelper.colDeptName}, new int []{android.R.id.text1});
SimpleCursorAdapter ca=new SimpleCursorAdapter(this,R.layout.deptspinnerrow, c, new String [] {DatabaseHelper.colDeptName,"_id"}, new int []{R.id.txtDeptName});
//ca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinDept.setAdapter(ca);
spinDept.setOnItemSelectedListener(new OnItemSelectedListener() {


@Override
public void onItemSelected(AdapterView<?> parent, View selectedView,
int position, long id) {
// TODO Auto-generated method stub

}


@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});


//never close cursor
}
catch(Exception ex)
{
CatchError(ex.toString());
}
}

public void btnAddEmp_Click(View view)
{
boolean ok=true;
try
{
//Spannable spn=txtAge.getText();
String mobile = txtMob.getText().toString();
String empID = txtID.getText().toString();
String name=txtName.getText().toString();
String age=txtAge.getText().toString();
String designation = et1.getText().toString();
System.out.println("Designation is..." +designation);
int deptID=Integer.valueOf((int)spinDept.getSelectedItemId());


boolean invalid = false;

if(name.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your name", Toast.LENGTH_SHORT).show();
}
else
if(empID.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your employeeID", Toast.LENGTH_SHORT).show();
}
else
if(age.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your Age", Toast.LENGTH_SHORT).show();
}
else
if(mobile.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your Mobile No.", Toast.LENGTH_SHORT).show();
}
else
if(designation.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your Designation.", Toast.LENGTH_SHORT).show();
}
else

if(invalid == false)
{
Employee emp=new Employee(name,empID,age,mobile,designation,deptID);
dbHelper.AddEmployee(emp);
Alerts.ShowEmpAddedAlert(this);
Intent i_register = new Intent(AddEmployee.this, DatabaseDemo.class);
startActivity(i_register);
}
}
catch(Exception ex)
{
ok=false;
CatchError(ex.toString());
}
finally
{
if(ok)
{
//NotifyEmpAdded();

txtEmps.setText("Number of employees "+String.valueOf(dbHelper.getEmployeeCount()));
}
}
}



void CatchError(String Exception)
{
Dialog diag=new Dialog(this);
diag.setTitle("Add new Employee");
TextView txt=new TextView(this);
txt.setText(Exception);
diag.setContentView(txt);
diag.show();
}

void NotifyEmpAdded()
{
Dialog diag=new Dialog(this);
diag.setTitle("Add new Employee");
TextView txt=new TextView(this);
txt.setText("Employee Added Successfully");
diag.setContentView(txt);
diag.show();
try {
diag.wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
CatchError(e.toString());
}
diag.notify();
diag.dismiss();
}

}


Alerts.java



public class Alerts {
public static void ShowEmpAddedAlert(Context con)
{
AlertDialog.Builder builder=new AlertDialog.Builder(con);
builder.setTitle("Add new Employee");
builder.setIcon(android.R.drawable.ic_dialog_info);
DialogListner listner=new DialogListner();
builder.setMessage("Employee Added successfully");
builder.setPositiveButton("ok", listner);

AlertDialog diag=builder.create();
diag.show();
}


public static AlertDialog ShowEditDialog(final Context con,final Employee emp)
{
AlertDialog.Builder b=new AlertDialog.Builder(con);
b.setTitle("Employee Details");
LayoutInflater li=LayoutInflater.from(con);
View v=li.inflate(R.layout.editdialog1, null);

b.setIcon(android.R.drawable.ic_input_get);

b.setView(v);
final EditText txtName=(EditText)v.findViewById(R.id.txtDelName);
final EditText txtID=(EditText)v.findViewById(R.id.txtDelID);
final EditText txtAge=(EditText)v.findViewById(R.id.txtDelAge);
final EditText txtMobile=(EditText)v.findViewById(R.id.txtDelMobile);
final EditText txtdesg = (EditText)v.findViewById(R.id.txtDelDesg);
final Spinner spin=(Spinner)v.findViewById(R.id.spinDiagDept);
Utilities.ManageDeptSpinner(con, spin);
for(int i=0;i<spin.getCount();i++)
{
long id=spin.getItemIdAtPosition(i);
if(id==emp.getDept())
{
spin.setSelection(i, true);
break;
}
}


txtName.setText(emp.getName());
txtID.setText(emp.getempID());
txtMobile.setText(emp.getMobile());
txtAge.setText(String.valueOf(emp.getAge()));
txtdesg.setText(emp.getDesg());
b.setPositiveButton("Modify", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
emp.setName(txtName.getText().toString());
emp.setempID(txtID.getText().toString());
emp.setAge(txtAge.getText().toString());
emp.setMobile(txtMobile.getText().toString());
emp.setDesg(txtdesg.getText().toString());
emp.setDept((int)spin.getItemIdAtPosition(spin.getSelectedItemPosition()));

try
{
DatabaseHelper db=new DatabaseHelper(con);
db.UpdateEmp(emp);

}
catch(Exception ex)
{
CatchError(con, ex.toString());
}
}
});

b.setNeutralButton("Delete", new OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DatabaseHelper db=new DatabaseHelper(con);
db.DeleteEmp(emp);
}
});
b.setNegativeButton("Cancel", null);

return b.create();
//diag.show();

}


static public void CatchError(Context con, String Exception)
{
Dialog diag=new Dialog(con);
diag.setTitle("Error");
TextView txt=new TextView(con);
txt.setText(Exception);
diag.setContentView(txt);
diag.show();
}




}


Here is the main class that holds a tab layout to hold the two linear layouts for adding employee details and displaying the details.
DatabaseDemo.java



public class DatabaseDemo extends TabActivity implements OnClickListener {
DatabaseHelper dbHelper;
GridView grid;
TextView txtTest;
Button logout;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SetupTabs();
        logout = (Button)findViewById(R.id.logout);
        logout.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
    menu.add(1, 1, 1, "Add Employee");
    return true;
    }
    public boolean onOptionsItemSelected(MenuItem item)
    {
    switch (item.getItemId())
    {
    //Add employee
    case 1:
    Intent addIntent=new Intent(this,AddEmployee.class);
    startActivity(addIntent);
    break;
    }
    super.onOptionsItemSelected(item);
    return false;
    }
    void SetupTabs()
    {
    TabHost host=getTabHost();
        TabHost.TabSpec spec=host.newTabSpec("tag1");
        Intent in1=new Intent(this, AddEmployee.class);
        spec.setIndicator("");
        spec.setContent(in1);
    
        TabHost.TabSpec spec2=host.newTabSpec("tag2");
        Intent in2=new Intent(this, GridList.class);
        
        spec2.setIndicator("Employees");
        spec2.setContent(in2);
        
        host.addTab(spec);
        host.addTab(spec2);
    }
               @Override
public void onClick(View v) {
Intent i = new Intent(DatabaseDemo.this, Login.class);
startActivity(i);

}
}


Here is the Database Helper class to create and manage the database and tables.
DatabaseHelper.java



public class DatabaseHelper extends SQLiteOpenHelper {


static final String dbName="demoDB";
static final String employeeTable="Employees";
static final String colID="EmployeeID";
static final String colName="EmployeeName";
static final String colempId="EmpID";
static final String colAge="Age";
static final String colMobile="Mobile";
static final String colDesg="Designation";
static final String colDept="Dept";

static final String deptTable="Dept";
static final String colDeptID="DeptID";
static final String colDeptName="DeptName";

static final String viewEmps="ViewEmps";


public DatabaseHelper(Context context) {
super(context, dbName, null,34);

// TODO Auto-generated constructor stub
}


@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

db.execSQL("CREATE TABLE "+deptTable+" ("+colDeptID+ " INTEGER PRIMARY KEY , "+
colDeptName+ " TEXT)");

db.execSQL("CREATE TABLE "+employeeTable+" ("+colID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+colName+" TEXT,"+colempId+" TEXT, "+
colAge+" Integer,"+colMobile+" TEXT,"+colDesg+" TEXT, "+colDept+" INTEGER NOT NULL ,FOREIGN KEY ("+colDept+") REFERENCES "+deptTable+" ("+colDeptID+"));");


db.execSQL("CREATE TRIGGER fk_empdept_deptid " +
" BEFORE INSERT "+
" ON "+employeeTable+

" FOR EACH ROW BEGIN"+
" SELECT CASE WHEN ((SELECT "+colDeptID+" FROM "+deptTable+" WHERE "+colDeptID+"=new."+colDept+" ) IS NULL)"+
" THEN RAISE (ABORT,'Foreign Key Violation') END;"+
"  END;");

db.execSQL("CREATE VIEW "+viewEmps+
" AS SELECT "+employeeTable+"."+colID+" AS _id,"+
" "+employeeTable+"."+colName+","+
" "+employeeTable+"."+colempId+","+
" "+employeeTable+"."+colAge+","+
" "+employeeTable+"."+colMobile+","+
" "+employeeTable+"."+colDesg+","+
" "+deptTable+"."+colDeptName+""+
" FROM "+employeeTable+" JOIN "+deptTable+
" ON "+employeeTable+"."+colDept+" ="+deptTable+"."+colDeptID
);

InsertDepts(db);

}


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

db.execSQL("DROP TABLE IF EXISTS "+employeeTable);
db.execSQL("DROP TABLE IF EXISTS "+deptTable);

db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger");
db.execSQL("DROP TRIGGER IF EXISTS dept_id_trigger22");
db.execSQL("DROP TRIGGER IF EXISTS fk_empdept_deptid");
db.execSQL("DROP VIEW IF EXISTS "+viewEmps);
onCreate(db);
}

void AddEmployee(Employee emp)
{

SQLiteDatabase db= this.getWritableDatabase();

ContentValues cv=new ContentValues();

cv.put(colName, emp.getName());
cv.put(colempId, emp.getempID());
cv.put(colAge, emp.getAge());
cv.put(colMobile, emp.getMobile());
cv.put(colDesg, emp.getDesg());
cv.put(colDept, emp.getDept());
//cv.put(colDept,2);

db.insert(employeeTable, colName, cv);
db.close();
}
 
int getEmployeeCount()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select * from "+employeeTable, null);
int x= cur.getCount();
cur.close();
return x;
}
 
Cursor getAllEmployees()
{
SQLiteDatabase db=this.getWritableDatabase();

Cursor cur= db.rawQuery("SELECT * FROM "+viewEmps,null);
return cur;
}
Cursor getAllDepts()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cur=db.rawQuery("SELECT "+colDeptID+" as _id, "+colDeptName+" from "+deptTable,new String [] {});
return cur;
}
void InsertDepts(SQLiteDatabase db)
{
ContentValues cv=new ContentValues();
cv.put(colDeptID, 1);
cv.put(colDeptName, "Sales");
db.insert(deptTable, colDeptID, cv);
cv.put(colDeptID, 2);
cv.put(colDeptName, "IT");
db.insert(deptTable, colDeptID, cv);
cv.put(colDeptID, 3);
cv.put(colDeptName, "HR");
db.insert(deptTable, colDeptID, cv);
db.insert(deptTable, colDeptID, cv);

}  
public String GetDept(int ID)
{
SQLiteDatabase db=this.getReadableDatabase();
 
String[] params=new String[]{String.valueOf(ID)};
Cursor c=db.rawQuery("SELECT "+colDeptName+" FROM"+ deptTable+" WHERE "+colDeptID+"=?",params);
c.moveToFirst();
int index= c.getColumnIndex(colDeptName);
return c.getString(index);
}  
public Cursor getEmpByDept(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
String [] columns=new String[]{"_id",colName,colempId,colAge,colMobile,colDesg,colDeptName};
Cursor c=db.query(viewEmps, columns, colDeptName+"=?", new String[]{Dept}, null, null, null);
return c;
}  
public int GetDeptID(String Dept)
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor c=db.query(deptTable, new String[]{colDeptID+" as _id",colDeptName},colDeptName+"=?", new String[]{Dept}, null, null, null);
c.moveToFirst();
return c.getInt(c.getColumnIndex("_id"));
 
}  
public int UpdateEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(colName, emp.getName());
cv.put(colempId, emp.getempID());
cv.put(colAge, emp.getAge());
cv.put(colMobile, emp.getMobile());
cv.put(colDesg, emp.getDesg());
cv.put(colDept, emp.getDept());
return db.update(employeeTable, cv, colID+"=?", new String []{String.valueOf(emp.getID())});
}  
public void DeleteEmp(Employee emp)
{
SQLiteDatabase db=this.getWritableDatabase();
db.delete(employeeTable,colID+"=?", new String [] {String.valueOf(emp.getID())});
db.close();
}
}


Here is Login class to authenticate the administrator.
Login.java



public class Login extends Activity implements OnClickListener{
Button btn;
EditText et1, et2;
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        btn = (Button)findViewById(R.id.btnlogin);
        btn.setOnClickListener(this);
        et1 = (EditText)findViewById(R.id.Leditename);
        et2 = (EditText)findViewById(R.id.Leditpw);
             
}
@Override
public void onClick(View v) {
String ename = et1.getText().toString().trim();
System.out.println("ename is..." +ename);
String epw = et2.getText().toString().trim();
System.out.println("Password is..." +epw);


if(ename.equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter user name", Toast.LENGTH_SHORT).show();
}
else
if(epw.equals(""))
{
Toast.makeText(getApplicationContext(), "please enter Password", Toast.LENGTH_SHORT).show();
}
else
if(ename.equals("srikanth") && epw.equals("12345")){

Toast.makeText(getApplicationContext(), "valid login..!", Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(), DatabaseDemo.class);
startActivity(in);
//finish();
}
else
{
Toast.makeText(getApplicationContext(), "Invalid authentication..!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(), Login.class);
startActivity(intent);
}
}
@Override
public void onBackPressed() 
{
Intent i = new Intent(Login.this, Login.class);
startActivity(i);
}



}


GridList.java



public class GridList extends Activity {
DatabaseHelper dbHelper;
static public GridView grid;
//TextView txtTest;
Spinner spinDept1;
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        setContentView(R.layout.gridview);
        grid=(GridView)findViewById(R.id.grid);
        //txtTest=(TextView)findViewById(R.id.txtTest);
        spinDept1=(Spinner)findViewById(R.id.spinDept1);
        
        Utilities.ManageDeptSpinner(this.getParent(),spinDept1);
        final DatabaseHelper db=new DatabaseHelper(this);
        try
        {
         
         spinDept1.setOnItemSelectedListener(new OnItemSelectedListener() {
         
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
LoadGrid();
    //sca.notifyDataSetChanged();
   
}


@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});
       
        }
        catch(Exception ex)
        {
        //txtTest.setText(ex.toString());
        }
              
        try
        {
        grid.setOnItemClickListener(new OnItemClickListener()
        {


        @Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
try
{

SQLiteCursor cr=(SQLiteCursor)parent.getItemAtPosition(position);
String name=cr.getString(cr.getColumnIndex(DatabaseHelper.colName));
String empid = cr.getString(cr.getColumnIndex(DatabaseHelper.colempId));
String mobile=cr.getString(cr.getColumnIndex(DatabaseHelper.colMobile));
String design=cr.getString(cr.getColumnIndex(DatabaseHelper.colDesg));
System.out.println("designation in grid list is.." +design);
String age=cr.getString(cr.getColumnIndex(DatabaseHelper.colAge));
String Dept=cr.getString(cr.getColumnIndex(DatabaseHelper.colDeptName));
Employee emp=new Employee(name, empid,age,mobile,design,db.GetDeptID(Dept));
emp.SetID((int)id);
AlertDialog diag= Alerts.ShowEditDialog(GridList.this,emp);
diag.setOnDismissListener(new OnDismissListener() {

@Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
//txtTest.setText("dismissed");
//((SimpleCursorAdapter)grid.getAdapter()).notifyDataSetChanged();
LoadGrid();
}
});
diag.show();
}
catch(Exception ex)
{
Alerts.CatchError(GridList.this, ex.toString());
}
}



        }
        );
        }
        catch(Exception ex)
        {
       
        }


    }
    
    @Override
    public void onStart()
    {
    super.onStart();
    //LoadGrid();
    }
    
    public void LoadGrid()
    {
    dbHelper=new DatabaseHelper(this);
    try
    {
    //Cursor c=dbHelper.getAllEmployees();
    View v=spinDept1.getSelectedView();
TextView txt=(TextView)v.findViewById(R.id.txtDeptName);
String Dept=String.valueOf(txt.getText());
    Cursor c=dbHelper.getEmpByDept(Dept);
    startManagingCursor(c);
   
    String [] from=new String []{DatabaseHelper.colName,DatabaseHelper.colempId,DatabaseHelper.colAge,DatabaseHelper.colMobile,DatabaseHelper.colDesg,DatabaseHelper.colDeptName};
    int [] to=new int [] {R.id.colName,R.id.colID,R.id.colAge,R.id.colMobile,R.id.colDesg,R.id.colDept};
    SimpleCursorAdapter sca=new SimpleCursorAdapter(this,R.layout.gridrow,c,from,to);
    grid.setAdapter(sca);
   
   
   
    }
    catch(Exception ex)
    {
    AlertDialog.Builder b=new AlertDialog.Builder(this);
    b.setMessage(ex.toString());
    b.show();
    }
    }
    @Override
public void onBackPressed() 
{
super.onBackPressed();
Intent i = new Intent(GridList.this, DatabaseDemo.class);
startActivity(i);
}

}









you can download the full source code here.  Please comment if you found any bugs.

Comments

  1. hello sir. thanks a lot for the code. but when I try to see the layout of the main.xml file, I get a NullPointerException. I searched a lot but couldnt get a proper solution. can u suggest something?
    any help would be appreciated.

    ReplyDelete
    Replies
    1. Can you please post your log cat here. So that i can get an idea about your problem.

      Delete
    2. Dear Sir,

      When i try to download the full source code, i face the following errors.
      Error (404)
      We can't find the page you're looking for. Check out our Help Center and forums for help, or head back to home.

      Could you post the xml file too.

      Delete
  2. Hi sir, can u mail me the source code or refresh the link
    Kuldeep.maurya15@gmail.com

    ReplyDelete
  3. Hello sir, please can u mail me the full source code with xml files of this project? I can't download tge source code. Please. My email address is: imnnishat@gmail. com

    ReplyDelete
  4. Hello sir, please can u mail me the full source code with xml and manifest files of this project? It shows error while downloading the source code. Please. My email address is:
    dikshataneja03@gmail.com

    ReplyDelete
  5. Hello sir, please can u mail me the full source code with xml and manifest files of this project?
    abhisheksaitwal@gmail.com

    ReplyDelete
  6. Hello sir, can u please mail me the full source code with xml and manifest files of this project? My mail is prince64123@gmail.com

    ReplyDelete

Post a Comment