Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Quote:
When i enter a name of employee in the search box, and click on the "search" button, the matching results are shown in listview //My code does that part. And when i click on one of the resulted employee names from the list, it should move me to new activity where name, title, phone, email, and department, of that employee are shown.

I'm stuck at getting the id of the clicked item of the list part.

This is what i have done so far.


public class MainActivity extends Activity {

    EditText name; //Textbox to input name
    ArrayAdapter<String> nameAdapter;
    DeptDPHelper Emp;  //Database object

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button Search = (Button)findViewById(R.id.Search);

        name = (EditText)findViewById(R.id.name);
        final ListView namelist = (ListView)findViewById(R.id.LV);
        nameAdapter = new ArrayAdapter<>(getApplicationContext() , android.R.layout.simple_list_item_1);
        namelist.setAdapter(nameAdapter);

        Emp = new DeptDPHelper(getApplicationContext());
        //Filling tables
        Emp.InsertEmp("AhmedMhmmd" , "010224455" , "gg@jj.com" , "xx");
        Emp.InsertEmp("MhmmdMhmoud" , "010224455" , "gg@jj.com" , "xx");
        Emp.InsertEmp("Ahmedxxx" , "010224455" , "gg@jj.com" , "xx");
        Emp.InsertDept("Finance");
        Emp.InsertDept("Sales");
        //When clicking on the search button
        Search.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v) {
                Cursor cur = Emp.GetEmpname(name.getText().toString());
                nameAdapter.clear();

                if(cur != null)
                {
                    while(!cur.isAfterLast())
                    {
                        //Toast.makeText(getApplicationContext() , "Error" , Toast.LENGTH_LONG).show();
                        nameAdapter.add(cur.getString(0));
                        cur.moveToNext();
                        //nameAdapter.add("gg");
                    }
                }

                else
                {
                    Toast.makeText(getApplicationContext() , "ErrOooor" , Toast.LENGTH_LONG).show();
                }
            }
        });


Quote:
//Problem from here, i want when i click one of the search results, to move in a new activity using intent, where Name, phone title, email, and department of that clicked employee are shown there. How can i get the id of the clicked name and pass it to the getEmpData and getDeptName methods so that i can pass their values to the new activity?


What I have tried:

namelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View view, int position, long id)
              {
  //This is where i'm stuck in
                  //int x = Integer.parseInt(namelist.getItemAtPosition(position).toString());

                  Intent i = new Intent(MainActivity.this, empDetails.class);
                   i.putExtra("empName", Emp.getEmpData(x));
                   i.putExtra("empTitle",Emp.getEmpData());
                   i.putExtra("empPhone",Emp.getEmpData());
                   i.putExtra("empEmail",Emp.getEmpData());
                   i.putExtra("empDept",Emp.getDeptName());
                  startActivity(i);
              }
          });
    }

//SQLITE
public static class DeptDPHelper extends SQLiteOpenHelper {
        SQLiteDatabase EmpDept;

        public DeptDPHelper(Context context) {
            super(context, "EmpDept", null, 2);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL("create table department(DeptID integer primary key autoincrement , name text);");
            db.execSQL("create table Employee (EmpID integer primary key autoincrement , name text not null," +
                    "Title text not null , phone text not null , email text not null ," +
                    "DeptID integer, foreign key(DeptID) references department (DeptID))");

            //ContentValues row = new ContentValues();
            //db.execSQL("insert into Employee (EmpID , name , Title , phone , email ) values ('Ahmemhmmd' , '010224455' , 'gg@jj.com' , 'xx')");

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("drop table if exists department ");
            db.execSQL("drop table if exists Employee ");
            onCreate(db);
        }
     //Inserting data in employee table
        public void InsertEmp (String Empname, String phone, String Email, String title)
        {
            ContentValues roww = new ContentValues();
            //roww.put("Id",empID );
            roww.put("name", Empname);
            roww.put("Title", title);
            roww.put("phone", phone);
            roww.put("Email", Email);

            EmpDept = getWritableDatabase();
            EmpDept.insert("Employee ", null, roww);
            EmpDept.close();
        }
  //Inserting data in department table
        public void InsertDept(String Deptname)
        {
            ContentValues row = new ContentValues();
            //row.put("Id", DeptID);
            row.put("name", Deptname);
            EmpDept = getWritableDatabase();
            EmpDept.insert("department ", null, row);
            EmpDept.close();
        }

        public Cursor GetEmpname(String namee)
        {
            EmpDept = getReadableDatabase();
            String[] arg = {namee};
            Cursor cur = EmpDept.rawQuery("select name from employee where name like ?;", new String[]{"%"+namee+"%"});
            cur.moveToFirst();
            EmpDept.close();
            return cur;
        }


        public Cursor Fetchallemployee() {
            EmpDept = getReadableDatabase();
            String[] rowdetails = {"name"};
            Cursor cursor = EmpDept.query("employee", rowdetails, null
                    , null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
            }
            EmpDept.close();
            return cursor;
        }


//Selecting employee name, title, phone, email by inputting employee ID

