单击列表视图中的项目时,Android应用程序崩溃

问题描述:

我的应用程序执行以下操作:

My app does the following:

-输入员工姓名,单击搜索按钮。

-Enter name of employee, click search button.

-结果是匹配名称的列表。

-List of matching names as a result.

-单击结果名称之一。

-新活动会打开,并显示单击的名称,标题,电话和电子邮件数据。

-A new activity opens with the clicked name, its title, phone, email data shown.

但是,当我单击结果名称之一时,我的应用程序崩溃了,没有任何错误。

However my app crashes when i click one of the resulted names, it shows no errors.

这是我到目前为止所做的。

This is what i have done so far.

    public class MainActivity extends Activity
    {    
    EditText name;
    ArrayAdapter<String> nameAdapter;
    DeptDPHelper Emp;

    @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());
        //Inserting some data into database
        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");
        //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();
                }
            }
        });
            //When clicking a name from the list of results.
          namelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View view, int position, long id)
              {
                  String name = namelist.getItemAtPosition(position).toString(); //get the name
                  Cursor empID = Emp.getEmpID(name);  //pass the name to a method to get its ID
                  Cursor DepID = Emp.getDeptID(name);
                  empID.moveToFirst();
                  DepID.moveToFirst();
                  int eID = empID.getInt(0); //Converting ID into Integer
                  int dID = DepID.getInt(0);


                  Intent intent = new Intent(MainActivity.this, empDetails.class);
                  intent.putExtra("empName", Emp.getEmpData(eID).toString()); //getting value of name using ID
                  intent.putExtra("empTitle",Emp.getEmpData(eID).toString());
                  intent.putExtra("empPhone",Emp.getEmpData(eID).toString());
                  intent.putExtra("empEmail",Emp.getEmpData(eID).toString());
                  intent.putExtra("empDept",Emp.getDeptName(dID).toString());
                  startActivity(intent);
              }
          });
    }
  //SQLITE Part
    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);
        }

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

        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;
        }
        //This method in order to get the employee id using the clicked name
        public Cursor getEmpID(String nameList)
        {
            EmpDept = getReadableDatabase();
            String[] rowID = {nameList};
            Cursor cursor = EmpDept.rawQuery("select EmpID from Employee where name like ?",rowID);
            EmpDept.close();
            if (cursor != null)
            {
                cursor.moveToFirst();
            }
            return cursor;
        }
        public Cursor getDeptID(String nameList)
        {
            EmpDept = getReadableDatabase();
            String[] rowwID = {nameList};
            Cursor curr = EmpDept.rawQuery("select DeptID from department inner join Employee on department.DeptID = Employee.DeptID where Employee.name like ? ",rowwID);
            //department d inner join Employee e on d.DeptID = e.DeptID where e.name like ?
            if (curr != null)
            {
                curr.moveToFirst();
            }
            EmpDept.close();
            return curr;
        }
    //This method for returning employee data using employee id as an input
        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;
        }
        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;

        }
    }
}

当我输入名称,然后单击搜索按钮,它会起作用,并且会显示名称列表,但是当我单击其中一个名称时,它会崩溃。

When i enter a name and i click the search button, it works and i get list of names, however when i click one of the names, it crashes.

出了什么问题

这是我的日志:

