Kotlin失败交付结果

时间:2018-08-30 00:16:52

标签: android kotlin null

Kotlin应用中,我们试图将jpg文件上传到ImageView小部件,其他类似的帖子LINK

我们要担心的是,通过在DCIM中选择Device Manager File并选择上载,将图像(jpg)添加到模拟器中,我们需要导航到该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) 

CreateHabitActivity文件

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)将其固定在空对象引用ERROR上

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

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

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

2 个答案:

答案 0 :(得分:1)

  

由于:java.lang.NullPointerException:尝试调用虚拟   方法“无效”   android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)'   空对象引用

您的ivIcon为空,因此抛出NullPointerException。请确保它存在。

答案 1 :(得分:1)

@ jaychang0917表示您的ivIcon在XML文件中不存在,因为它没有名称(id)两个ImageView可以具有相同的ID(名称)。注意,您在这里注意到的是,您需要小心您和您从哪里导入。 Kotlin中的这种新行为是不使用findviewbyid

的折衷方案

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

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