1

I'm creating a Room DB for an app I've making, and I keep getting the following exception/error whenever I try and run my code:

Cannot find setter for field. - value in java.lang.String

This is extremely frustrating. I have tried to look through some other people's suggestions, and I have tried to fix my code accordingly although I am still getting the same error.

I am extremely confused as to where the source of the problem is because of the vagueness of the error message. I have tried for a couple of hours to fix the code but nothing is really working, so I'd thought I would ask it here.

PixelArts Kotlin Class


import androidx.room.*
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Entity
data class PixelArts(
    @ColumnInfo(name = "item_bitmap") var bitmap: String,
    @ColumnInfo(name = "item_title") var title: String,
    @ColumnInfo(name = "item_pixel_data") var pixelData: String,
    @ColumnInfo(name = "item_favourited") var favourited: Boolean,
    @ColumnInfo(name = "item_date_created") var dateCreated: String = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss").format(LocalDateTime.now())) {
    @PrimaryKey(autoGenerate = true) var id = 0
}

PixelArtCreationsDao.kt

@Dao
interface PixelArtCreationsDao {
    @Insert
    suspend fun insertPixelArt(pixelArt: PixelArts)

    @Query("SELECT * FROM PixelArts ")
    fun getAllPixelArtCreations(): String

    @Query("DELETE FROM PixelArts WHERE id=:pixelArtId")
    fun deletePixelArtCreation(pixelArtId: Int)

    @Query("UPDATE PixelArts SET item_pixel_data=:pixelData AND item_bitmap=:bitmap WHERE id=:pixelArtId")
    fun updatePixelArtCreation(pixelArtId: Int, bitmap: String, pixelData: String)
}

AppData class

class AppData {
    companion object {
        var dbFileName = "pixel_art_db"
        lateinit var db: PixelArtDatabase

        var pixelArtsData = mutableListOf<PixelArts>()

        fun initialize() {
            pixelArtsData.add(PixelArts(BitmapConverter.bitmapToString(Bitmap.createBitmap(10, 10, Bitmap.Config.ARGB_8888)), "Creation 1", JsonConverter.convertListOfViewToJsonString(listOf()), true))
        }
    }
}

onCreate method

 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setBindings()
        setOnClickListeners()
        setTitle()

        AppData.db = PixelArtDatabase.getDatabase(this)!!

        if (databaseFileExists()) {
            CoroutineScope(Dispatchers.IO).launch {
                AppData.pixelArtsData = AppData.db.pixelArtCreationsDao().getAllPixelArtCreations()

                withContext(Dispatchers.Main) {
                    binding.activityMainRecentCreationsRecyclerView.layoutManager = GridLayoutManager(this@MainActivity, 2)
                    binding.activityMainRecentCreationsRecyclerView.adapter = RecentCreationsAdapter(AppData.pixelArtsData, this@MainActivity)
                }
            }
        } else {
            AppData.initialize()
            binding.activityMainRecentCreationsRecyclerView.layoutManager = GridLayoutManager(this, 2)
            binding.activityMainRecentCreationsRecyclerView.adapter = RecentCreationsAdapter(AppData.pixelArtsData, this)

            CoroutineScope(Dispatchers.IO).launch {
                for (pixelArts in AppData.pixelArtsData) {
                    AppData.db.pixelArtCreationsDao().insertPixelArt(pixelArts)
                }
            }
        }
    }

Converters (maybe something is wrong here?)

object BitmapConverter {
    fun stringToBitmap(str: String): Bitmap? {
        return try {
            val byte: ByteArray = Base64.decode(str, Base64.DEFAULT)
            BitmapFactory.decodeByteArray(Base64.decode(str, Base64.DEFAULT), 0, byte.size)
        } catch (exception: Exception) {
            exception.printStackTrace()
            null
        }
    }

    fun bitmapToString(bitmap: Bitmap): String {
        val byteArrayOutputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)

        return Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT)
    }
}
object JsonConverter {
    fun convertListOfViewToJsonString(list: List<View>) = Gson().toJson(list)
    fun convertJsonStringToListOfView(str: String) = Gson().fromJson(str, Array<View>::class.java).toList()
}

