0

I try to implemente an android application that receives sms and persist it in local dabase, here we'll use Sqlite,

in my main activity, i try to persist an sms, and then, i try to read it from my database, but i can't, le find() line is never executed (that what says my logs), here is some code of my main activity :

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();
        }

and my logs say :

02-19 07:19:23.087 2837-2837/? I/test: try ok
02-19 07:19:23.087 2837-2837/? I/test: persist ok

but i don't have line "find ok".

here is how i build my sms (i use builder pattern) :

public class CSmsReceived implements Serializable{
    private final String dateReceiving; // optional
    private final String processed; // optional
    private final String phone; // optional
    private final String data; // optional

    private CSmsReceived(SmsReceivedBuilder builder) {
        this.dateReceiving = builder.dateReceiving;
        this.processed = builder.processed;
        this.phone = builder.phone;
        this.data = builder.data;
    }

    public String getDateReceiving() {
        return dateReceiving;
    }

    public String getProcessed() {
        return processed;
    }

    public String getPhone() {
        return phone;
    }

    public String getData() {
        return data;
    }

    public String toString(){
        return "dateReceiving : " + dateReceiving + " processed : " + processed +"\n"
                + " phone : " + phone + " data : " + data;
    }

    public static class SmsReceivedBuilder {
        private String dateReceiving;
        private String processed;
        private String phone;
        private String data;

        public SmsReceivedBuilder Data(String data) {
            this.data = data;
            return this;
        }

        public SmsReceivedBuilder DateReceiving(String dateReceiving) {
            this.dateReceiving = dateReceiving;
            return this;
        }

        public SmsReceivedBuilder Phone(String phone) {
            this.phone = phone;
            return this;
        }

        public SmsReceivedBuilder Processed(String processed) {
            this.processed = processed;
            return this;
        }


        public CSmsReceived build() {
            return new CSmsReceived(this);
        }

    }
}

and here is my creation database : (connection and create tables)

edit : Try CREATE TABLE IF NOT EXISTS – @Prithviraj Shiroor but it changes nothing

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 IF NOT EXISTS " + 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 IF NOT EXISTS" + 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);
    }

}

and finally there is my smsDAO :

EDIT : persist method debuged

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);

=>

values.put(COL_DateReceiving,t.getDateReceiving());
        values.put(COL_PROCESSED, t.getProcessed());
        values.put(COL_PHONE, t.getPhone());
        values.put(COL_DATA, t.getData());

now my code :

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(COL_DateReceiving,t.getDateReceiving());
        values.put(COL_PROCESSED, t.getProcessed());
        values.put(COL_PHONE, t.getPhone());
        values.put(COL_DATA, t.getData());

        //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;
    }
}

so why my find method doesn't work ?

like @Elite says, log cat can be interesting (log updated) :

02-19 08:12:29.568 8463-8463/? I/art: Not late-enabling -Xcheck:jni (already on)
02-19 08:12:29.592 8463-8463/? W/System: ClassLoader referenced unknown path: /data/app/com.dev.boblinux.cador-1/lib/x86
02-19 08:12:29.592 8463-8471/? E/art: Failed writing handshake bytes (-1 of 14): Broken pipe
02-19 08:12:29.592 8463-8471/? I/art: Debugger is no longer active
02-19 08:12:29.599 8463-8463/? I/GMPM: App measurement is starting up, version: 8487
02-19 08:12:29.599 8463-8463/? I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
02-19 08:12:29.603 8463-8463/? E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services.  Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
02-19 08:12:29.603 8463-8463/? E/GMPM: Scheduler not set. Not logging error/warn.
02-19 08:12:29.632 8463-8479/? E/GMPM: Uploading is not possible. App measurement disabled
02-19 08:12:29.644 8463-8463/? I/test: try ok
02-19 08:12:29.644 8463-8463/? E/SQLiteLog: (1) no such table: table_sms_received
02-19 08:12:29.644 8463-8463/? E/SQLiteDatabase: Error inserting phone=+33565456 processed=zz dateReceiving=janvier data=coords XY
                                                 android.database.sqlite.SQLiteException: no such table: table_sms_received (code 1): , while compiling: INSERT INTO table_sms_received(phone,processed,dateReceiving,data) VALUES (?,?,?,?)
                                                     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                     at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1469)
                                                     at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
                                                     at com.dev.boblinux.cador.bdd.CSmsReceiverDAO.persist(CSmsReceiverDAO.java:85)
                                                     at com.dev.boblinux.cador.activities.CMainActivity.onCreate(CMainActivity.java:43)
                                                     at android.app.Activity.performCreate(Activity.java:6237)
                                                     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                     at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                     at android.os.Handler.dispatchMessage(Handler.java:102)
                                                     at android.os.Looper.loop(Looper.java:148)
                                                     at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-19 08:12:29.644 8463-8463/? I/test: persist ok