11-27 04:39:48.835 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:39:48.835 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:39:58.905 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:39:58.905 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:08.975 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:08.975 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:09.665 704-1339/? E/Watchdog: !@Sync 6712 [11-27 04:40:09.670]
11-27 04:40:10.695 13974-13989/? E/ContactsProvider_EventLog: Flush buffer to file cnt : 1 size : 0Kb duration : 1ms lastUpdatedAfter : 60117 ms mFlush_time_threasold : 2000 mCurrentSize : 294
11-27 04:40:19.045 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:19.045 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:21.025 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.025 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.275 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.315 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.315 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.315 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.435 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.435 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.495 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.595 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.655 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.705 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.775 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.775 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.895 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:21.955 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:22.015 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:22.035 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:22.035 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:22.045 220-225/? E/Tzdaemon: [w2] pthread_setaffinity_np() failed: 22
11-27 04:40:29.095 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:712,format:0
11-27 04:40:29.095 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:712,format:0
11-27 04:40:30.465 3733-3733/? E/AffinityControl: AffinityControl: registerfunction enter
11-27 04:40:39.175 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:39.175 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:39.235 2767-2767/? E/MtpServerJNI: server is null in send_object_removed
11-27 04:40:39.665 704-1339/? E/Watchdog: !@Sync 6713 [11-27 04:40:39.672]
11-27 04:40:49.245 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:49.245 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:59.315 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:40:59.315 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:09.385 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:09.385 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:09.665 704-1339/? E/Watchdog: !@Sync 6714 [11-27 04:41:09.673]
11-27 04:41:10.825 13974-13989/? E/ContactsProvider_EventLog: Flush buffer to file cnt : 1 size : 0Kb duration : 2ms lastUpdatedAfter : 60131 ms mFlush_time_threasold : 2000 mCurrentSize : 294
11-27 04:41:19.465 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:19.465 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:29.535 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:29.535 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:29.775 704-876/? E/MARsDBManager: updateDBAll : begin --size 1
11-27 04:41:29.815 704-876/? E/MARsDBManager: updateDBAll : end
11-27 04:41:39.605 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:39.605 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:39.665 704-1339/? E/Watchdog: !@Sync 6715 [11-27 04:41:39.674]
11-27 04:41:49.675 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:49.675 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:59.745 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:41:59.745 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:09.665 704-1339/? E/Watchdog: !@Sync 6716 [11-27 04:42:09.675]
11-27 04:42:09.815 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:09.815 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:10.955 13974-13989/? E/ContactsProvider_EventLog: Flush buffer to file cnt : 1 size : 0Kb duration : 3ms lastUpdatedAfter : 60123 ms mFlush_time_threasold : 2000 mCurrentSize : 294
11-27 04:42:19.895 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:19.895 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:29.965 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:29.965 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:38.625 1547-32615/? E/Places: ?: Exceeded maximum network back off time, fetching nearby places failed with status: 7
11-27 04:42:39.665 704-1339/? E/Watchdog: !@Sync 6717 [11-27 04:42:39.676]
11-27 04:42:40.035 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:40.035 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:50.105 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:42:50.105 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:00.175 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:00.175 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:09.675 704-1339/? E/Watchdog: !@Sync 6718 [11-27 04:43:09.678]
11-27 04:43:10.245 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:10.245 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:11.065 13974-13989/? E/ContactsProvider_EventLog: Flush buffer to file cnt : 1 size : 0Kb duration : 1ms lastUpdatedAfter : 60110 ms mFlush_time_threasold : 2000 mCurrentSize : 294
11-27 04:43:20.315 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:20.315 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:30.395 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:30.395 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:39.675 704-1339/? E/Watchdog: !@Sync 6719 [11-27 04:43:39.679]
11-27 04:43:40.465 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:40.465 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:50.535 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:43:50.535 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:00.605 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:00.605 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:09.675 704-1339/? E/Watchdog: !@Sync 6720 [11-27 04:44:09.680]
11-27 04:44:10.675 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:10.675 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:11.185 13974-13989/? E/ContactsProvider_EventLog: Flush buffer to file cnt : 1 size : 0Kb duration : 1ms lastUpdatedAfter : 60116 ms mFlush_time_threasold : 2000 mCurrentSize : 294
11-27 04:44:20.745 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:20.745 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:30.815 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:30.815 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:39.675 704-1339/? E/Watchdog: !@Sync 6721 [11-27 04:44:39.681]
11-27 04:44:40.895 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:40.895 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:50.965 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:44:50.965 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:45:01.035 326-1009/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0
11-27 04:45:01.035 217-291/? E/NetlinkEvent: NetlinkEvent::decode(): buffer'change@/devices/battery/power_supply/battery' size:713,format:0

