从数据库中显示ListView中的结果

时间:2014-12-25 13:01:28

标签: android listview android-sqlite

我正在尝试在listView中显示数据库中的结果,这是可点击的长按,项目可以删除,点击后可以转到另一个活动。所以我创建了一个名为editdeletedoctor

的活动
public class editdeletedoctor extends Activity {
    private ArrayList<String> results = new ArrayList<String>();
    private String tableName = TableData.TableInfo.TABLE_DOCTOR;
    private SQLiteDatabase newDB;
    private ArrayList<doctorClass> doctor_List = new ArrayList<doctorClass>();
    public static String MODEL_TO_EDIT = "MODEL_TO_EDIT";
    public ListView list;
    public ArrayAdapter<String> adapter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        init();
        openAndQueryDatabase();
        displayResultList();
    }

    private void init() {
        list = (ListView) findViewById(R.id.list);
        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Intent intent = new Intent(editdeletedoctor.this,
                        registerdoctor.class);
                intent.putExtra("theText", doctor_List.get(position).getUsername());
                intent.putExtra(editdeletedoctor.MODEL_TO_EDIT,doctor_List.get(position));
                editdeletedoctor.this.finish();
                startActivity(intent);
            }
        });

        list.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,
                    final int position, long id) {
                Builder dialog = new AlertDialog.Builder(editdeletedoctor.this);

                dialog.setTitle("Are you sure you want to delete This doctor?");

                dialog.setPositiveButton("Yes", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doctorClass doctor = doctor_List.get(position);
                        doctor_List.remove(position);

                        DatabaseOperations db = new DatabaseOperations(getApplicationContext());
                        try {

                            db.open();
                            HashMap<String, String> conditionKV = new HashMap<String, String>();
                            conditionKV.put(TableData.TableInfo.DOCTOR_ID, doctor.getId() + "");

                            db.deleteDoctor(conditionKV);
                            results.remove(position);
                            adapter.notifyDataSetChanged();
                        } catch (SQLiteException se) {
                            Log.e(getClass().getSimpleName(),
                                    "Could not create or Open the database");
                        } finally {
                            if (db != null)
                                db.close();

                        }

                        dialog.dismiss();
                    }
                });

                dialog.setNegativeButton("No", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

                dialog.show();
                return false;
            }
        });

    }

    private void displayResultList() {

        adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, results);
        list.setAdapter(adapter);
        list.setTextFilterEnabled(true);

    }

    private void openAndQueryDatabase() {
        DatabaseOperations db = new DatabaseOperations(getApplicationContext());
        try {

            db.open();
            doctor_List = db.getDoctor(null);
            for (doctorClass inc : doctor_List) {
                if(inc.getId()==TableData.TableInfo.userID)
                results.add("Name: " + inc.getUsername() + " Phone:"
                        + inc.getPhone() + ",Address: "
                        + inc.getAddress());
            }
        } catch (SQLiteException se) {
            Log.e(getClass().getSimpleName(),
                    "Could not create or Open the database");
        } finally {
            if (db != null)
                db.close();

        }
    }

}


And in the DatabaseOperations.java class :



    public DatabaseOperations open() throws SQLException {
            ourHelper = new DatabaseOperations(context);
            ourDatabase = ourHelper.getWritableDatabase();
            return this;
        }
        public void close() {
            ourHelper.close();
        }
        public ArrayList<doctorClass> getDoctor(HashMap<String, String> conditionKV) {
            Cursor m_cursor = get(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
            ArrayList<doctorClass> list = new ArrayList<doctorClass>();
            if (m_cursor.moveToFirst()) {
                do {
                    doctorClass model = new doctorClass();
                    if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)) != null)
                        model.setId(m_cursor.getInt(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ID)));
                    if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_NAME)) != null)
                        model.setUsername(m_cursor.getString(m_cursor
                                .getColumnIndex(TableData.TableInfo.DOCTOR_NAME)));
                    if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PASS)) != null)
                        model.setPassword(m_cursor.getString(m_cursor
                                .getColumnIndex(TableData.TableInfo.DOCTOR_PASS)));
                    if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)) != null)
                        model.setEmail(m_cursor.getString(m_cursor
                                .getColumnIndex(TableData.TableInfo.DOCTOR_MAIL)));
                    if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)) != null)
                        model.setPhone(m_cursor.getString(m_cursor
                                .getColumnIndex(TableData.TableInfo.DOCTOR_PHONE)));
                    if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)) != null)
                        model.setAddress(m_cursor.getString(m_cursor
                                .getColumnIndex(TableData.TableInfo.DOCTOR_ADDRESS)));
                    if (m_cursor.getString(m_cursor.getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)) != null)
                        model.setGender(m_cursor.getString(m_cursor
                                .getColumnIndex(TableData.TableInfo.DOCTOR_GENDER)));
                    list.add(model);
                } while (m_cursor.moveToNext());
            }// end if
            return list;
        }
        public Cursor get(String tableName, HashMap<String, String> conditionKV) {
            String whereClause = null;
            if (conditionKV != null)
                whereClause = formatWherecondition(conditionKV);
            String completeQuery = "SELECT * FROM " + tableName + " ";
            if (whereClause != null) {
                completeQuery += " WHERE " + whereClause;
            }
            return ourDatabase.rawQuery(completeQuery, null);
        }

        public String formatWherecondition(HashMap<String, String> conditionKV) {
            try {
                String result = "";
                if (conditionKV.size() < 1) {
                    throw new Exception("Hahsmap condition Empty");
                }
                Iterator l_iterator = conditionKV.keySet().iterator();
                boolean isOneField = false;
                while (l_iterator.hasNext()) {
                    String l_key = (String) l_iterator.next();
                    String l_value = conditionKV.get(l_key);
                    if (isOneField)
                        result = result + " AND ";
                    result = result + l_key + "='" + l_value + "' ";
                    isOneField = true;
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        public void deleteDoctor(HashMap<String, String> conditionKV) {
            delete(TableData.TableInfo.TABLE_DOCTOR, conditionKV);
        }

        private void delete(String tableName, HashMap<String, String> conditionKV) {
            String whereClause = null;
            if (conditionKV == null)
                return;
            whereClause = formatWherecondition(conditionKV);
            String completeQuery = "DELETE FROM " + tableName + " ";
            if (whereClause != null) {
                completeQuery += " WHERE " + whereClause;
                ourDatabase.execSQL(completeQuery);
            }
        }

运行时出现错误Here is the logcat

请帮帮我。

谢谢

1 个答案:

答案 0 :(得分:0)

你确定你在这里使用的“上下文”不是空的吗? 如何以这种方式重写open()函数并通过open(getApplicationContext());调用它?

 public DatabaseOperations open(Context context) throws SQLException {
                ourHelper = new DatabaseOperations(context);
                ourDatabase = ourHelper.getWritableDatabase();
                return this;
            }