我一直在使用SQLite Android,每当我第二次尝试更新表时我都会出错,而且我不知道我的代码有什么问题。第一次更新工作正常。
有人请告诉我,我做错了什么?提前谢谢。
这是我用来更新表格的函数:
public boolean updateEvents(int id, boolean shown){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(EVENTS_COLUMN_SHOWN, shown);
int result = db.update(EVENTS_TABLE_NAME, contentValues, EVENTS_COLUMN_ID_EVENTS + " = ?", new String[]{Integer.toString(id)});
Log.d(DBHelper.class.getSimpleName(),"update result: "+result);
return result==1;
}
在AsyncTask类中完成doInBackground()后调用该函数。 这是调用该更新函数的类:
private class GetEvents extends AsyncTask<Void,Void,Events>{
private DBHelper dbHelper;
@Override
protected Events doInBackground(Void... voids) {
try{
if(new Connection().GetEvents() && Settings.events.size()>0){
dbHelper = new DBHelper(FirstActivity.this);
for(int i=0; i<Settings.events.size(); i++){
dbHelper.recordEvents(Settings.events.get(i),dbHelper.isEventsShown(Settings.events.get(i).id_event));
}
for(int a=0; a<Settings.events.size(); a++){
boolean shown = dbHelper.isEventsShown(Settings.events.get(a).id_event);
Log.d(FirstActivity.class.getSimpleName(),"shown "+a+": "+shown);
if(Settings.events.get(a).isEnabled() && Settings.events.get(a).isEventValid() && !shown){
return Settings.events.get(a);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Events events) {
if(events!=null){
dbHelper.updateEvents(events.id_event, true);
showPopUp(events);
}
super.onPostExecute(events);
}
}
答案 0 :(得分:0)
我不确定我是否理解你想要实现的目标,但我试了一下。试试下面的代码让我知道。
private class GetEvents extends AsyncTask<Void,Void,ArrayList<Events>>{
private DBHelper dbHelper;
@Override
protected Events doInBackground(Void... voids) {
ArrayList<Events> pendingEvents = new ArrayList<Events>();
try{
if(new Connection().GetEvents() && Settings.events.size()>0){
dbHelper = new DBHelper(FirstActivity.this);
for(int i=0; i<Settings.events.size(); i++){
dbHelper.recordEvents(Settings.events.get(i),dbHelper.isEventsShown(Settings.events.get(i).id_event));
}
for(int a=0; a<Settings.events.size(); a++){
boolean shown = dbHelper.isEventsShown(Settings.events.get(a).id_event);
Log.d(FirstActivity.class.getSimpleName(),"shown "+a+": "+shown);
if(Settings.events.get(a).isEnabled() && Settings.events.get(a).isEventValid() && !shown){
pendingEvents.add(Settings.events.get(a));
// return Settings.events.get(a);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return pendingEvents;
}
@Override
protected void onPostExecute(ArrayList<Events> events) {
if(events!=null){
for(Events events1:events){
dbHelper.updateEvents(events1.id_event, true);
}
showPopUp(events);
}
super.onPostExecute(events);
}
}
问题(如果我理解正确的话)是,一旦找到一个事件,就会返回doInBackground方法。这就是为什么我把所有这些事件放在一个列表中,如果它在迭代完整的Settings.events列表后返回。