这是我的empDetails活动代码:

Here is my empDetails Activity code:

public class empDetails extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emp_details);
        TextView name = (TextView)findViewById(R.id.textView7);
        TextView title = (TextView)findViewById(R.id.textView8);
        TextView phone = (TextView)findViewById(R.id.textView9);
        TextView email = (TextView)findViewById(R.id.textView10);
        TextView dept = (TextView)findViewById(R.id.textView11);
        name.setText(getIntent().getExtras().getString("empName"));
        title.setText(getIntent().getExtras().getString("empTitle"));
        phone.setText(getIntent().getExtras().getString("empPhone"));
        email.setText(getIntent().getExtras().getString("empEmail"));
        dept.setText(getIntent().getExtras().getString("empDept"));

    }
}

当我调试时,调试器部分显示没什么,控制台部分的内容显示如下:

When i debug, debugger section shows nothing, part of the console section shows this:

    --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.fatma.assgnment004, PID: 2580
    java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
        at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked(SQLiteConnectionPool.java:962)
        at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:599)
        at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:348)
        at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:894)
        at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:834)
        at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62)
        at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:143)
        at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:132)
        at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:219)
        at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:258)
        at com.example.fatma.assgnment004.MainActivity$DeptDPHelper.getEmpID(MainActivity.java:182)
        at com.example.fatma.assgnment004.MainActivity$2.onItemClick(MainActivity.java:77)
        at android.widget.AdapterView.performItemClick(AdapterView.java:310)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1156)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3121)
        at android.widget.AbsListView.onTouchUp(AbsListView.java:4048)
        at android.widget.AbsListView.onTouchEvent(AbsListView.java:3807)
        at android.view.View.dispatchTouchEvent(View.java:10023)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2626)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2307)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2632)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2632)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2632)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
        at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2632)
        at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2321)
        at com.android.internal.policy.DecorView.superDispatchTouchEvent(DecorView.java:413)
        at com.android.internal.policy.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1808)
        at android.app.Activity.dispatchTouchEvent(Activity.java:3061)
        at com.android.internal.policy.DecorView.dispatchTouchEvent(DecorView.java:375)
        at android.view.View.dispatchPointerEvent(View.java:10243)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4438)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4306)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3853)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3906)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3872)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3999)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3880)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4056)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3853)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3906)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3872)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3880)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3853)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6246)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6220)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6181)
        at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6349)
E/AndroidRuntime:     at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
        at android.os.MessageQueue.nativePollOnce(Native Method)
        at android.os.MessageQueue.next(MessageQueue.java:323)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:6119)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Disconnected from the target VM, address: 'localhost:8647', transport: 'socket'


编辑


已添加到问题的一行显示为

Edited

The stack-trace that has been added to the question has a line that says


java.lang.IllegalStateException:由于连接池已关闭,无法执行此操作。

这是说连接(可能有一个数字,因此连接池)已关闭。该连接是与数据库的连接。 It is closed because you have specifically closed it using EmpDept.close().

This is saying that the connection(s as there may be a number, hence the connection pool) has been closed. The connection being the connection(s) to the database. It is closed because you have specifically closed it using EmpDept.close().

When a Cursor is created, it doesn’t actually contain the data, rather it reads the data from the database when that data is needed. If the database has been closed then it cannot get the data.

When a Cursor is created, it doesn't actually contain the data, rather it reads the data from the database when that data is needed. If the database has been closed then it cannot get the data.

e.g. you have :-

e.g. you have :-

        cur.moveToFirst();
        EmpDept.close(); //<<<<<<<<<< Database connection closed
        return cur;

In short you cannot close the database connection and then access data in the Cursor.

