5

Sometimes when I use a string resource in my composable, the preview will show the wrong string. It always works fine for literal strings, only string resources are wrong. The bug isn't consistent.

For example if I have this strings.xml:

<resources>
    <string name="app_name">Violit</string>
    <string name="load_topic_failure_message">Something went wrong loading the topic</string>
</resources>

And I have this composable:

@Composable
fun TopicFailureContent() {
    Text(stringResource(R.string.load_topic_failure_message))
}

@Preview(showBackground = true)
@Composable
fun TopicFailureContentPreview() {
    TopicFailureContent()
}

It might render something like "Partially checked" or "Navigation menu" instead of "Something went wrong loading the topic".

If I change the composable to this:

@Composable
fun TopicFailureContent() {
    Text("Something went wrong loading the topic")
}

it renders the preview correctly.

It looks like the preview might be rendering nearby strings instead of the one I want. String resources work fine in tests and running the app. It's just preview that is not always working.

I'm using Android Studio Electric Eel 2022.1.1 but I was having the same problem on the previous version as well. This fails on both Compose UI version 1.2.1 and 1.3.3.

Any idea why string resources don't always work in preview and how to fix it?

Eva
  • 4,397
  • 5
  • 43
  • 65
  • 1
    Can you try cleaning project and rebuilding again. If that does not work try clearing gradle cache in home directory. Looks like a cache related problem. – Karan Sharma Jan 22 '23 at 01:02
  • Same issue here, I am using `stringResource(R.string.hello_world)`, but when running the app its render totally other string. Android Studio Giraffe | 2022.3.1 Canary 3 Build #AI-223.7571.182.2231.9532861, built on January 27, 2023 Runtime version: 17.0.5+0-17.0.5b762.1-9522829 aarch64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. macOS 13.2 – rosuh Feb 10 '23 at 00:59
  • Karan Sharma's solution seems to work. Kinda a pain when the cache needs to be invalidated. Usually just cleaning and rebuilding will do it – Eva Feb 10 '23 at 16:48

0 Answers0