02-19 08:12:29.644 8463-8463/? E/SQLiteLog: (1) no such table: table_sms_received
02-19 08:12:29.645 8463-8463/? W/System.err: android.database.sqlite.SQLiteException: no such table: table_sms_received (code 1): , while compiling: SELECT ID, dateReceiving, processed, phone, data FROM table_sms_received WHERE dateReceiving LIKE "janvier"
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
02-19 08:12:29.645 8463-8463/? W/System.err:     at com.dev.boblinux.cador.bdd.CSmsReceiverDAO.find(CSmsReceiverDAO.java:64)
02-19 08:12:29.645 8463-8463/? W/System.err:     at com.dev.boblinux.cador.activities.CMainActivity.onCreate(CMainActivity.java:45)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.app.Activity.performCreate(Activity.java:6237)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.app.ActivityThread.-wrap11(ActivityThread.java)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.os.Looper.loop(Looper.java:148)
02-19 08:12:29.645 8463-8463/? W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
02-19 08:12:29.645 8463-8463/? W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
02-19 08:12:29.645 8463-8463/? W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
02-19 08:12:29.645 8463-8463/? W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
02-19 08:12:29.669 8463-8481/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-19 08:12:29.801 8463-8481/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-19 08:12:29.866 8463-8481/? W/EGL_emulation: eglSurfaceAttrib not implemented
02-19 08:12:29.866 8463-8481/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad760be0, error=EGL_SUCCESS
02-19 08:12:30.483 8463-8463/? I/Choreographer: Skipped 45 frames!  The application may be doing too much work on its main thread.

why i can't create my table table_sms_received ? (it seems to be the main problem

boblinux
  • 105
  • 2
  • 2
  • 10
  • 1
    have you face in error..if so provide log cat. – ELITE Feb 19 '16 at 06:31
  • you're right, i juste see strange message and really interesting (i post it) – boblinux Feb 19 '16 at 06:36
  • 1
    It means table is not present – ELITE Feb 19 '16 at 06:39
  • but i created it ? i don't find where is syntax error on my create table line ... – boblinux Feb 19 '16 at 06:40
  • 1
    Android already has an SMS database and a content provider for reading from it – OneCricketeer Feb 19 '16 at 06:40
  • can u give me some link @cricket_007? please, but i wanna try with Sqlite before, it is a constraint in my project – boblinux Feb 19 '16 at 06:42
  • 1
    ContentProviders are sqlite. http://stackoverflow.com/questions/1976252/how-to-use-sms-content-provider-where-are-the-docs – OneCricketeer Feb 19 '16 at 06:44
  • 1
    Try CREATE TABLE IF NOT EXISTS – Prithviraj Shiroor Feb 19 '16 at 06:45
  • @PrithvirajShiroor doesn't work, (but i edit my code with this) – boblinux Feb 19 '16 at 06:51
  • 1
    there is a syntax error with ur insert statement try attaching debugger at the insert query and check for the string query in inspection and see the syntax – Prithviraj Shiroor Feb 19 '16 at 06:56
  • @PrithvirajShiroor i find an error, i edit my code (but doesn't resolve problem) – boblinux Feb 19 '16 at 07:07
  • `table_sms_received ` does this Table actual exist? use http://facebook.github.io/stetho/ from Facebook to debug using chrome to look at your db live. – kandroidj Feb 19 '16 at 07:40
  • I would recommend you to uninstall your app and then install your app again. I suspect that, you are already having a db present without the table table_sms_received. While you have updated your db helper class to include that table, you might not have changed the version and because of that neither 'onUpgrade' nor 'onCreate' getting called on sqlite helper class. This is purely based on assumption and experience. So avoid if that is not the case – sandip Feb 19 '16 at 10:33

1 Answers1

0
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);

=>

values.put(COL_DateReceiving,t.getDateReceiving());
        values.put(COL_PROCESSED, t.getProcessed());
        values.put(COL_PHONE, t.getPhone());
        values.put(COL_DATA, t.getData());

and when you change some code, you have to uninstall and re-install your app (required!), to remake new database, and then it works .

boblinux
  • 105
  • 2
  • 2
  • 10
  • 1
    `when you change some code, you have to uninstall and re-install your app` **NO**. Only when you change your database structure. – Phantômaxx Feb 19 '16 at 10:27