In short you cannot close the database connection and then access data in the Cursor.

Here’s a complete working solution that doesn’t include the above flaw nor other flaws (some indicated by comments).

Here's a complete working solution that doesn't include the above flaw nor other flaws (some indicated by comments).

First a new Class named Employee in Employee.java

First a new Class named Employee in Employee.java

public class Employee {

    private long employeeId;
    private String employeeName;
    private String employeeTitle;
    private String employeePhone;
    private String employeeEmail;
    private long employeeDeptId;
    private String employeeDeptName;

    public Employee(
            long id,
            String name,
            String title,
            String phone,
            String email,
            long deptid,
            String deptname
    ) {
        this.employeeId = id;
        this.employeeName = name;
        this.employeeTitle = title;
        this.employeePhone = phone;
        this.employeeEmail = email;
        this.employeeDeptId = deptid;
        this.employeeDeptName = deptname;
    }

    public Employee() {
        this(-1L,"","","","",-1L,"");
    }

    public Employee(String name, String title, String phone, String email) {
        this(-1L,name,title,phone,email,-1L,"");
    }

    public long getEmployeeId() {
        return employeeId;
    }

    public void setEmployeeId(long employeeId) {
        this.employeeId = employeeId;
    }

    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }

    public String getEmployeeTitle() {
        return employeeTitle;
    }

    public void setEmployeeTitle(String employeeTitle) {
        this.employeeTitle = employeeTitle;
    }

    public String getEmployeePhone() {
        return employeePhone;
    }

    public void setEmployeePhone(String employeePhone) {
        this.employeePhone = employeePhone;
    }

    public String getEmployeeEmail() {
        return employeeEmail;
    }

    public void setEmployeeEmail(String employeeEmail) {
        this.employeeEmail = employeeEmail;
    }

    public long getEmployeeDeptId() {
        return employeeDeptId;
    }

    public void setEmployeeDeptId(long employeeDeptId) {
        this.employeeDeptId = employeeDeptId;
    }

    public String getEmployeeDeptName() {
        return employeeDeptName;
    }

    public void setEmployeeDeptName(String employeeDeptName) {
        this.employeeDeptName = employeeDeptName;
    }

    public boolean ifFullyUseableEmployee() {
         return this.employeeId < 1 || this.employeeDeptId < 1 || this.employeeDeptName.length() < 1;
    }

    @Override
    public String toString() {
        return this.employeeTitle + " " + this.employeeName;
    }
}

A perhaps new class for the DatabaseHelper namely DeptDPhelper.java

A perhaps new class for the DatabaseHelper namely DeptDPhelper.java

public class DeptDPHelper extends SQLiteOpenHelper {

    SQLiteDatabase EmpDept;

    //<<<<<<<<<< BAD PRACTICE TO HARD CODE TABLE AND COLUMN NAMES THROUGHOUT >>>>>>>>>>
    //<<<<<<<<<< INSTEAD USE CONSTANTS                                       >>>>>>>>>>>

    public static final String DBNAME = "EmpDept";
    public static final int DBVERSION = 2;
    public static final String DEPARTMENT_TABLE = "department";
    public static final String EMPLOYEE_TABLE = "employee"; //<<<<<<<<<< not Employee to be consistent with naming connvention

    public static final String DEPARTMENT_DEPTID_COLUMN = "departmenttid";
    public static final String DEPARTMENT_NAME_COLUMN = "departmentname";

    public static final String EMPLOYEE_EMPID_COLUMN = "employeeid";
    public static final String EMPLOYEE_NAME_COLUMN = "employeename";
    public static final String EMPLOYEE_TITLE_COLUMN= "employeetitle";
    public static final String EMPLOYEE_PHONE_COLUMN = "employeephone";
    public static final String EMPLOYEE_EMAIL_COLUMN = "employeeemail";
    public static final String EMPLOYEE_DEPT_COLUMN = "employeeedepartmentid";

