0

我有一个调用远程服务器并从中获取数据的 Android 服务,我将数据存储在 SQLite 数据库中,一切正常,但是当我不调用该服务并在模拟器中再次执行时,我发现所有存储的数据消失了,数据库为空,是因为我在模拟器中运行项目并且它只将数据保存在某种缓存中吗?

谢谢

编辑

当我第二次运行该应用程序时,数据似乎在那里,但第三次它消失了。有时数据会在第二次或第四次运行时被擦除。

这是我的 Openhelper

public class DataBaseHelper extends SQLiteOpenHelper {

static final String dbName="DBlite2";
static final String tableMagasin= "magasin";
static final String tablenotif= "notification";
static final String tabletemp= "temporaire";
//colonnes de la table magasin
static final String colNomMag= "nomMag";
static final String colCategorie="categorie";
static final String colVille="ville";
static final String colAdresse="adresse";
static final String collat="latitude";
static final String collon="longitude";
static final String colDescr="description";
static final String colFavoris= "favori";
//colonnes de la table notifications
static final String colidNotif= "idnotif";
static final String colcontenu= "contenu";
static final String coldate= "datenotif";
static final String colvalidite= "validite";
static final String colnmnotif= "nmnotif";
static final String colctnotif= "ctnotif";
static final String colvlnotif= "vlnotif";

public DataBaseHelper(Context context)
{
    super(context,dbName ,null,1);

}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

    //création de la table magasin
    db.execSQL("CREATE TABLE "+tableMagasin+"("+colNomMag+" TEXT, "+ colCategorie +
        " TEXT, "+ colVille+" TEXT, "+colAdresse + " TEXT, "+ collat +
        " FLOAT, " + collon +" FLOAT, "+ colDescr+ " TEXT, " +
             colFavoris + " BIT,  PRIMARY KEY ( "+colNomMag+ " , "+colCategorie+" , "+colVille+" ));");

    //création de la table notification
    db.execSQL("CREATE TABLE "+tablenotif+"("+colidNotif+" INTEGER PRIMARY KEY,"+ colcontenu+" TEXT, "+coldate+" DATETIME, " 
            +colvalidite+" INTEGER, "+colnmnotif+" TEXT, "+colctnotif+" TEXT, "+colvlnotif+" TEXT, FOREIGN KEY ("
            +colnmnotif+") REFERENCES "+tableMagasin+" ( "+colNomMag+" ), FOREIGN KEY ( "+colctnotif+" ) REFERENCES "
            +tableMagasin+" ( "+colCategorie +" ), FOREIGN KEY("+ colvlnotif + ") REFERENCES "+ tableMagasin + " ("+ colVille+ "));");

    //création de la table tomporaire
    db.execSQL("CREATE TABLE "+tabletemp+"("+colidNotif+" INTEGER PRIMARY KEY,"+ colcontenu+" TEXT, "+coldate+" DATETIME, " 
            +colvalidite+" INTEGER, "+colnmnotif+" TEXT, "+colctnotif+" TEXT, "+colvlnotif+" TEXT, FOREIGN KEY ("
            +colnmnotif+") REFERENCES "+tableMagasin+" ( "+colNomMag+" ), FOREIGN KEY ( "+colctnotif+" ) REFERENCES "
            +tableMagasin+" ( "+colCategorie +" ), FOREIGN KEY("+ colvlnotif + ") REFERENCES "+ tableMagasin + " ("+ colVille+ "));");
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
    // TODO Auto-generated method stub


}

 @Override
 public String toString()
 {
     return (colNomMag + "\nCatégorie:" + colCategorie+ "\nVille:"+colVille);
  }
}

而我在其中进行插入的班级,更新了删除:

