首页 > 解决方案 > Kotlin 失败交付结果

问题描述

在一个Kotlin应用程序中,我们正在尝试将 jpg 文件上传到 ImageView 小部件其他类似的帖子链接

DCIM我们担心的一个问题是通过选择并选择上传上传将图像(jpg)添加到模拟器Device Manager File我们需要DCIM在第一次运行应用程序时导航到这个位置应用程序不知道jpg在哪里。我们将发布 Logcat 代码和 XML 代码

08-29 16:39:27.444 18552-18675/com.androidstackoverflow.habittrainer E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE) 
08-29 16:39:27.445 18552-18675/com.androidstackoverflow.habittrainer I/chatty: uid=10084(u0_a84) Binder:18552_3 identical 3 lines
08-29 16:39:27.445 18552-18675/com.androidstackoverflow.habittrainer E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE) 
08-29 16:39:28.329 18552-18593/com.androidstackoverflow.habittrainer D/EGL_emulation: eglMakeCurrent: 0xa51c7820: ver 2 0 (tinfo 0xa518b060)
08-29 16:39:28.331 18552-18685/com.androidstackoverflow.habittrainer E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE) 
08-29 16:39:28.332 18552-18685/com.androidstackoverflow.habittrainer I/chatty: uid=10084(u0_a84) hwuiTask2 identical 3 lines
08-29 16:39:28.333 18552-18685/com.androidstackoverflow.habittrainer E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE) 
08-29 16:39:28.777 18552-18552/com.androidstackoverflow.habittrainer W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
08-29 16:39:28.798 18552-18552/com.androidstackoverflow.habittrainer I/AssistStructure: Flattened final assist data: 3020 bytes, containing 1 windows, 11 views
08-29 16:39:30.252 18552-18552/com.androidstackoverflow.habittrainer I/System.out: =============================== Intent { act=android.intent.action.CHOOSER (has extras) }
08-29 16:39:30.252 18552-18552/com.androidstackoverflow.habittrainer D/CreateHabitActivity: Image was sent
08-29 16:39:30.755 18552-18593/com.androidstackoverflow.habittrainer D/EGL_emulation: eglMakeCurrent: 0xa51c7820: ver 2 0 (tinfo 0xa518b060)
08-29 16:39:30.818 18552-18593/com.androidstackoverflow.habittrainer D/OpenGLRenderer: endAllActiveAnimators on 0x8bfaf980 (RippleDrawable) with handle 0x9957fbf0
08-29 16:39:45.615 18552-18559/com.androidstackoverflow.habittrainer I/zygote: Do partial code cache collection, code=24KB, data=29KB
08-29 16:39:45.618 18552-18559/com.androidstackoverflow.habittrainer I/zygote: After code cache collection, code=24KB, data=29KB
    Increasing code cache capacity to 128KB
08-29 16:39:45.622 18552-18552/com.androidstackoverflow.habittrainer D/CreateHabitActivity: An Image WAS Choosen
08-29 16:39:45.623 18552-18552/com.androidstackoverflow.habittrainer I/System.out: ------------------------------ 1   more -1
08-29 16:39:45.661 18552-18552/com.androidstackoverflow.habittrainer D/AndroidRuntime: Shutting down VM
08-29 16:39:45.703 18552-18552/com.androidstackoverflow.habittrainer E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.androidstackoverflow.habittrainer, PID: 18552
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/primary:Pictures/water.jpg flg=0x1 }} to activity {com.androidstackoverflow.habittrainer/com.androidstackoverflow.habittrainer.CreateHabitActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4324)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4367)
        at android.app.ActivityThread.-wrap19(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        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)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
        at com.androidstackoverflow.habittrainer.CreateHabitActivity.onActivityResult(CreateHabitActivity.kt:71)
        at android.app.Activity.dispatchActivityResult(Activity.java:7235)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4320)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4367) 
        at android.app.ActivityThread.-wrap19(Unknown Source:0) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1649) 
        at android.os.Handler.dispatchMessage(Handler.java:105) 
        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) 

创建习惯活动文件

class CreateHabitActivity : AppCompatActivity() {

    private val TAG = CreateHabitActivity::class.java.simpleName

