Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么我在尝试将图像分配给GridView时会出现此NullPointerException?_Java_Android_Kotlin - Fatal编程技术网

Java 为什么我在尝试将图像分配给GridView时会出现此NullPointerException?

Java 为什么我在尝试将图像分配给GridView时会出现此NullPointerException?,java,android,kotlin,Java,Android,Kotlin,我有一个GridView,其中应用了与对象实例关联的不同图像。我使用RealPathUtil对象来处理文件路径的检索,以便解码和显示位图 当我打开将这些图像分配给网格的活动时,我的应用程序会自动崩溃,并在声明此if子句的行上显示一个NullPointerException: else if ("content".equals(uri.scheme!!, ignoreCase = true)) { // Return the remote address

我有一个GridView,其中应用了与对象实例关联的不同图像。我使用RealPathUtil对象来处理文件路径的检索,以便解码和显示位图

当我打开将这些图像分配给网格的活动时,我的应用程序会自动崩溃,并在声明此if子句的行上显示一个NullPointerException:

else if ("content".equals(uri.scheme!!, ignoreCase = true)) {
       // Return the remote address
       return if (isGooglePhotosUri(uri)) uri.lastPathSegment else getDataColumn(context, uri, null, null)
}
我熟悉NullPointerException以及它们通常被抛出的原因,但我不太明白为什么会给出这个。由于我将图像显示方法从URI切换到位图,所以我尝试分配的图像都没有正确显示。当我使用URI将图像分配给ImageView时,这个问题没有出现,但我不得不切换,因为这会在其他设备上产生问题

下面是处理GridView的适配器中导致出现此错误的代码。当tempUri的值设置到末尾时,会发生以下错误:

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val view: View = View.inflate(activity,R.layout.layout_adapter,null)

        // Get view data from UI elements - image, name, and count
        val tv_lang = view.findViewById(R.id.itemName) as TextView
        val imageView = view.findViewById<ImageView>(R.id.itemImage)
        val itemCount = view.findViewById(R.id.itemCount) as TextView

        // Assign data to UI elements
        tv_lang.text = itemList[position].itemNote
        itemCount.text = itemList[position].itemCount.toString()
        val itemImage = itemList[position].itemImage


        // Assign each item image to corresponding grid ImageView
        tempUri = Uri.parse(itemImage)
        realPathUri = RealPathUtil.getRealPath(parent!!.context, tempUri).toString()
        val myBitmap = BitmapFactory.decodeFile(realPathUri)
        imageView.setImageBitmap(myBitmap)

        return view
}
override-fun-getView(位置:Int,convertView:View?,父级:ViewGroup?):视图{
val视图:视图=视图。充气(活动,右布局。布局适配器,空)
//从UI元素(图像、名称和计数)获取视图数据
val tv_lang=view.findviewbyd(R.id.itemName)作为文本视图
val imageView=view.findViewById(R.id.itemImage)
val itemCount=view.findviewbyd(R.id.itemCount)作为TextView
//将数据分配给UI元素
tv_lang.text=itemList[position]。itemNote
itemCount.text=itemList[position].itemCount.toString()
val itemImage=itemList[position].itemImage
//将每个项目图像指定给相应的网格图像视图
tempUri=Uri.parse(itemImage)
realPathUri=RealPathUtil.getRealPath(parent!!.context,tempUri).toString()
val myBitmap=BitmapFactory.decodeFile(realPathUri)
设置图像位图(myBitmap)
返回视图
}
RealPathUtil

    object RealPathUtil {
        // SDK <= 11 && SDK < 19
        /* Calls either getRealPathFromURIAPI11to19 or getRealPathFromURIAPI19, depending upon which API the software detects the user running the app through. */
        @SuppressLint("ObsoleteSdkInt")
        fun getRealPath(context: Context, fileUri: Uri): String? {
            return if (Build.VERSION.SDK_INT < 19) {
                getRealPathFromURIAPI11to18(context, fileUri)
            } else {
                getRealPathFromURIAPI19(context, fileUri)
            }
        }

        /* Uses other methods within the RealPathUtil object to determine
        * location list file path based upon the user's phone's active API (11-18). */
        @SuppressLint("NewApi")
        fun getRealPathFromURIAPI11to18(context: Context, contentUri: Uri): String? {
            val project = arrayOf(MediaStore.Images.Media.DATA)
            var result: String? = ""

            val cursorLoader = CursorLoader(context, contentUri, project, null, null, null)
            val cursor = cursorLoader.loadInBackground()

            if (cursor != null) {
                val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                cursor.moveToFirst()
                result = cursor.getString(columnIndex)
                cursor.close()
            }
            return result
        }

        /* Uses other methods within the RealPathUtil object to determine location list file
        path based upon the user's phone's active API (19). */
        @SuppressLint("NewApi")
        fun getRealPathFromURIAPI19(context: Context, uri: Uri): String? {
            val isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT

            // Create the DocumentProvider
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                // Safe cast the ExternalStorageProvider
                if (isExternalStorageDocument(uri)) {
                    val docId = DocumentsContract.getDocumentId(uri)
                    val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                    val type = split[0]

                    if ("primary".equals(type, ignoreCase = true)) {
                        return Environment.getExternalStorageDirectory().toString() + "/" + split[1]
                    }
                } else if (isDownloadsDocument(uri)) {
                    var cursor: Cursor? = null

                    try {
                        cursor = context.contentResolver.query(uri, arrayOf(MediaStore.MediaColumns.DISPLAY_NAME), null, null, null)
                        cursor!!.moveToNext()

                        val fileName = cursor.getString(0)
                        val path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName

                        if (!TextUtils.isEmpty(path)) {
                            return path
                        }
                    } finally {
                        cursor?.close()
                    }

                    val id = DocumentsContract.getDocumentId(uri)

                    if (id.startsWith("raw:")) {
                        return id.replaceFirst("raw:".toRegex(), "")
                    }
                    val contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads"), java.lang.Long.valueOf(id))

                    return getDataColumn(context, contentUri, null, null)
                } else if (isMediaDocument(uri)) {
                    val docId = DocumentsContract.getDocumentId(uri)
                    val split = docId.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                    val type = split[0]

                    var contentUri: Uri? = null

                    when (type) {
                        "image" -> contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
                        "video" -> contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
                        "audio" -> contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
                    }

                    val selection = "_id=?"
                    val selectionArgs = arrayOf(split[1])

                    return getDataColumn(context, contentUri, selection, selectionArgs)
                } // Media Provider
                // Downloads Provider
            } else if ("content".equals(uri.scheme!!, ignoreCase = true)) {
                // Return the remote address
                return if (isGooglePhotosUri(uri))
                    uri.lastPathSegment
                else
                    getDataColumn(context, uri, null, null) /** Collapse this if-else block into one line if any new, unexplained I/O issues arise. */
            } else if ("file".equals(uri.scheme!!, ignoreCase = true)) {
                return uri.path
            } // File
            // MediaStore

            return null
        }

        private fun getDataColumn(context: Context, uri: Uri?, selection: String?, selectionArgs: Array<String>?): String? {
            var cursor: Cursor? = null
            val column = "_data"
            val projection = arrayOf(column)

            try {
                cursor = context.contentResolver.query(uri!!, projection, selection, selectionArgs, null)

                if (cursor != null && cursor.moveToFirst()) {
                    val index = cursor.getColumnIndexOrThrow(column)
                    return cursor.getString(index)
                }
            } finally {
                cursor?.close()
            }
            return null
        }

        /* Takes the URI being analyzed and determines whether the URI authority is ExternalFileProvider or not. */
        private fun isExternalStorageDocument(uri: Uri): Boolean {
            return "com.android.externalstorage.documents" == uri.authority
        }

        /* Takes the URI being analyzed and determines whether the URI authority is DownloadsProvider or not. */
        private fun isDownloadsDocument(uri: Uri): Boolean {
            return "com.android.providers.downloads.documents" == uri.authority
        }

        /* Takes the URI being analyzed and determines whether the URI authority is MediaProvider or not. */
        private fun isMediaDocument(uri: Uri): Boolean {
            return "com.android.providers.media.documents" == uri.authority
        }

        /* Takes the URI being analyzed and determines whether the URI authority is Google Photos or not. */
        private fun isGooglePhotosUri(uri: Uri): Boolean {
            return "com.google.android.apps.photos.content" == uri.authority
        }
    }