    public DeptDPHelper(Context context) {
        super(context, DBNAME, null, DBVERSION);
        EmpDept = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crt_dept_table_sql = "CREATE TABLE IF NOT EXISTS " + DEPARTMENT_TABLE + "(" +
                DEPARTMENT_DEPTID_COLUMN + " INTEGER PRIMARY KEY, " + //<<<<<<<<<< AUTOINCREMENT INEFFICIENT NOT NEEDED
                DEPARTMENT_NAME_COLUMN + " TEXT" +
                ")";
        db.execSQL(crt_dept_table_sql);

        String crt_employee_table_sql = "CREATE TABLE IF NOT EXISTS " + EMPLOYEE_TABLE + "(" +
                EMPLOYEE_EMPID_COLUMN + " INTEGER PRIMARY KEY, " +
                EMPLOYEE_NAME_COLUMN + " TEXT NOT NULL, " +
                EMPLOYEE_TITLE_COLUMN + " TEXT NOT NULL, " +
                EMPLOYEE_PHONE_COLUMN + " TEXT NOT NULL, " +
                EMPLOYEE_EMAIL_COLUMN + " TEXT NOT NULL, " +
                EMPLOYEE_DEPT_COLUMN + " INTEGER REFERENCES " + DEPARTMENT_TABLE + "(" +
                DEPARTMENT_DEPTID_COLUMN +
                ")" +
                ")";
        db.execSQL(crt_employee_table_sql);
    }

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

