【问题标题】:Display Results in ListView from Database从数据库的 ListView 中显示结果
【发布时间】:2014-12-25 13:01:28
【问题描述】:

我正在尝试在可单击的 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

请帮帮我。

谢谢

【问题讨论】:

  • 请注意问题出在 openAndQueryDatabase() 方法

标签: android listview android-sqlite


【解决方案1】:

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

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

【讨论】:

  • 能否请您仅为您的应用过滤 Stacktrace 或向下滚动一点此外,据我从您的输出中可以看出,NPE 的问题实际上已经解决。你现在有另一种例外。
  • 您能重新发布您最近的更改吗?
  • 在尝试您的解决方案并将其删除后显示此异常,因此代码仍然相同,问题出在 openAndQueryDatabase() 方法中,因为当我评论它时没有发生错误.. 希望你可以帮助我
  • 您自己发现任何错误的唯一可靠方法是使用日志语句并跟踪执行流程。此方法很有用,尤其是当您不想使用调试器时..
猜你喜欢
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-23
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
相关资源
最近更新 更多