我有一个简单的问题。我试图每1秒将当前日期插入数据库,但是当我尝试这样做时,日期总是相同的,我希望有一个当前日期。接下来的问题是,当我尝试使用“停止”按钮关闭数据库时,我遇到了这个例外:
01-27 13:57:51.063: E/AndroidRuntime(12964): FATAL EXCEPTION: Thread-144
01-27 13:57:51.063: E/AndroidRuntime(12964): java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/pl.pawelfrydrych.flyingball/databases/baza.db
01-27 13:57:51.063: E/AndroidRuntime(12964): at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
01-27 13:57:51.063: E/AndroidRuntime(12964): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1437)
01-27 13:57:51.063: E/AndroidRuntime(12964): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1339)
01-27 13:57:51.063: E/AndroidRuntime(12964): at pl.pawelfrydrych.flyingball.MainActivity.insertData(MainActivity.java:146)
01-27 13:57:51.063: E/AndroidRuntime(12964): at pl.pawelfrydrych.flyingball.MainActivity$2.run(MainActivity.java:248)
insertData方法:
public void insertData() throws InterruptedException {
ContentValues values = new ContentValues();
myDBAdapter = new Database(this).open();
while(true) {
Date date = new Date();
long millis = System.currentTimeMillis();
values.put(Database.LEFT_POSITION, xPosition);
values.put(Database.RIGHT_POSITION, yPosition);
values.put(Database.GPS, GPSposition);
values.put(Database.TIME, date.toString());
if(myDBAdapter.db != null) {
myDBAdapter.db.insert("baza", null, values);
Thread.sleep(1000 - millis % 1000);
} else {
Log.d(Database.DB_NAME,"db is null");
}
}
}
MainActivity onClick方法:
public void onClick(View v) {
switch(v.getId()){
case R.id.bStart:
Thread watek = new Thread(){
public void run(){
try {
Looper.prepare();
insertData();
} catch (InterruptedException e) {
Log.v("Thread", "Problem with inserting insertData method");
e.printStackTrace();
}
}
};
watek.start();
break;
case R.id.bStop:
myDBAdapter.close();
break;
}
}
答案 0 :(得分:0)
我认为您可以使用TimerTask重复具有特定间隔的内容。你可以根据需要使用scheduleTask(),间隔为1秒。 作为此
的代码TimerTask task = new TimerTask() {
public void run() {
}
};
Timer timer = new Timer();
timer.scheduleAtFixedRate(task, firstTime, period);
如果你不想使用Timertask你也可以使用1个替代品。或者可以按照类似的链接。 Android - Controlling a task with Timer and TimerTask?
private Runnable onEverySecond=new Runnable() {
public void run() {
// do real work here
if (!isPaused) {
someLikelyWidget.postDelayed(onEverySecond, 1000);
}
}
};
答案 1 :(得分:0)
1)尝试使用sqlite语法:
values.put(Database.TIME, "NOW()");
2)按钮'stop'你应该退出while-cicle,例如: 制作全球旗帜
boolean stop_posting = false;
开始按钮,清除此标志
case R.id.bStart:
stop_posting = false;
/*...*/
在停止按钮上,不要关闭数据库,而是设置标志
case R.id.bStop:
stop_posting = true;
break;
在cicle中,检查此标志并在设置时返回
while(true){
if(stop_posting) {
myDBAdapter.close();
return;
}
/*...*/}