 public Cursor getEmpData(Integer employeeID)
        {
            EmpDept = getReadableDatabase();
           // String[] empRow = {"name", "title", "phone", "Email"};
            //String[] arg = {name, title, phone, email};
            Integer[] empRow = {employeeID};
            //Cursor c = EmpDept.query("Employee", empRow, null, null, null, null, null);
            Cursor c = EmpDept.rawQuery("Select name, Title, phone, email from Employee where EmpID like ?", new String[]{employeeID.toString()});
            if (c != null)
            {
                c.moveToFirst();
            }
            EmpDept.close();
            return c;
        }

//Selecting department name by inputting department ID

public Cursor getDeptName(Integer departmentID)
        {
            EmpDept = getReadableDatabase();
            Integer[] deptRow = {departmentID};
            //Cursor cr = EmpDept.rawQuery("Select name from department d inner join Employee e on d.DeptID = e.DeptID where e.name like ?",new String[]{deptartmentID.toString()});
            Cursor cr = EmpDept.rawQuery("Select name from department where DeptID like ?",new String[]{departmentID.toString()});
            if (cr != null)
            {
                cr.moveToFirst();
            }
            EmpDept.close();
            return cr;

        }
    }
}
Posted
Updated 20-Aug-19 11:33am
Comments
David Crow 26-Nov-18 23:10pm    
Have you considered asking this (lengthy) question in the actual Android forum? This "quick answers" section is for much shorter questions, and even shorter answers.

For brevity, consider something like:

class EmpInfo
{
    String name;
    String title;
    String phone;
    String email;
    String dept;
}
...
ArrayAdapter<EmpInfo> nameAdapter = new ArrayAdapter<EmpInfo>(...);
...
while (! cur.isAfterLast())
{
    String name = cur.getString(0);
    String title = cur.getString(1);
    String phone = cur.getString(2);
    String email = cur.getString(3);
    String dept = cur.getString(4);
    nameAdapter.add(new EmpInfo(name, title, phone, email, dept));
    cur.moveToNext();
}
...
Intent i = new Intent(MainActivity.this, empDetails.class);
EmpInfo empInfo = nameAdapter.getItem(position);
i.putExtra("empName", empInfo.name);
i.putExtra("empTitle", empInfo.title);
i.putExtra("empPhone", empInfo.phone);
i.putExtra("empEmail", empInfo.email);
i.putExtra("empDept", empInfo.dept);

1 solution

If using a ListView, rather than trying to build multiple arrays to access stored values or utilising objects such as an Employee object, utilising a CursorAdapter can be much simpler.

The one complication (simply overcome) is that a Cursor Adapter requires a specific column named _id and that the column contains an integer value that should uniquely identify a row that is listed. This value is passed to the onItemClick and onItemLongClick events as the 4th parameter (*note although a value is passed for ArrayAdapters that value is the same as the position but as a long*), additionally the underlying Cursor is positioned at the respective row so all the data for the selected row is easily obtained.

SimpleCursorAdapter is as it says a CursorAdapter that is easy to use.

