android - How to fix Resources$NotFoundException: String resource in Kotlin without context?
问题描述
Android, Kotlin.
I want to use the RestApiService
file for requests and send String value from the strings.xml
file further as like that:
fun showPostsInRadius(modelSearchParams: ModelSearch, onResult: (Array<Post>?, Boolean, String?) -> Unit){
val retrofit = ServiceBuilder.buildService(RestApi::class.java)
retrofit.showPostsInRadius(Build.VERSION.SDK_INT, modelSearchParams).enqueue(
object : Callback<Array<ModelSearchResult>> {
override fun onFailure(call: Call<Array<ModelSearchResult>>, t: Throwable) {
onResult(null, false, Resources.getSystem().getString(R.string.connection_error_login))
println(t)
}
...
This line gives error:
onResult(null, false, Resources.getSystem().getString(R.string.connection_error_login))
Error:
W/ResourceType: No known package when getting value for resource number 0x7f0f003c
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jaskierltd.goodtogether, PID: 15205
android.content.res.Resources$NotFoundException: String resource ID #0x7f0f003c
at android.content.res.Resources.getText(Resources.java:338)
at android.content.res.Resources.getString(Resources.java:432)
at com.jaskierltd.goodtogether.network.RestApiService$showPostsInRadius$1.onFailure(RestApiService.kt:145)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$2.run(ExecutorCallAdapterFactory.java:79)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Should I configure anything related to strings.xml file or should I call this with another method? None of existing topics helped.
解决方案
Since no-one provided any answer how to avoid context, the only way is to use context
or get the ID
of the STRING
object and send back.
Option #1:
// Place anywhere you want to get the String
fun getID(): Int{
R.string.error_no_location
}
// Use this inside Activity
println(getString(getID()))
Option #2:
fun getID(context: Context){
println(context.getString(R.string.error_no_location))
}
推荐阅读
- sql - 获取用户的名字、城市和当月乘坐的次数
- ruby-on-rails - Rails:回形针上传时 AWS S3 访问被拒绝错误
- python - Python 如果它的相同输出不发送消息
- ajax - 通过laravel中的ajax在表中显示来自sql查询的数据
- scala - 如何在 Scala 中使用 Heroku DATABASE_URL 环境变量?
- c# - 是否可以将 HttpServer 和 WPF 作为单个应用程序运行?
- java - 找不到类?com.google.cloud.sql.mysql.SocketFactory 尝试连接云 sql
- java - 更改 ArrayList 中元素顺序的最快方法是什么?
- python-3.x - AWS Lambda:在运行时获取当前重试次数
- git - 带有预提交钩子的 Git 提交,为什么会得到不同的结果?