CRUD:我的SQLite实现上的`find()`函数永远不会被执行

时间:2016-02-14 16:33:33

标签: android sqlite android-sqlite crud

在一个拦截短信的小应用程序中,将它们保存在本地数据库中, 我正在尝试在我的DAO中实现一个find方法。

这是我的所有CRUD代码:

public class CSmsReceiverDAO implements IDAO<CSmsReceived> {
    private SQLiteDatabase bdd;
    private CMaBaseSQLite cMaBaseSQLite;
    private static final String NOM_BDD = "sms.db";
    private static final int VERSION_BDD = 1;

    private static final String COL_ID = "ID";
    private static final int NUM_COL_ID = 0;

    private static final String TABLE_SMS_SENT = "table_sms_sent";
    private static final String COL_DateSending = "dateSending";

    private static final String TABLE_SMS_RECEIVED = "table_sms_received";
    private static final String COL_DateReceiving = "dateReceiving";

    private static final int NUM_COL_DateReceiving = 1;

    private static final String COL_PROCESSED ="processed";
    private static final int NUM_COL_PROCESSED = 2;

    private static final String COL_PHONE ="phone";
    private static final int NUM_COL_PHONE= 3;

    private static final String COL_DATA ="data";
    private static final int NUM_COL_DATA= 4;


    public CSmsReceiverDAO(Context context){
        //On créer la BDD et sa table
        cMaBaseSQLite = new CMaBaseSQLite(context, NOM_BDD, null, VERSION_BDD);
    }

    public void open(){
        //on ouvre la BDD en écriture
        bdd = cMaBaseSQLite.getWritableDatabase();
    }

    public void close(){
        //on ferme l'accès à la BDD
        bdd.close();
    }

    public SQLiteDatabase getBDD(){
        return bdd;
    }

    @Override
    public CSmsReceived find(String date) throws Exception {
        //Récupère dans un Cursor les valeur correspondant à un livre contenu dans la BDD (ici on sélectionne le livre grâce à son titre)
        Cursor c = bdd.query(TABLE_SMS_RECEIVED, new String[] {COL_ID, COL_DateReceiving, COL_PROCESSED, COL_PHONE, COL_DATA}, COL_DateReceiving + " LIKE \"" + date +"\"", null, null, null, null);
        return cursorToSms(c);
    }

    @Override
    public List<CSmsReceived> findAll() throws Exception {
        return null;
    }

    @Override
    public void persist(CSmsReceived t) throws Exception {

        //Création d'un ContentValues (fonctionne comme une HashMap)
        ContentValues values = new ContentValues();
        //on lui ajoute une valeur associé à une clé (qui est le nom de la colonne dans laquelle on veut mettre la valeur)
        values.put(t.getDateReceiving(), NUM_COL_DateReceiving);
        values.put(t.getProcessed(), NUM_COL_PROCESSED);
        values.put(t.getPhone(), NUM_COL_PHONE);
        values.put(t.getData(), NUM_COL_DATA);

        //on insère l'objet dans la BDD via le ContentValues
        bdd.insert(TABLE_SMS_RECEIVED, null, values);
    }

    @Override
    public void remove(CSmsReceived t) throws Exception {

    }

    @Override
    public void update(CSmsReceived s, CSmsReceived t) throws Exception {

    }

    @Override
    public void refresh(CSmsReceived t) throws Exception {

    }

    //Cette méthode permet de convertir un cursor en un sms
    private CSmsReceived cursorToSms(Cursor c){
        //si aucun élément n'a été retourné dans la requête, on renvoie null
        if (c.getCount() == 0)
            return null;

        //Sinon on se place sur le premier élément
        c.moveToFirst();
        //On créé un sms
        //on lui affecte toutes les infos grâce aux infos contenues dans le Cursor
        CSmsReceived cSmsReceived = new CSmsReceived.SmsReceivedBuilder()
                .DateReceiving(c.getString(NUM_COL_DateReceiving))
                .Processed(c.getString(NUM_COL_PROCESSED)).Phone(c.getString(NUM_COL_PHONE))
                .Data(c.getString(NUM_COL_DATA)).build();
        //On ferme le cursor
        c.close();

        //On retourne le livre
        return cSmsReceived;
    }
}