Even with a custom layout as the 4th a 5th parameters are the column names (as a String array) from which the data to be displayed is extracted and the respective id of the view into which the data is displayed (the example uses the name column as the source data for the list which is displayed in the layout who's id is the text1 view).

As such I'd suggest considering the following working example that is an adaptation of your code.

DeptDBHelper.java (simplified but importantly gets _id column for Cursor Adapter)

public class DeptDPHelper extends SQLiteOpenHelper {
    SQLiteDatabase EmpDept;

    public DeptDPHelper(Context context) {
        super(context, "EmpDept", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db)
    {
        db.execSQL("create table department(DeptID integer primary key autoincrement , name text);");
        db.execSQL("create table Employee (EmpID integer primary key autoincrement , name text not null," +
                "Title text not null , phone text not null , email text not null ," +
                "DeptID integer, foreign key(DeptID) references department (DeptID))");

        //ContentValues row = new ContentValues();
        //db.execSQL("insert into Employee (EmpID , name , Title , phone , email ) values ('Ahmemhmmd' , '010224455' , 'gg@jj.com' , 'xx')");

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists department ");
        db.execSQL("drop table if exists Employee ");
        onCreate(db);
    }
    //Inserting data in employee table
    public void InsertEmp (String Empname, String phone, String Email, String title)
    {
        ContentValues roww = new ContentValues();
        //roww.put("Id",empID );
        roww.put("name", Empname);
        roww.put("Title", title);
        roww.put("phone", phone);
        roww.put("Email", Email);

        EmpDept = getWritableDatabase();
        EmpDept.insert("Employee ", null, roww);
        //EmpDept.close(); 
    }
    //Inserting data in department table
    public void InsertDept(String Deptname)
    {
        ContentValues row = new ContentValues();
        //row.put("Id", DeptID);
        row.put("name", Deptname);
        EmpDept = getWritableDatabase();
        EmpDept.insert("department ", null, row);
        //EmpDept.close(); // No need to close database - it's inefficient
    }

    /**
     * *********** This is all that you need to resolve your current issue
     */
    public Cursor getEmployeeData(String namee) {
        EmpDept = this.getWritableDatabase();
        return EmpDept.query(
                "employee",
                new String[]{
                        "*", //<<<<<<<<<< get all columns as you want all data eventually
                        "EmpID AS " + BaseColumns._ID //<<<<<<<<<< add column _id (copy of the EmpID) for CursorAdapter
                },
                "name LIKE ?",
                new String[]{"%" + namee + "%"},
                null,null,null
        );
    }

    //Selecting department name by inputting department ID

    // Mush simpler to just return the Cursor directly
    public Cursor getDeptName(Integer departmentID)
    {
        EmpDept = getReadableDatabase();
        Integer[] deptRow = {departmentID};
        //Cursor cr = EmpDept.rawQuery("Select name from department d inner join Employee e on d.DeptID = e.DeptID where e.name like ?",new String[]{deptartmentID.toString()});
        return EmpDept.rawQuery("Select name from department where DeptID like ?",new String[]{departmentID.toString()});
        /*
        if (cr != null) // A Cursor will never be null when returned from an SQLitedatabase method, checking for null is useless
        {
            cr.moveToFirst();
        }
        EmpDept.close(); //closing database will make returned cursor unusable
        return cr;
        */
    }
}


MainActivity.java (uses SimpleCursorAdapter)

public class MainActivity extends Activity {

    EditText name; //Textbox to input name
    SimpleCursorAdapter nameAdapter; //<<<<<<<<<< CHANGED
    DeptDPHelper Emp;  //Database object
    Cursor csr; //<<<<<<<<<< ADDED

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Emp = new DeptDPHelper(this);
        addDataIfNone(); //<<<<<<<<< Add the data (just once)
        final Button Search = (Button) findViewById(R.id.Search);
        name = (EditText) findViewById(R.id.name);
        final ListView namelist = (ListView) findViewById(R.id.LV);

        //nameAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1);
        csr = Emp.getEmployeeData(name.getText().toString());
        nameAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,csr,new String[]{"name"},new int[]{android.R.id.text1},0);
        namelist.setAdapter(nameAdapter);
        namelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String empName = csr.getString(csr.getColumnIndex("name"));
                String empTitle = csr.getString(csr.getColumnIndex("Title"));
                String empPhone = csr.getString(csr.getColumnIndex("phone"));
                String empEmail = csr.getString(csr.getColumnIndex("email"));
                //Note theorectically you should always get id's as long (rather than int) as they can be up to 64bit signed
                long empDept = csr.getLong(csr.getColumnIndex("DeptID"));
                Toast.makeText(view.getContext(),"You clicked on the Employee with an ID of " + String.valueOf(id) +
                                " Name is " + empName + " Title is " + empTitle + " Phone is " + empPhone + " Email is " + empEmail + " DeptID is " + String.valueOf(empDept),
                        Toast.LENGTH_SHORT).show();
                /* you would use 
                Intent i = new Intent(MainActivity.this, empDetails.class);
                i.putExtra("empName",empName );
                i.putExtra("empTitle",empTitle);
                i.putExtra("empPhone",empPhone);
                i.putExtra("empEmail",csr.getString(csr.getColumnIndex("email"))); // or get the data directly
                i.putExtra("empDept",csr.getLong(csr.getColumnIndex("DeptID")));
                startActivity(i);
                */
            }
        });
        //Filling tables moved

        //When clicking on the search button
        Search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                csr = Emp.getEmployeeData(name.getText().toString());
                nameAdapter.swapCursor(csr);
            }
        });
    }

    /**
     * Add data if no data already exists
     */
    private void addDataIfNone() {
        if (DatabaseUtils.queryNumEntries(Emp.getWritableDatabase(),"employee") > 0) return;
        Emp.InsertEmp("AhmedMhmmd", "010224455", "gg@jj.com", "xx");
        Emp.InsertEmp("MhmmdMhmoud", "010224455", "gg@jj.com", "xx");
        Emp.InsertEmp("Ahmedxxx", "010224455", "gg@jj.com", "xx");
        Emp.InsertDept("Finance");
        Emp.InsertDept("Sales");
    }
}


When first run, the App list's the 3 items.
Clicking on an item Toast's all the details EmpID, name, title, phone, email, DeptID.
Typing in the Search and clicking the search button refreshes the list according to the text entered (e.g. x will just display 1 row, q will show no rows, A or a will show 2 rows).
 
Share this answer
 
v4
Comments
Graeme_Grant 20-Aug-19 22:53pm    
5'ed ... was going to be my answer, well done!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900