2014-12-25 5 views
0

Я пытаюсь отобразить результат из базы данных в спискеView, который можно щелкнуть. При длинном щелчке элементы можно удалить и щелкнуть мышью по другому действию. Поэтому я создаю деятельность под названием editdeletedoctorОтобразить результаты в ListView из базы данных

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

Пожалуйста, помогите мне.

Спасибо

+0

Пожалуйста, обратите внимание, что проблема в настоящее openAndQueryDatabase() метод – user3552658

ответ

0

Вы уверены, что «контекст» используется здесь не равно нулю? Как насчет того, чтобы переписать функцию open() так и позвонить через open(getApplicationContext());?

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

изменился :( – user3552658

+0

http://i60.tinypic.com/27y5y0n.png – user3552658

+0

Не могли бы вы фильтровать StackTrace только для вашего приложения или свитка бит вниз Кроме того, проблема NPE на самом деле решена, насколько я могу судить по вашему результату. У вас теперь есть другое исключение. –

Смежные вопросы