对象RealPathUtil{
//SDK=Build.VERSION\u CODES.KITKAT
//创建文档提供者
if(isKitKat&&DocumentsContract.isDocumentUri(context,uri)){
//安全强制转换ExternalStorageProvider
if(isExternalStorageDocument(uri)){
val docId=DocumentsContract.getDocumentId(uri)
val split=docId.split(“:”.toRegex()).dropLastWhile{it.isEmpty()}.toTypedArray()
val类型=拆分[0]
if(“primary”.equals(type,ignoreCase=true)){
返回Environment.getExternalStorageDirectory().toString()+“/”+split[1]
}
}else if(isDownloadsDocument(uri)){
变量游标:游标?=null
试一试{
cursor=context.contentResolver.query(uri,arrayOf(MediaStore.MediaColumns.DISPLAY_NAME),null,null,null)
光标!!.moveToNext()
val fileName=cursor.getString(0)
val path=Environment.getExternalStorageDirectory().toString()+“/Download/”+文件名
如果(!TextUtils.isEmpty(路径)){
返回路径
}
}最后{
光标?.close()
}
val id=DocumentsContract.getDocumentId(uri)
if(id.startsWith(“原始:)){
返回id.replaceFirst(“原始:”.toRegex(),“”)
}
val contentUri=ContentUris.withAppendedId(Uri.parse(“content://downloads),java.lang.Long.valueOf(id))
返回getDataColumn(上下文、contentUri、null、null)
}else if(isMediaDocument(uri)){
val docId=DocumentsContract.getDocumentId(uri)
val split=docId.split(“:”.toRegex()).dropLastWhile{it.isEmpty()}.toTypedArray()
val类型=拆分[0]
var contentUri:Uri?=null
何时(输入){
“image”->contentUri=MediaStore.Images.Media.EXTERNAL\u CONTENT\u URI
“视频”->contentUri=MediaStore.video.Media.EXTERNAL\u CONTENT\u URI
“音频”->contentUri=MediaStore.audio.Media.EXTERNAL\u CONTENT\u URI
}
val selection=“\u id=?”
val selectionArgs=arrayOf(拆分[1])
返回getDataColumn(上下文、contentUri、选择、selectionArgs)
}//媒体提供商
//下载提供商
}else如果(“content.equals(uri.scheme!!,ignoreCase=true)){
//返回远程地址
返回if(iGoogle PhotoSuri(uri))
uri.lastPathSegment
其他的
getDataColumn(上下文、uri、null、null)/**如果出现任何新的、无法解释的I/O问题,请将此if-else块折叠成一行*/
}else如果(“file.equals(uri.scheme!!,ignoreCase=true)){
返回uri.path
}//文件
//媒体商店
返回空
}
private fun getDataColumn(上下文:上下文,uri:uri?,选择:字符串?,选择:数组?):字符串?{
变量游标:游标?=null
val column=“\u数据”
val投影=阵列(列)
试一试{
cursor=context.contentResolver.query(uri!!,投影,选择,selectionArgs,null)
if(cursor!=null&&cursor.moveToFirst()){
val index=cursor.getColumnIndexOrThrow(列)
返回cursor.getString(索引)
}
}最后{
C
else if ("content".equals(uri.scheme!!, ignoreCase = true)) {
else if (uri.scheme?.equals("content", ignoreCase = true) == true) {
public actual fun String?.equals(other: String?, ignoreCase: Boolean = false): Boolean { 
if (this === null) 
    return other === null
return if (!ignoreCase) (this as java.lang.String).equals(other) 
       else (this as java.lang.String).equalsIgnoreCase(other) 
}