Home > other >  Get a filtred list from database
Get a filtred list from database

Time:10-01

Well, I'm using Room Database and I need pick a filtred list by one property, that is isSelected: Boolean. I need it to put in a variable selectedTasksList to show programmatically a menuItem based on selection mode that is enabled if the selectedTasksList isn't empty and after this, to delete the tasks selecteds. But first I need setup the selectedTasksList putting into the tasks that is isSelected = true.

Some Idea???

My Object:

data class Task(
    @PrimaryKey(autoGenerate = true)
    val uid: Int,
    [...]
    @ColumnInfo
    var isSelected: Boolean
)

Activity:

class ListTaskActivity : AppCompatActivity() {

    private lateinit var binding: ActivityListTaskBinding

    lateinit var viewModel: ListTaskViewModel

    private lateinit var adapter: ListTaskAdapter

    private var deleteMenu: Menu? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityListTaskBinding.inflate(layoutInflater)
        viewModel = ListTaskViewModel(application)
        setContentView(binding.root)

        viewModel.taskList.observe(
            this
        ) { tasks ->
            adapter.addTask(tasks)
        }

        viewModel.selectionMode.observe(
            this
        ) { selectionMode ->
            changeTrashVisibilityBasedOnSelectionMode()
        }

        changeTrashVisibilityBasedOnSelectionMode()
        setupList()
    }

    private fun changeTrashVisibilityBasedOnSelectionMode() {
        this.deleteMenu?.findItem(R.id.menu_delete_action)?.isVisible =
            viewModel.selectionMode.value == true
    }

    private fun setupList() {
        adapter = ListTaskAdapter(
            selectionTaskCallback = { task ->
                viewModel.syncSelection(task) }
        )
        binding.recyclerViewTasks.layoutManager = LinearLayoutManager(this)
        binding.recyclerViewTasks.adapter = adapter
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.delete_menu, menu)
        this.deleteMenu = menu
        this.deleteMenu?.findItem(R.id.menu_delete_action)?.isVisible = false
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if(item.itemId == R.id.menu_delete_action){
            setupConfirmationDialog()
        }
        return super.onOptionsItemSelected(item)
    }
}

ViewModel:

class ListTaskViewModel(private val context: Application) : AndroidViewModel(context) {

    val taskList = MutableLiveData<List<Task>>()
    val selectionMode = MutableLiveData<Boolean>(false)
    private var selectedTasks = ArrayList<Task>()

    fun syncSelection(task: Task) {
        if (task.isTaskSelected()) {
            val exists = selectedTasks.any { it.uid == task.uid }
            if (!exists) {
                selectedTasks.add(task)
            }
        } else {
            selectedTasks.remove(task)
        }

        if (isSelectionModeEnabled() != selectionMode.value) {
            selectionMode.value = isSelectionModeEnabled()
        }
    }

    fun deleteSelectedTasks(context: Context){
        viewModelScope.launch {
            selectedTasks.forEach {
                DataBaseConnect.getTaskDao(context).deleteTask(it)
            }
            selectionMode.postValue(false)
            selectedTasks.clear()
            refreshScreen()
        }
    }

    fun isTaskListEmpty(): Boolean? {
        return taskList.value?.isEmpty()
    }

    fun isSelectionModeEnabled(): Boolean {
        return selectedTasks.isNotEmpty()
    }

    fun update(task: Task) {
        viewModelScope.launch {
            DataBaseConnect.getTaskDao(context).updateTask(task)
        }
    }
}

CodePudding user response:

In order to query a table and filter rows by a column, we need to use the SELECT keyword.

Using Room DB we need to use the @Query annotation that allows us to perform custom SQLite queries. More about it here.

Adding this function to your dao should do the trick (assuming your table name is task):

@Query("SELECT * FROM task WHERE isSelected = 0")
fun getSelectedTasks(): List<Task>

Notice that we compare isSelected to 0. This is because SQLite using 0/1 for booleans.

  • Related