代码之家  ›  专栏  ›  技术社区  ›  Vector

Kotlin未能交付结果

  •  0
  • Vector  · 技术社区  · 8 年前

    在一个 Kotlin 我们正在尝试上传一个jpg文件到一个ImageView小部件其他类似的帖子 LINK

    DCIM 在 Device Manager File 选择上传上传我们需要导航到这个 位置应用程序第一次运行时,应用程序不知道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) 
    

    CreateHabitatity文件

    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?.let 这条线呢 data: Intent? private var imageBitmap: Bitmap? = null

    这个

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

    2 回复  |  直到 8 年前
        1
  •  1
  •   jaychang0917    8 年前

    方法“无效” android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)'在一个

    你的 ivIcon 为null,因此它抛出 NullPointerException

        2
  •  1
  •   James_Duh    8 年前

    正如@jaychang0917所说,您的ivIcon在XML文件中不存在,因为它没有名称(id),两个ImageView的id(名称)可能是相同的。Kotlin中的这种新行为是不使用findviewbyid的代价

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

    这个答案被贴出来是为了澄清格伦德尔的评论,没有必要投票认为是有用的