    private val CHOOSE_IMAGE_REQUEST = 1
    private var imageBitmap: Bitmap? = null

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

    }// end onCreate

    fun onstoreHabit(view: View) {
        if(etTitle.text.toString().isBlank() && 
    etDescription.text.toString().isBlank()) {
            Log.d(TAG, "No Image")
            displayErrorMsg("You Need TITLE and DESCTIPTIOM")
            return
        }else if(imageBitmap == null){
            displayErrorMsg("Select Image")
            Log.d(TAG,"Image Missing")
            return

        }
            tvError.visibility = View.INVISIBLE
    }

    private fun displayErrorMsg(msg: String) {
        tvError.text = msg
        tvError.visibility = View.VISIBLE
    }

    fun onChooseImage(view:View){
        val intent = Intent()
        intent.type = "image/*"
        intent.action = Intent.ACTION_GET_CONTENT

        val chooser = Intent.createChooser(intent,"Choose Image for Habit")
        startActivityForResult(chooser, CHOOSE_IMAGE_REQUEST)
        System.out.println("=============================== "+chooser)
        Log .d(TAG,"Image was sent" )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: 
    Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if(requestCode == CHOOSE_IMAGE_REQUEST && resultCode == 
    Activity.RESULT_OK
        && data != null && data.data != null){
            Log.d(TAG,"An Image WAS Choosen")
            System.out.println("------------------------------ "+requestCode+"   
        more "+resultCode)
            // request is 1 and result is -1
            val bitmap = tryReadBitmap(data.data)

            bitmap?.let {
                this.imageBitmap = bitmap
                ivIcon.setImageBitmap(bitmap)
                // Line of code above on a null object reference
                Log.d(TAG,"We Updated and Read Bitmap")

            }
        }
    }

    private fun tryReadBitmap(data: Uri?): Bitmap?{
        return try{
            MediaStore.Images.Media.getBitmap(contentResolver,data)
        }catch (e:IOException){
            e.printStackTrace()
            null
        }
    }
}// end Class

XML 代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/color_lightGray"
    android:padding="8dp"
    tools:context=".CreateHabitActivity">
    <EditText
        android:id="@+id/etTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="40dp"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Eat an Apple" />

    <EditText
        android:id="@+id/etDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="100dp"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Apple a Day No Doctor"
        android:inputType="textImeMultiLine"
        android:lines="2" />

    <Button
        android:id="@+id/btnChooseImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="160dp"
        android:layout_weight="1"
        android:onClick="onChooseImage"
        android:text="Choose Image"
        android:textColor="@color/color_Black"
        android:textSize="18sp"
        android:textStyle="bold" />

    <ImageView

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="220dp"
        android:contentDescription="Select Image"
        android:padding="10dp" />

    <TextView
        android:id="@+id/tvError"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="280dp"
        android:layout_weight="1"
        android:text="Error"
        android:visibility="invisible" />

    <Button
        android:id="@+id/btnSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="340dp"
        android:layout_weight="1"
        android:onClick="onstoreHabit"
        android:text="SAVE"
        android:textColor="@color/color_Black"
        android:textSize="18sp"
        android:textStyle="bold" />

</RelativeLayout>

我们的问题是如何使用这行代码 ivIcon.setImageBitmap(bitmap) 修复空对象引用错误

我们已经通过添加和删除进行了测试?这与这行代码 bitmap?.let和这一行data: Intent?)并更改了此声明 private var imageBitmap: Bitmap? = null

这个

System.out.println("------------------------------ "+requestCode+"   more "+resultCode) 

正在为我们认为不正确的 resultCode 返回 -1

标签: androidkotlinnull

解决方案


正如@jaychang0917 所说,您的 ivIcon 在 XML 文件中不存在,因为它没有名称(id)这两个 ImageView 可以具有相同的 id(名称),正如您所指出的,这里的注意事项是您需要小心您和您从哪里导入。Kotlin 中的这种新行为是不使用 findviewbyid 的权衡

所以是的,您可以在两个单独的 XML 文件中使用相同的 id(名称)

发布此答案是为了澄清 Grendel 的评论 无需投票它是有用的,我们在这里分享和学习


推荐阅读