【问题标题】:Room database @Delete not executing房间数据库@Delete 未执行
【发布时间】:2018-01-28 16:52:58
【问题描述】:

我正在尝试从我创建的房间数据库中删除一行。

奇怪的是,只有我第一次执行命令时它没有删除行:

App.get().getDB().productDao().delete(myArrayList.get(clickedItemIndex));

当我第一次尝试再次删除该行后,一切正常并被删除。

我删除一行的活动:

private class DeletePelati extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //Perform pre-adding operation here.
    }
    @Override
    protected Void doInBackground(Void... voids) {
       App.get().getDB().productDao().delete(myArrayList.get(clickedItemIndex));
       return null;
    }
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        //To after addition operation here.
        setResult(pelatis,3);
        finish();
    }
}

然后当我重新启动我的应用程序时,删除查询会正常执行。

这是我扩展应用程序的应用程序:

public class App extends Application {

public static App INSTANCE;
private static final String DATABASE_NAME = "MyDatabase";
private static final String PREFERENCES = "RoomDemo.preferences";
private static final String KEY_FORCE_UPDATE = "force_update";

private MyDatabase database;

public static App get() {
    return INSTANCE;
}

@Override
public void onCreate() {
    super.onCreate();
    Stetho.initializeWithDefaults(this);

    // create database
    database = Room.databaseBuilder(getApplicationContext(),MyDatabase.class,DATABASE_NAME)
            .build();

    INSTANCE = this;
}

public MyDatabase getDB() {
    return database;
}

public boolean isForceUpdate() {
    return getSP().getBoolean(KEY_FORCE_UPDATE, true);
}

public void setForceUpdate(boolean force) {
    SharedPreferences.Editor edit = getSP().edit();
    edit.putBoolean(KEY_FORCE_UPDATE, force);
    edit.apply();
}

private SharedPreferences getSP() {
    return getSharedPreferences(PREFERENCES, MODE_PRIVATE);
}

public  void cleanUp(){
    database = null;
}
}

这是我的 DAO 类:

@Dao
public interface PelatesDao {

@Query("SELECT * FROM Pelates")
List<Pelates> getAll();

@Query("SELECT * FROM Pelates WHERE name LIKE :name LIMIT 1")
Pelates findByName(String name);

@Insert
void insertAll(List<Pelates> pelates);

@Insert
void insert(Pelates pelates);

@Update
void update(Pelates pelates);

@Delete
void delete(Pelates pelates);
}

【问题讨论】:

    标签: android android-room


    【解决方案1】:

    而不是使用@Delete 使用:

    @Query("DELETE FROM Test WHERE id=:arg0")
    fun deleteById(position: Int)
    

    上面例子中Test是表名,id=:arg0是WHERE子句 而在函数参数中传递的是where子句字段的值。

    PC上面的例子是 kotlin 语言的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多