public class MagasinDataSource {

private SQLiteDatabase db;
private DataBaseHelper dbhelper;
private String[] allcolumns = {DataBaseHelper.colNomMag,DataBaseHelper.colCategorie, DataBaseHelper.colVille,
        DataBaseHelper.colAdresse,DataBaseHelper.collat,DataBaseHelper.collon,DataBaseHelper.colDescr,DataBaseHelper.colFavoris};
private String[] notifcol={DataBaseHelper.colidNotif, DataBaseHelper.colcontenu, DataBaseHelper.coldate, DataBaseHelper.colvalidite,
        DataBaseHelper.colnmnotif,DataBaseHelper.colctnotif,DataBaseHelper.colvlnotif}; 
public MagasinDataSource(Context context)
{
    this.dbhelper= new DataBaseHelper(context);
}

public void open() throws SQLException {
    db = dbhelper.getWritableDatabase();
}

public void close() {
    dbhelper.close();
}

public long insertMag(Magasin ma)
{
    ContentValues values = new ContentValues();
    values.put(DataBaseHelper.colNomMag, ma.getNomMag());
    values.put(DataBaseHelper.colCategorie, ma.getCat());
    values.put(DataBaseHelper.colVille, ma.getVille());
    values.put(DataBaseHelper.colAdresse, ma.getAdr());
    values.put(DataBaseHelper.colDescr, ma.getDescr());
    values.put(DataBaseHelper.colFavoris, ma.isFav());
    values.put(DataBaseHelper.collat, ma.getLat());
    values.put(DataBaseHelper.collon, ma.getLon());
    return db.insert(DataBaseHelper.tableMagasin, null, values);
}

public long insertNotif(Notif n)
{
    ContentValues values = new ContentValues();
    values.put(DataBaseHelper.colidNotif, n.getId_notif());
    values.put(DataBaseHelper.colcontenu, n.getContenu());
    //values.put(DataBaseHelper.coldate, n.getDatenotif());
    values.put(DataBaseHelper.colvalidite, n.getValidite());
    values.put(DataBaseHelper.colnmnotif, n.getNmag());
    values.put(DataBaseHelper.colctnotif, n.getCtmag());
    values.put(DataBaseHelper.colvlnotif, n.getVlmag());
    return db.insert(DataBaseHelper.tablenotif, null, values);
}

public long inserttemp(Notif n)
{
    ContentValues values = new ContentValues();
    values.put(DataBaseHelper.colidNotif, n.getId_notif());
    values.put(DataBaseHelper.colcontenu, n.getContenu());
    //values.put(DataBaseHelper.coldate, n.getDatenotif());
    values.put(DataBaseHelper.colvalidite, n.getValidite());
    values.put(DataBaseHelper.colnmnotif, n.getNmag());
    values.put(DataBaseHelper.colctnotif, n.getCtmag());
    values.put(DataBaseHelper.colvlnotif, n.getVlmag());
    return db.insert(DataBaseHelper.tabletemp, null, values);
}

public void deleteMag(Magasin ma)
{
    db.delete(DataBaseHelper.tableMagasin, DataBaseHelper.colNomMag +" =?"  + " AND "+ DataBaseHelper.colCategorie+" =?"+ " AND "+ DataBaseHelper.colVille+" =?", new String []{String.valueOf(ma.getNomMag()),String.valueOf(ma.getCat()),String.valueOf(ma.getVille())});
}

public void deleteAllnotif()
{
    db.delete(DataBaseHelper.tablenotif, null, null);
}
public void deleteAlltemp()
{
    db.delete(DataBaseHelper.tabletemp, null, null);
}

public void deletAllmag()
{
    db.delete(DataBaseHelper.tableMagasin, null, null);
}

public void updateMag(Magasin ma)
{

    ContentValues values = new ContentValues();
    values.put(DataBaseHelper.colNomMag, ma.getNomMag());
    values.put(DataBaseHelper.colCategorie, ma.getCat());
    values.put(DataBaseHelper.colVille, ma.getVille());
    values.put(DataBaseHelper.colAdresse, ma.getAdr());
    values.put(DataBaseHelper.colDescr, ma.getDescr());
    values.put(DataBaseHelper.colFavoris, ma.isFav());

    db.update(DataBaseHelper.tableMagasin, values, DataBaseHelper.colNomMag +" =? AND "+DataBaseHelper.colCategorie+" =? AND "+DataBaseHelper.colVille+" =?" ,new String []{String.valueOf(ma.getNomMag()),String.valueOf(ma.getCat()),String.valueOf(ma.getVille())});
    // + " AND "+ DataBaseHelper.colCategorie+" = "+ct+ " AND "+ DataBaseHelper.colVille+" = "+ vl,null);
 //  db.execSQL("UPDATE "+ DataBaseHelper.tableMagasin+" SET "+DataBaseHelper.colNomMag+" = "+ma.getNomMag()+" , "+DataBaseHelper.colCategorie+" = "+ma.getCat()+" , "+DataBaseHelper.colVille+" = "+ma.getVille()+" , "+DataBaseHelper.colAdresse+" = "+ma.getAdr()+
    //     " , "+DataBaseHelper.colDescr+" = "+ma.getDescr()+" , "+DataBaseHelper.colVille+" = "+ma.isFav()+" WHERE "+DataBaseHelper.colNomMag+" = "+ma.getNomMag()+" AND "+DataBaseHelper.colCategorie+" = "+ma.getCat()+" AND "+DataBaseHelper.colVille+" = "+ma.getVille());
}

public List<Magasin> getFavoris()
{
    List<Magasin> lstfavoris = new ArrayList<Magasin>();
    String getfav= "select * from magasin where favori=1";
    Cursor cursor= db.rawQuery(getfav, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Magasin magasin= cursorToMagasin(cursor);
        lstfavoris.add(magasin);
        cursor.moveToNext();
    }
    cursor.close();
    return lstfavoris;
}

public List<Notif> getGeoloc(float latitude, float longitude)
{
    List<Magasin> lstgeo= new ArrayList<Magasin>();
    List<Notif> lstnotif= new ArrayList<Notif>();
    float latinf= latitude - (float) 0.5;
    float latsup= latitude + (float) 0.5;
    float loninf= longitude - (float) 0.5;
    float lonsup= longitude + (float) 0.5;
    String requete="select * from magasin where latitude > "+String.valueOf(latinf)+" and latitude < "+String.valueOf(latsup)+
              " and longitude > "+String.valueOf(loninf)+" and longitude < "+ String.valueOf(lonsup);
 //  String requete="select * from magasin where favori=1";
//  String requete="select * from notification";
    Cursor cursor= db.rawQuery(requete, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast())
    {
        Magasin mag= cursorToMagasin(cursor);
        lstgeo.add(mag);
        cursor.moveToNext();
    }
    cursor.close();
    for(int i=0;i<lstgeo.size();i++)
    {
        String nm= lstgeo.get(i).getNomMag();
        String ct= lstgeo.get(i).getCat();
        String vl= lstgeo.get(i).getVille();
        String requete2="select * from notification where nmnotif = '"+nm+"' and ctnotif = '"+ct+"' and vlnotif = '"+vl+"'";
   Cursor  cursor2= db.rawQuery(requete2, null);
   cursor2.moveToFirst();
        while (!cursor2.isAfterLast())
        {
            Notif notif= cursorToNotif(cursor2);
            lstnotif.add(notif);
            cursor2.moveToNext();
        }
        cursor2.close();
    }

    return lstnotif;
}

public List<Magasin> getAll()
{
    List<Magasin> lstall = new ArrayList<Magasin>();
    Cursor cursor= db.query(DataBaseHelper.tableMagasin,allcolumns, null, null, null, null, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Magasin magasin= cursorToMagasin(cursor);
        lstall.add(magasin);
        cursor.moveToNext();
    }
    cursor.close();
    return lstall;
}

public boolean existeMag(String nm,String ct,String vl)
{
    List<Magasin> lst= new ArrayList<Magasin>();
    lst= getAll();
    boolean b=false;
    String nom;
    String cat;
    String ville;
    for(int i=0;i<lst.size();i++)
    {
         nom= lst.get(i).getNomMag();
         cat= lst.get(i).getCat();
         ville=lst.get(i).getVille();
         if((nm.equals(nom)) && (ct.equals(cat)) && (vl.equals(ville)))
         {
             b=true;
             break;
         }
    }
    return b;
}

public Magasin getMagasin(String nm,String ct,String vl)
{
    List<Magasin> lst= new ArrayList<Magasin>();
    Magasin m= new Magasin();
    lst=getAll();
    String nom;
    String cat;
    String ville;
    for(int i=0;i<lst.size();i++)
    {
         nom= lst.get(i).getNomMag();
         cat= lst.get(i).getCat();
         ville=lst.get(i).getVille();
         if((nm.equals(nom)) && (ct.equals(cat)) && (vl.equals(ville)))
         {
             m=lst.get(i);
             break;
         }
    }
    return m;
}

public boolean existeNotif(Notif notif)
{
    List<Notif> lst= new ArrayList<Notif>();
    lst=getAllNotif();
    boolean b=false;

    for(int i=0;i<lst.size();i++)
    {
        Notif s= new Notif();
        s=lst.get(i);
        if(notif.getId_notif()==s.getId_notif())
        {
            b=true;
            break;
        }
    }
    return b;
}

public boolean existetemp(Notif notif)
{
    List<Notif> lst= new ArrayList<Notif>();
    lst=getAlltemp();
    boolean b=false;

    for(int i=0;i<lst.size();i++)
    {
        Notif s= new Notif();
        s=lst.get(i);
        if(notif.getId_notif()==s.getId_notif())
        {
            b=true;
            break;
        }
    }
    return b;
}

public List<Notif> getAllNotif()
{
    List<Notif> lstnotif= new ArrayList<Notif>();
    Cursor cursor= db.query(DataBaseHelper.tablenotif,notifcol, null, null, null, null, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Notif s= cursorToNotif(cursor);
        lstnotif.add(s);
        cursor.moveToNext();
    }
    cursor.close();
    return lstnotif;

}

public List<Notif> getAlltemp()
{
    List<Notif> lstnotif= new ArrayList<Notif>();
    Cursor cursor= db.query(DataBaseHelper.tabletemp,notifcol, null, null, null, null, null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
        Notif s= cursorToNotif(cursor);
        lstnotif.add(s);
        cursor.moveToNext();
    }
    cursor.close();
    return lstnotif;
}

private Magasin cursorToMagasin(Cursor cursor) {
        Magasin magasin = new Magasin();
        magasin.setNomMag(cursor.getString(0));
        magasin.setCat(cursor.getString(1));
        magasin.setVille(cursor.getString(2));
        magasin.setAdr(cursor.getString(3));
        magasin.setLat(cursor.getFloat(4));
        magasin.setLon(cursor.getFloat(5));
        magasin.setDescr(cursor.getString(6));
        magasin.setFav(cursor.getInt(7)==1);
        return magasin;
    }