build.gradle

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
}

android {
    compileSdk 31

    testOptions {
        unitTests.includeAndroidResources = true
    }

    defaultConfig {
        applicationId "com.realtomjoney.pyxlmoose"
        minSdk 27
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    buildFeatures {
        viewBinding true
    }
    testOptions {
        unitTests.returnDefaultValues = true
    }
}

dependencies {
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    implementation 'com.google.android.material:material:1.5.0-beta01'
    testImplementation 'junit:junit:4.13.2'
    testImplementation 'androidx.test:core-ktx:1.4.0'
    androidTestImplementation 'androidx.test.ext:junit-ktx:1.1.3'
    testImplementation 'org.robolectric:robolectric:4.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0-alpha03'
    androidTestImplementation 'androidx.test:rules:1.4.1-alpha03'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'

    // ROOM
    implementation "androidx.room:room-runtime:2.3.0"
    implementation "androidx.room:room-ktx:2.3.0"
    kapt "androidx.room:room-compiler:2.3.0"

    // COROUTINE
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.0-RC'
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.0-RC'

    implementation 'com.google.code.gson:gson:2.8.6'
}

Image: enter image description here

If you find an issue with this question, or you think for some reason it's not well written then tell me in the comments the exact problem. Don't be an elitist.

This question is unique than similar posts because I've tried every possible 'solution' and the problem still resides.

thebluepandabear
  • 263
  • 2
  • 7
  • 29
  • `pixelData` is still a `val`. Does it need to be a `var`? – Tenfour04 Dec 03 '21 at 05:49
  • @Tenfour04 Oops, apologies for that stupid mistake. Even when I change `pixelData` to `var` I'm still getting the same exception unfortunately, even after I cleaned, rebuilt my project, and invalidated caches. – thebluepandabear Dec 03 '21 at 06:04
  • Does this answer your question? [Cannot find setter for field - using Kotlin with Room database](https://stackoverflow.com/questions/44213446/cannot-find-setter-for-field-using-kotlin-with-room-database) – Ivo Dec 03 '21 at 08:19
  • @IvoBeckers No, I went through every answer and it didn't help. Strange. – thebluepandabear Dec 03 '21 at 10:28
  • @TomJoney you should post your stacktrack and mark the crashes occuring position. – yan sam Dec 03 '21 at 12:31
  • @yansam how do I view the stacktrace? If you mean Logcat it is saying there are no processes to debug so it's not possible to view Logcat. – thebluepandabear Dec 03 '21 at 12:35
  • @TomJoney `Cannot find setter for field. - value in java.lang.String` this code display page. – yan sam Dec 03 '21 at 12:59
  • @yansam see image – thebluepandabear Dec 03 '21 at 13:07
  • In that image, you've shrunk the left panel down so it cannot be read. That will provide more information about what part of the build is causing this issue. I tried duplicating your Entity and Dao in a project and they compiled fine with Room 2.3.0. Are there any other Entities in your project? I don't think this has to do with your Bitmap conversion or anything like that because its a build error and it's showing an error that comes from Room. – Tenfour04 Dec 03 '21 at 14:12
  • @Tenfour04 hey man, I sent an image of that left panel. I really need this issue to get fixed so I can get started with my app, it's taken me a couple of weeks to try and get Room ready but it's honestly been very difficult! I am willing to give 100 reputation to whoever can help me. I actually made a lot of progress in my app and I made the mistake of using Room much later in development, which means most of my code needs to be rewritten.. Again, there are many many errors as you can tell by the image lol – thebluepandabear Dec 04 '21 at 02:57

1 Answers1

0

actually the solution to the above problem is very simple, I had the same problem, just figured out the answer after spending several hours on it.

 @Query("SELECT * FROM PixelArts ")
fun getAllPixelArtCreations(): String

In This part, the getAllPixelArtCreations function is supposed to return PixelArts object since the query used is select * from.... but the return type that you specified is String.

@Query("SELECT * FROM PixelArts ")
fun getAllPixelArtCreations(): PixelArts

Using the above code should fix 'the cannot find setter problem'.

sidd_r
  • 1