使用声明为“Bundle”对象的空变量初始化“intent.extras”

Posted

技术标签:

【中文标题】使用声明为“Bundle”对象的空变量初始化“intent.extras”【英文标题】:Initializing "intent.extras" with a null variable declared as "Bundle" object 【发布时间】:2019-04-08 17:26:32 【问题描述】:

b 初始化为intent.extra 时存在类型不匹配。虽然bBundle? 类型,而intent.extra 不采用null 值,而且Bundle 也不能为空。

请为此问题提出解决方案。该应用程序在安装到 android 手机并准备运行时不断崩溃。

代码主体中的以下代码 sn-p 仅显示警告,但仅在启动时导致应用程序崩溃。

    import android.app.Activity
    import android.content.Context
    import android.content.Intent
    import android.graphics.Bitmap
    import android.graphics.BitmapFactory
    import android.graphics.drawable.BitmapDrawable
    import android.os.Bundle
    import android.provider.MediaStore
    import android.support.design.widget.Snackbar
    import android.support.design.widget.NavigationView
    import android.support.v4.view.GravityCompat
    import android.support.v7.app.ActionBarDrawerToggle
    import android.support.v7.app.AppCompatActivity
    import android.view.Menu
    import android.view.MenuItem
    import android.view.View
    import android.view.ViewGroup
    import android.widget.BaseAdapter
    import android.widget.Toast
    import com.example.debo.kickv01.R.id.lvTweets
    import kotlinx.android.synthetic.main.activity_navig.*
    import kotlinx.android.synthetic.main.app_bar_navig.*

    import com.example.debo.kickv01.saved
    import com.example.debo.kickv01.login as lg
    import com.google.firebase.auth.FirebaseAuth
    import com.google.firebase.database.FirebaseDatabase
    import com.google.firebase.storage.FirebaseStorage
    import kotlinx.android.synthetic.main.activity_login.*
    import kotlinx.android.synthetic.main.activity_saved.view.*
    import java.io.ByteArrayOutputStream
    import java.text.SimpleDateFormat
    import java.util.*

    class navig : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener 
        private var mAuth: FirebaseAuth?=null
        private var database= FirebaseDatabase.getInstance()
        private var myRef = database.reference

        var list_T=ArrayList<ticket>()
        var adaptor:MyPrjAdaptor?=null
        var UserUID:String?=null
        var myEmail:String?=null
        // var b:Bundle= intent.extras
        override fun onCreate(savedInstanceState: Bundle?) 
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_navig)
            val toolbar= null
            var b:Bundle = intent.extras
            myEmail = b.getString("email")
            UserUID = b.getString("uid")

            list_T.add(ticket("0","him","url","add"))
            list_T.add(ticket("0","him","url","debo"))
            list_T.add(ticket("0","him","url","debo_2"))

            adaptor=MyPrjAdaptor(this,list_T)
            lvTweets.adapter=adaptor

            fab.setOnClickListener  view ->
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show()
            

            val toggle = ActionBarDrawerToggle(
                    this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
            drawer_layout.addDrawerListener(toggle)
            toggle.syncState()

            nav_view.setNavigationItemSelectedListener(this)
        

        override fun onNavigationItemSelected(item: MenuItem): Boolean 
            // Handle navigation view item clicks here.
            when (item.itemId) 
                R.id.nav_home -> 
                    // Handle the camera action
                    var intent = Intent(this, navig::class.java)
                    startActivity(intent)
                
                R.id.nav_explore -> 
                    var intent = Intent(this, explore::class.java)
                    startActivity(intent)
                
                R.id.nav_Saved -> 
                    var intent = Intent(this, saved::class.java)
                    startActivity(intent)
                
                R.id.nav_actions -> 
                    var intent = Intent(this, actions::class.java)
                    startActivity(intent)
                
                R.id.nav_login -> 
                    var intent = Intent(this, com.example.debo.kickv01.login::class.java)
                    startActivity(intent)
                
            

            drawer_layout.closeDrawer(GravityCompat.START)
            return true
        

        inner class MyPrjAdaptor: BaseAdapter
            var listNotesAdaptor= ArrayList<ticket>()
            var context:Context?=null
            constructor(context: Context,listNotesAdaptor: ArrayList<ticket>):super()
                this.listNotesAdaptor=listNotesAdaptor
                this.context=context
            

            override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View 
                var myTweet=listNotesAdaptor[position]

                if (myTweet.tweetPersonUID.equals("add")) 
                    var myView = layoutInflater.inflate(R.layout.activity_saved, null)
                    myView.etAttach.setOnClickListener 
                        loadImage()
                    

                    myView.etPost.setOnClickListener 
                        myRef.child("posts").push().setValue(PostInfo(UserUID!!,
                                myView.etProject.text.toString(),
                                myView.etDescription.text.toString(),
                                DownloadURL!!))

                    
                    return myView
                else
                    var myView = layoutInflater.inflate(R.layout.activity_explore, null)
                    return myView
                
            

            override fun getItem(position: Int): Any 
                return listNotesAdaptor[position]
            

            override fun getItemId(position: Int): Long 
                return position.toLong()
            

            override fun getCount(): Int 
                return listNotesAdaptor.size
            
        

        override fun onBackPressed() 
            if (drawer_layout.isDrawerOpen(GravityCompat.START)) 
                drawer_layout.closeDrawer(GravityCompat.START)
             else 
                super.onBackPressed()
            
        

        override fun onCreateOptionsMenu(menu: Menu): Boolean 
            // Inflate the menu; this adds items to the action bar if it is present.
            menuInflater.inflate(R.menu.navig, menu)
            return true
        

        override fun onOptionsItemSelected(item: MenuItem): Boolean 
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            when (item.itemId) 
                R.id.action_settings -> return true
                else -> return super.onOptionsItemSelected(item)
            
        

        var PICK_IMAGE_CODE=123
        fun loadImage()
            var intent=Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent, PICK_IMAGE_CODE)
        

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

            if(requestCode==PICK_IMAGE_CODE && resultCode== Activity.RESULT_OK && data!=null)
                val selectedImage=data.data
                val filePathColum = arrayOf(MediaStore.Images.Media.DATA)
                val cursor= contentResolver.query(selectedImage,filePathColum,null,null,null)
                cursor.moveToFirst()
                val columIndex= cursor.getColumnIndex(filePathColum[0])
                val picturepath= cursor.getString(columIndex)
                cursor.close()
                UploadImage(BitmapFactory.decodeFile(picturepath))
            
        

        var DownloadURL:String?=null
        fun UploadImage(bitmap: Bitmap)
            var currentUser= mAuth!!.currentUser

            val storage = FirebaseStorage.getInstance()
            val storageRef= storage.getReferenceFromUrl("gs://kick-13840.appspot.com")
            val df= SimpleDateFormat("ddMMyyHHmmss")
            val dataobj= Date()
            val imagePath= SplitString(myEmail!!) + "."+ df.format(dataobj)+ ".jpg"
            val ImageRef= storageRef.child("imagePost/"+imagePath)


            val baos= ByteArrayOutputStream()
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos)
            val data=baos.toByteArray()
            val uploadTask=ImageRef.putBytes(data)
            uploadTask.addOnFailureListener
                Toast.makeText(applicationContext,"fail to upload", Toast.LENGTH_LONG).show()

            .addOnSuccessListener  taskSnapshot ->
                DownloadURL = taskSnapshot.storage.downloadUrl.toString()
            
        

        fun SplitString(email: String):String
            val split= email.split("@")
            return split[0]
        
    

