使用Cordova和Android从SQLIte数据库同时读/写

时间:2014-10-23 15:35:08

标签: java android database sqlite cordova

我为90%的Cordova(3.5.0)和10%的Java编写了一个应用程序。这个用Java编写的10%用于将数据库与外部API同步。同步按以下方式进行:

    @Override
    protected void onPreExecute()
    {
        this.checkVersionForInvalidOptionsMenu();
    }

    @Override
    protected Boolean doInBackground(Void... params) 
    {
        Log.d("Execute", "Task");
        return sync();
    }

    protected void onPostExecute(Boolean result) {
        this.checkVersionForInvalidOptionsMenu();
        if (result)
        {
            Toast.makeText(this.ac.getApplicationContext(), R.string.CURR_SYNC, Toast.LENGTH_SHORT).show();
            this.notificationProgress.setContentText(this.ac.getString(R.string.notification_complete))
                                     .setProgress(0,0,false)
                                     .setAutoCancel(true);
            this.notificationManage.notify(0, notificationProgress.build());
        }
        closeDB();
    }

    public boolean sync()
    {
        if (!syncInitialData())
            return false;
        return true;
    }

    public boolean syncInitialData()
    {
        String syncData = sfzApi.getInitialData();
        if(syncData != null) 
        {
            try 
            {
                SQLQueries.execSql(db, syncData, this);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return true;
        }
        return false;
    }

我使用AsyncTask。以下是代码和方法:SQLQueries.execSql (db, syncData, this);

public static void execSql(SQLiteDatabase db, String fileName, SyncDatabase task) throws SQLException, IOException
    {
        // TODO: Count lines
        int allLines = 26000;
        BufferedReader br = new BufferedReader(new FileReader(fileName));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fileName", fileName);
        map.put("task", task);
        map.put("allLines", allLines);
        afterThirteenAPIVersion(br, db, map);
        br.close();
        removeFile(fileName);
    }

    private static void afterThirteenAPIVersion(BufferedReader br, SQLiteDatabase db, Map<String, Object> map) throws SQLException, IOException
    {
        String line;
        int counter = 0;
        int lastPercent = 0;

        db.beginTransaction();
        while ((line = br.readLine()) != null) {
            if(line.trim().length() == 0)
                continue;
            SQLiteStatement stmt = db.compileStatement(line);
            stmt.execute();
            stmt.clearBindings();
            stmt.close();
            int percent = (int) ((counter * 100) / ((Integer)map.get("allLines")));
            if (percent != lastPercent)
            {
                ((SyncDatabase)map.get("task")).doProgress(percent);
                lastPercent = percent;
            }

            counter++;
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

此类使整个事务记录来自外部api的sql,然后执行事务。

虽然我同步但我希望能够在应用中进行搜索。我有一个用于搜索的字段。下面是一个示例代码,它实现了该字段背后的部分功能:

define([
  'underscore',
  'backbone',
  'sqlinstall',
  'models/schedule/ScheduleModel'
], function(_, Backbone, SqlInstall, ScheduleModel){
  var SchedulesCollection = Backbone.Collection.extend({
    model: ScheduleModel,

     initialize: function() {
      this.scheduleModel = new ScheduleModel();
      this.db = getDatabase();
    },

    fetch: function(line, typeTransport, callback, direction, stopUid) {
      var self = this;
      this.reset();
      this.db.transaction(function(tx) { 
            self.scheduleModel.getTransport(tx, line, typeTransport, self, callback, direction, stopUid); 
      }, this.errorDB, this.successDB);
    },

    errorDB: function(err) {
      console.log(err);
        if(err.code == 5) {
            new SchedulesCollection().notExistRecord();
            return;
        }
        console.log(err);
    },

    successDB: function() {
    },
  return SchedulesCollection;
});

getTransport: function(tx, line, typeTransport, collection, callback, direction, stopUid) {
      var self = this;
      var typeTransport = getCorrectType(typeTransport);
      var sql = this.sqlDefaultQuery(line, typeTransport);
        tx.executeSql(sql, [], function(tx, result) {
            for (var i=0; i < result.rows.length; i++){
                collection.add({
                    transport: result.rows.item(i).num,
                    typeTransport: convertToHtmlTypeTransport(result.rows.item(i).type_transport_short),
              direction: result.rows.item(i).from_to_stop,
              stopName: result.rows.item(i).name,
              stopUid: result.rows.item(i).uid_stop,
              stopLat: result.rows.item(i).latitude,
              stopLon: result.rows.item(i).longitude,
              schedule: $.parseJSON(result.rows.item(i).time),
                });
            }
        self.addDirections(tx, line, typeTransport, collection, callback, direction);
        callback();
        });
    },

当您到达此代码时,将执行错误,然后一切都失败。该事务将被执行,但随后会出现数据库问题,并以某种方式删除自己。

我尝试在部件上进行事务处理,然后稍微运行,然后在同步状态下说明基座已关闭并再次收到基座关闭的错误。

如果您等待同步完成,然后寻求没有问题。当我尝试同时写入和读取时出现问题。由于Java只能通过cordova(即由js)进行写入和读取。

你遇到类似问题的人。我使用SQLite for Java和Web SQLite for cordova。

如果您需要更多代码详细信息,请提供。

0 个答案:

没有答案