lundi 7 mars 2016

How to proceed if cursor is empty or null

I have a sqlite database which I want to query and retrieve some values if they exist, in case they don't exist make a toast.

For this porpoise I have the next code which will call a function to create the cursor and in case this is not empty it will retrieve the information in the edittext otherwise it will make a toast:

private String lookforelementID() {
// TODO Auto-generated method stub
     int ElementRequest=0;

     ElementRequest = Integer.parseInt(eTElementNumb.getText().toString());
     try{
         database db = new database(this);
         db.open();

         String passedReg = getIntent().getStringExtra(MainActivity.ID_STUDY);

            String returnedInfo1 = db.elementID(ElementRequest, passedReg, 0);

            if (returnedInfo1.matches("")){
                Toast.makeText(getApplicationContext(), "No Exist this Element", Toast.LENGTH_SHORT).show();
            }else{
                    eTIDElement.setText(returnedInfo1);
                String returnedInfo2 = db.elementID(ElementRequest, passedReg, 2);
                    eTElementCode.setText(returnedInfo2);
                String returnedInfo3 = db.elementID(ElementRequest, passedReg, 3);
                    eTElementDecription.setText(returnedInfo3);

            }

                db.close();
     }catch(ClassCastException e){
         e.printStackTrace();
     }
     eTElementNumb.setText(""); 
     return null;

}

The function with the cursor is as follows:

             public String elementID(int elementRequest, String idStudy, int i) {
            // TODO Auto-generated method stub
            String[] columns = new String[]{ KEY_ROWELEMENTID, KEY_STUDYID, KEY_ELEMENTCODE, KEY_ELEMENTNAME};
            Cursor c = ourDatabase.query(DATABASE_TABLEELEMENTS, columns, KEY_ELEMENTCODE + "=" + elementRequest + " AND " + KEY_STUDYID + "=" + idStudy, null, null, null, null);
            String ElementInformation = null;
            if(c != null){
                c.moveToFirst();
                ElementInformation = c.getString(i);     
            }
            return ElementInformation;
        }

Aucun commentaire:

Enregistrer un commentaire