我的Sql Base代码:

public class CMaBaseSQLite extends SQLiteOpenHelper {

    private static final String COL_ID = "ID";

    private static final String TABLE_SMS_SENT = "table_sms_sent";
    private static final String COL_DateSending = "dateSending";

    private static final String TABLE_SMS_RECEIVED = "table_sms_received";
    private static final String COL_DateReceiving = "dateReceiving";
    private static final String COL_PROCESSED ="processed";

    private static final String COL_PHONE ="phone";
    private static final String COL_DATA ="data";

    private static final String CREATE_BDD_SMS_RECEIVED = "CREATE TABLE " + TABLE_SMS_RECEIVED + " ("
            + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_DateReceiving + "TEXT, "
            + COL_PROCESSED + "TEXT, " + COL_PHONE + "TEXT, " + COL_DATA + "TEXT);";

    private static final String CREATE_BDD_SMS_SENT = "CREATE TABLE " + TABLE_SMS_SENT + " ("
            + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_DateSending + "TEXT, "
            + COL_PHONE + "TEXT, " + COL_DATA + "TEXT NOT NULL);";

    public CMaBaseSQLite(Context context, String name, CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //on créé la table à partir de la requête écrite dans la variable CREATE_BDD sent et received
        db.execSQL(CREATE_BDD_SMS_RECEIVED);
        //db.execSQL(CREATE_BDD_SMS_SENT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //On peut fait ce qu'on veut ici moi j'ai décidé de supprimer la table et de la recréer
        //comme ça lorsque je change la version les id repartent de 0
        //db.execSQL("DROP TABLE " + TABLE_SMS_SENT + ";");
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SMS_RECEIVED + ";");
        onCreate(db);
    }

这是我的活动:

CSmsReceiverDAO cSmsReceiverDAO = new CSmsReceiverDAO(this);
CSmsReceived SmsReceived1 = new CSmsReceived.SmsReceivedBuilder()
        .Data("coords XY").DateReceiving("janvier").Phone("+33565456").Processed("zz").build();

cSmsReceiverDAO.open();

try {
    Log.i("test","try ok");
    cSmsReceiverDAO.persist(SmsReceived1);
    Log.i("test", "persist ok");
    CSmsReceived smsFromBdd = cSmsReceiverDAO.find(SmsReceived1.getDateReceiving());
    Log.i("test", "find ok");

    if (smsFromBdd !=null){
        Toast.makeText(this, smsFromBdd.toString(), Toast.LENGTH_LONG).show();
    }
    else {
        Toast.makeText(this, "persist fail...", Toast.LENGTH_LONG).show();

    }

} catch (Exception e) {
    e.printStackTrace();
}

在我的日志中,从不执行find方法,但我不明白为什么。

02-14 17:25:09.460 7571-7571/com.dev.boblinux.cador I/test: try ok
02-14 17:25:09.470 7571-7571/com.dev.boblinux.cador I/test: persist ok

编辑:感谢Hrundi V. Bakshi

我的日志现在:

try ok persist ok find ok

但我的smsFromBdd上没有任何内容:

        `if (smsFromBdd !=null){
            Toast.makeText(this, smsFromBdd.toString(), Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(this, "persist fail...", Toast.LENGTH_LONG).show();

        }`

显示persist fail...

1 个答案:

答案 0 :(得分:2)

您不能将您的字段名称与其类型分开 因此,表格格式不正确 并且您的应用在执行cSmsReceiverDAO.find()

时正在中止

字段名称和字段类型之间需要空格

private static final String CREATE_BDD_SMS_RECEIVED = "CREATE TABLE " + TABLE_SMS_RECEIVED + " ("
        + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_DateReceiving + " TEXT, "
        + COL_PROCESSED + " TEXT, " + COL_PHONE + " TEXT, " + COL_DATA + " TEXT);";

private static final String CREATE_BDD_SMS_SENT = "CREATE TABLE " + TABLE_SMS_SENT + " ("
        + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_DateSending + " TEXT, "
        + COL_PHONE + " TEXT, " + COL_DATA + " TEXT NOT NULL);";

然后您需要卸载您的应用并重新运行它,以便重新创建数据库。