        //<<<<<<<<<< IF USING FOREIGN KEYS AND SUPPORT IS ON THEN CANNOT DELETE PARENT TABLE FIRST >>>>>>>>>>
        //<<<<<<<<<< AS SUCH DEPARTMENT TABLE MUST BE DROPPED FIRST OTHEWISE THERE WILL BE CONFLICTS >>>>>>>>>>
        db.execSQL("DROp TABLE IF EXISTS " + EMPLOYEE_TABLE);
        db.execSQL("DROP TABLE IF EXISTS " + DEPARTMENT_TABLE);
        onCreate(db);
    }

    //<<<<<<<<<< FOREIGN KEY SUPPORT IS TUREND OFF BY DEFAULT SO TURN THEM ON >>>>>>>>>>
    //<<<<<<<<<< IF NOT USELESS CODING FOREIGN KEYS                           >>>>>>>>>>
    @Override
    public void onConfigure(SQLiteDatabase db) {
        db.setForeignKeyConstraintsEnabled(true);
        super.onConfigure(db);
    }

    public long insertEmployee(String name, String title, String phone, String email, long deptid) {
        //<<<<<<<<<< optional check if deptid references a deptartment >>>>>>>>>>
        //<<<<<<<<<< however INSERT OR IGNORE doesn't ignore FK conflicts >>>>>>>>>>
        if (!ifDepertmentExists(deptid)) return -1;

        ContentValues cv = new ContentValues();
        cv.put(EMPLOYEE_NAME_COLUMN,name);
        cv.put(EMPLOYEE_TITLE_COLUMN,title);
        cv.put(EMPLOYEE_PHONE_COLUMN,phone);
        cv.put(EMPLOYEE_EMAIL_COLUMN,email);
        cv.put(EMPLOYEE_DEPT_COLUMN,deptid);
        return EmpDept.insert(EMPLOYEE_TABLE,name,cv);
    }

    public long insertDepartment(String name) {
        ContentValues cv = new ContentValues();
        cv.put(DEPARTMENT_NAME_COLUMN,name);
        return EmpDept.insert(DEPARTMENT_TABLE,null,cv);
    }

    public Cursor selectLikeEmployeesByNamePart(String namepart) {
        String[] columns = new String[]{EMPLOYEE_NAME_COLUMN};
        String whereclause = EMPLOYEE_NAME_COLUMN + "LIKE ?";
        String[] whereargs = new String[] {"%" + namepart +"%"};
        return EmpDept.query(EMPLOYEE_TABLE,columns,whereclause,whereargs,null,null,EMPLOYEE_NAME_COLUMN);
    }

    public ArrayList<Employee> getAllEmployees(String namepart) {
        ArrayList<Employee> employees = new ArrayList<>();
        String whereclause = null;
        String[] wherargs = null;
        if (namepart != null && namepart.length() > 0) {
            whereclause = EMPLOYEE_NAME_COLUMN + " LIKE ?";
            wherargs = new String[]{"%" + namepart + "%"};
        }
        Cursor csr = EmpDept.query(EMPLOYEE_TABLE + " JOIN " + DEPARTMENT_TABLE + " ON " + EMPLOYEE_DEPT_COLUMN + "=" + DEPARTMENT_DEPTID_COLUMN,
                    null,whereclause, wherargs, null, null, EMPLOYEE_NAME_COLUMN + "," + EMPLOYEE_DEPT_COLUMN);
        while (csr.moveToNext()) {
            employees.add( new Employee(
                    csr.getLong(csr.getColumnIndex(EMPLOYEE_EMPID_COLUMN)),
                    csr.getString(csr.getColumnIndex(EMPLOYEE_NAME_COLUMN)),
                    csr.getString(csr.getColumnIndex(EMPLOYEE_TITLE_COLUMN)),
                    csr.getString(csr.getColumnIndex(EMPLOYEE_PHONE_COLUMN)),
                    csr.getString(csr.getColumnIndex(EMPLOYEE_EMAIL_COLUMN)),
                    csr.getLong(csr.getColumnIndex(DEPARTMENT_DEPTID_COLUMN)),
                    csr.getString(csr.getColumnIndex(DEPARTMENT_NAME_COLUMN)))
            );
        }
        csr.close();
        return employees;
    }


    private boolean ifDepertmentExists(long deptid) {
        String wherecluase = DEPARTMENT_DEPTID_COLUMN + "=?";
        String[] whereargs = new String[]{String.valueOf(deptid)};
        Cursor csr =EmpDept.query(DEPARTMENT_TABLE,null,wherecluase,whereargs,null,null,null);
        int rowcount = csr.getCount();
        csr.close();
        return rowcount > 0;
    }
}



  • Some comments have been added, which should explain some things.

  • The empDetails Activity namely empDetails.java

    The empDetails Activity namely empDetails.java

public class empDetails extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emp_details);
        TextView name = (TextView)findViewById(R.id.textview7);
        TextView title = (TextView)findViewById(R.id.textview8);
        TextView phone = (TextView)findViewById(R.id.textview9);
        TextView email = (TextView)findViewById(R.id.textview10);
        TextView dept = (TextView)findViewById(R.id.textview11);
        Button mDoneButton = this.findViewById(R.id.donebutton);
        mDoneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        name.setText(getIntent().getExtras().getString(DeptDPHelper.EMPLOYEE_NAME_COLUMN));
        title.setText(getIntent().getExtras().getString(DeptDPHelper.EMPLOYEE_TITLE_COLUMN));
        phone.setText(getIntent().getExtras().getString(DeptDPHelper.EMPLOYEE_PHONE_COLUMN));
        email.setText(getIntent().getExtras().getString(DeptDPHelper.EMPLOYEE_EMAIL_COLUMN));
        dept.setText(getIntent().getExtras().getString(DeptDPHelper.DEPARTMENT_NAME_COLUMN));
    }
}

And lastly MainActivity.java

And lastly MainActivity.java

public class MainActivity extends AppCompatActivity {

