Как получить только строку из библиотеки сохранения состояния комнаты? - PullRequest
0 голосов
/ 16 июня 2020

Сегодня я начал изучать, как использовать Room для моего простого тестового проекта. Моя текущая проблема - получение сохраненных данных в виде строки, а не всего объекта. Я добавил изображение внизу:

Мне просто нужен заголовок для каждого объекта. Есть идеи?

As you can see here all data appears instead of only the string

MainActivity:

class MainActivity: AppCompatActivity () {

lateinit var mAdapter: MyAdapter
lateinit var db: NotesDatabase

var itemsList = mutableListOf<String>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    loadApp()
}

private fun loadApp() {

    GlobalScope.launch {
        dataBaseSetup()

        withContext(Dispatchers.Main) {
            setUpRecycler()
        }
    }
}

//Database
private fun dataBaseSetup() {
    db = Room.databaseBuilder(
        applicationContext, NotesDatabase::class.java, "notes-list.db"
    ).build()

    //Database
    GlobalScope.launch {
        var dataBaseList = db.notesDao().getAllNotes() as MutableList
        Log.d("Main", "$dataBaseList")

        for (i in 0 until dataBaseList.size) {
            itemsList.add("${dataBaseList[i]}")
        }
    }
}

private fun setUpRecycler() {
    mAdapter =
        MyAdapter(itemsList)
    val mList: DragDropSwipeRecyclerView = findViewById(R.id.list)
    mList.layoutManager = LinearLayoutManager(this)
    mList.adapter = mAdapter

    mList.orientation =
        DragDropSwipeRecyclerView.ListOrientation.VERTICAL_LIST_WITH_VERTICAL_DRAGGING
    mList.disableSwipeDirection(DragDropSwipeRecyclerView.ListOrientation.DirectionFlag.RIGHT)

    val onItemSwipeListener = object : OnItemSwipeListener<String> {
        override fun onItemSwiped(
            position: Int,
            direction: OnItemSwipeListener.SwipeDirection,
            item: String
        ): Boolean {
            Log.d("Main", "Position = $position, Direction = $direction, Item = $item")

            when (direction) {
                OnItemSwipeListener.SwipeDirection.RIGHT_TO_LEFT -> {
                    Toast.makeText(
                        applicationContext,
                        "$item deleted",
                        Toast.LENGTH_SHORT
                    ).show()
                    //todo: add deleted code here

                    //Database
                    GlobalScope.launch(Dispatchers.Default) {
                        db.notesDao().delete(NotesEntity("$item"))

                    }
                }
                OnItemSwipeListener.SwipeDirection.LEFT_TO_RIGHT -> {
                    Toast.makeText(
                        applicationContext,
                        "$item archived",
                        Toast.LENGTH_SHORT
                    ).show()
                    //todo: add archived code here
                }
                else -> return false
            }
            return false
        }
    }
    mList.swipeListener = onItemSwipeListener

    // button
    fabAddItem()
}

private fun fabAddItem() {
    fab_add.setOnClickListener {
        Log.d("Main", "Button pressed")
        val builder = AlertDialog.Builder(this)
        val inflater = layoutInflater
        val dialogLayout = inflater.inflate(R.layout.edit_text_layout, null)
        val editText = dialogLayout.findViewById<EditText>(R.id.et_editText)

        with(builder) {
            setTitle("Enter some text!")
            setPositiveButton("OK") { dialog, which ->
                mAdapter.updateItem(editText.text.toString())

                //Database
                GlobalScope.launch(Dispatchers.Default) {
                    db.notesDao().insertAll(NotesEntity(editText.text.toString()))
                }

                Toast.makeText(
                    applicationContext,
                    "Text added successfully",
                    Toast.LENGTH_SHORT
                ).show()
            }
            setNegativeButton("Cancel") { dialog, which ->
                Log.d("Main", "Negative button clicked")
            }
            setView(dialogLayout)
            show()
        }
    }
}

}

Класс NotesEntity:

  @Entity(tableName = "notes_items")
    data class NotesEntity(
@PrimaryKey var title: String

)

NotesDao:

@Dao
interface NotesDao {

    @Query("SELECT * FROM notes_items")
    fun getAllNotes(): List<NotesEntity>

    @Query("SELECT * FROM notes_items WHERE title LIKE :title")
    fun getTitle(title: String): NotesEntity

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg todo: NotesEntity)

    @Delete
    fun delete(title: NotesEntity)

    @Update
    fun updateNotes(vararg title: NotesEntity)
}

База данных Notes:

@Database(entities = [NotesEntity::class], version = 1)
abstract class NotesDatabase : RoomDatabase() {
    abstract fun notesDao(): NotesDao

    companion object {
        @Volatile private var instance: NotesDatabase? = null
        private val LOCK = Any()

        operator fun invoke(context: Context)= instance ?: synchronized(LOCK){
            instance ?: buildDatabase(context).also { instance = it}
        }

        private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
            NotesDatabase::class.java, "todo-list.db")
            .build()
    }
}

Ответы [ 2 ]

1 голос
/ 16 июня 2020

"${dataBaseList[i]}" должно быть "${dataBaseList[i].title}", единственное поле вашей сущности

0 голосов
/ 17 июня 2020

В запросе SQL, когда вы набираете Select *, * здесь означает ALL . Таким образом, ваш запрос вернет объект, чтобы просто вернуть строку, вам нужно заменить * на имя столбца (атрибут), которое вы хотите получить как:

Select title from notes_items
...