代码之家  ›  专栏  ›  技术社区  ›  J A S K I E R

如何修复资源$NotFoundException:Kotlin中没有上下文的字符串资源?

  •  0
  • J A S K I E R  · 技术社区  · 5 年前

    安卓,科特林。

    RestApiService 用于请求的文件,并从 strings.xml

    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)
                }
    ...
    

    这一行给出了错误:

    onResult(null, false, Resources.getSystem().getString(R.string.connection_error_login))
    

    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)
    

    0 回复  |  直到 5 年前
        1
  •  0
  •   J A S K I E R    5 年前

    由于没有人提供任何关于如何避免上下文的答案, 是用 context 或者得到 ID STRING 对象并发回。

    // Place anywhere you want to get the String
    fun getID(): Int{
       R.string.error_no_location
    }
    
    // Use this inside Activity
    println(getString(getID()))
    

    选项2:

    fun getID(context: Context){
       println(context.getString(R.string.error_no_location))
    }