    DeptDPHelper mDBHlpr;
    ArrayList<Employee> mEmployeeList;
    ArrayAdapter mNameAdapter;
    ListView namelist;
    EditText mNamePart;
    TextWatcher mTW;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        namelist = this.findViewById(R.id.namelist);
        mNamePart = this.findViewById(R.id.searchbar);
        mDBHlpr = new DeptDPHelper(this);
        addSomeData();
        setupOrRefreshNameList();
        setupSearch();
    }

    private void setupOrRefreshNameList() {
        String namepart = mNamePart.getText().toString();
        if (namepart.length() < 1) namepart = null;
        if (mEmployeeList != null) {
            mEmployeeList.clear();
            ArrayList<Employee> el = mDBHlpr.getAllEmployees(namepart);
            mEmployeeList.addAll(el);
        } else {
            mEmployeeList = mDBHlpr.getAllEmployees(namepart);
        }
        if (mNameAdapter == null) {
            mNameAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mEmployeeList);
            namelist.setAdapter(mNameAdapter);
            setupListViewListeners();
        } else {
            mNameAdapter.notifyDataSetChanged();
        }
    }

    //<<<<<<<<<< For testing >>>>>>>>>>
    private void addSomeData() {
        long dept1 = mDBHlpr.insertDepartment("Dept001");
        long dept2 = mDBHlpr.insertDepartment("Dept002");

        mDBHlpr.insertEmployee("Fred","Mr.","1234567890","fred.x.com",dept1);
        mDBHlpr.insertEmployee("Fred","Mr.","0987654321","fred@z.com",dept2);
        mDBHlpr.insertEmployee("Mary","Ms.","9999999999","mary@marymail.net",dept1);
        mDBHlpr.insertEmployee("Albert","Sir ", "1113334445","lord@roayls.org",dept1);
    }

    private void setupListViewListeners() {
        namelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Employee e = (Employee) mNameAdapter.getItem(i);
                Toast.makeText(
                        getApplicationContext(),
                        "You clicked on " +
                                e.getEmployeeTitle() + " " +
                                e.getEmployeeName() +
                                " ID=" + String.valueOf(e.getEmployeeId()) +
                                " Email=" + e.getEmployeeEmail() +
                                " Phone=" + e.getEmployeePhone() +
                                " Dept=" + e.getEmployeeDeptName()
                        ,
                        Toast.LENGTH_SHORT)
                        .show();
                Intent intent = new Intent(MainActivity.this,empDetails.class);
                intent.putExtra(DeptDPHelper.EMPLOYEE_NAME_COLUMN,e.getEmployeeName());
                intent.putExtra(DeptDPHelper.EMPLOYEE_EMPID_COLUMN,e.getEmployeeId());
                intent.putExtra(DeptDPHelper.EMPLOYEE_TITLE_COLUMN,e.getEmployeeTitle());
                intent.putExtra(DeptDPHelper.EMPLOYEE_PHONE_COLUMN,e.getEmployeePhone());
                intent.putExtra(DeptDPHelper.EMPLOYEE_EMAIL_COLUMN,e.getEmployeeEmail());
                intent.putExtra(DeptDPHelper.DEPARTMENT_NAME_COLUMN,e.getEmployeeDeptName());
                startActivity(intent);
            }
        });
    }

    private void setupSearch() {
        mTW = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            //<<<<<<<<<< Every time the text is changed refresh the ListView >>>>>>>>>>
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                setupOrRefreshNameList();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        };
        mNamePart.addTextChangedListener(mTW);
    }
}



  • Note this dynamically alters the list as you enter text into the EditText

    • Note this dynamically alters the list as you enter text into the EditText

      Note that the Mainifest includes <activity android:name=".empDetails"></activity>

      Note that the Mainifest includes <activity android:name=".empDetails"></activity>

      When first run you get :-

      When first run you get :-

      Entering A for example (note only applies to the name not the title part):-

      Entering A for example (note only applies to the name not the title part):-

      Clicking on Mary :-

      Clicking on Mary :-

      Done will r eturn to the MainActivity.

      Done will return to the MainActivity.