【问题讨论】:

你试过private val bundle by lazy intent.extras 吗? 错误或问题是什么? 这个值 'bundle' 如何帮助将变量 'b' 变成一个非空对象。 @EpicPandaForce 哦,我刚刚将 b 重命名为 bundle,因为良好的编码习惯包括“不使用单字母变量名”(大部分时间)。 问题是“intent.extras”不采用空值,因为“b”是“捆绑?”对象“intent.extras”显示提示为“类型不匹配。必需:找到捆绑:捆绑?” -@AbhayKoradiya 【参考方案1】:

b 的类型为Bundle,而intent.extras 返回Bundle?Intent.getExtras() 的注释为@Nullable,如果您查看它的代码),如IDE 所示。您需要使用非空断言运算符 !! 或将 b 更改为键入 Bundle?

【讨论】:

以上是关于使用声明为“Bundle”对象的空变量初始化“intent.extras”的主要内容,如果未能解决你的问题,请参考以下文章

Kotlin空安全 ① ( Kotlin 的空安全机制 | 变量可空性 | 默认变量不可赋空值 | 声明可空类型变量 )

如果声明但未初始化,对象的变量是不是使用内存空间?

036_面向对象_09_static变量和方法

javaScript数组遍历

mMap.setOnMapClickListener(this) 中的空对象错误;

学习:类和对象——静态成员变量和函数