    private Notif cursorToNotif(Cursor cursor)
    {
        Notif n= new Notif();
        n.setId_notif(cursor.getInt(0));
        n.setContenu(cursor.getString(1));
        //n.setDatenotif(cursor.getString(2));
        n.setValidite(cursor.getInt(3));
        n.setNmag(cursor.getString(4));
        n.setCtmag(cursor.getString(5));
        n.setVlmag(cursor.getString(6));

        return n;
    }
}

编辑2

这是我的服务代码:

public class SyncService extends Service {
 private MagasinDataSource datasource;


    protected LocationManager locationManager;
    public static ShopAlertActivity MAIN_ACTIVITY;      
    private Timer timer=new Timer();   
    private static long UPDATE_INTERVAL =  86400000;  //default
    private static long DELAY_INTERVAL = 10000;  
    public static void setMainActivity(ShopAlertActivity activity)
    {
      MAIN_ACTIVITY = activity;   

    }

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

 @Override
    public void onCreate()
    {
     SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
     String interval= SP.getString("synchronisation", "1");
    if(interval.equals("1")) UPDATE_INTERVAL= 43200000;
    if(interval.equals("2")) UPDATE_INTERVAL= 86400000;
    if(interval.equals("3")) UPDATE_INTERVAL= 115200000;
      super.onCreate();     

      _startService();

     // if (MAIN_ACTIVITY != null)  Log.d(getClass().getSimpleName(), "FileScannerService started");
    }
  /*
     * starting the service
     */
    private void _startService()
    {   

      timer.scheduleAtFixedRate(   

              new TimerTask() {

                    public void run() {

                        try{

                        doServiceWork();

                        Thread.sleep(UPDATE_INTERVAL);

                        }catch(InterruptedException ie){

                            Log.e(getClass().getSimpleName(), "FileScannerService InterruptedException"+ie.toString());
                        }

                    }
                  },
                  DELAY_INTERVAL,
                  UPDATE_INTERVAL);

      Log.i(getClass().getSimpleName(), "FileScannerService Timer started....");
    }
    /*
     * start the processing, the actual work, getting config params, get data from network etc
     */
    private void doServiceWork()
    {
        //avoir les préférences
         SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
         String interval= SP.getString("synchronisation", "1");
        if(interval.equals("1")) UPDATE_INTERVAL= 43200000;
        if(interval.equals("2")) UPDATE_INTERVAL= 86400000;
        if(interval.equals("3")) UPDATE_INTERVAL= 115200000;

    try{


         //call the distant web service
        soapclass sc= new soapclass("TabMag");
        soapclass cs= new soapclass("TabNotif");
        Magasin[] tab_mag=sc.get_table_magasin();
        Notif[] tab_notif=cs.get_table_notif();


         datasource = new MagasinDataSource(this); 
         datasource.open();


         //Delete existing data
         if(tab_mag.length>0)
         {
            // datasource.deletAllmag();
            // datasource.deleteAllnotif();
         }


         //Insert data received from web service in table magasin
         for(int i=0;i<tab_mag.length;i++)
         {
             Magasin m= new Magasin();
             m=tab_mag[i];
             if(lst_fav.contains(m))
             {
                 m.setFav(true);
             }
             datasource.insertMag(m);
         }
         //insert data in tab_notif
         for(int i=0;i<tab_notif.length;i++)
         {
             Notif n= new Notif();
             n= tab_notif[i];
             datasource.insertNotif(n);
         }
         datasource.close();

    }
    catch(Exception e)
    {

    }



    }
    /*
     * shutting down the service
     */
    private void _shutdownService()
    {
      if (timer != null) timer.cancel();

     // Log.i(getClass().getSimpleName(), "Timer stopped...");
    }
}
4

0 回答 0