从Gallary获取图像并将其设置在recyclerview中

如何解决从Gallary获取图像并将其设置在recyclerview中

我有一个回收站视图,并且必须在回收站视图中设置图像。我已经获得许可并以表格的形式获取了图像,但是必须从表格中将其发送到recyclerview卡中。

我尝试了位图处理,但没有成功。

MainActivity:

    package com.example.itemgetset
    
    import android.annotation.SuppressLint
    import android.app.Activity
    import android.content.Intent
    import android.os.Bundle
    import android.os.Handler
    import android.os.Message
    import android.view.Menu
    import android.view.MenuItem
    import android.view.View
    import android.widget.Button
    import android.widget.LinearLayout
    import androidx.appcompat.app.AppCompatActivity
    import androidx.recyclerview.widget.GridLayoutManager
    import androidx.recyclerview.widget.LinearLayoutManager
    import androidx.recyclerview.widget.RecyclerView
    
    @Suppress("DEPRECATION")
    class MainActivity : AppCompatActivity() {
    
        lateinit var activity: Activity
        val userList = ArrayList<ProductInfoGetSet>()
        private lateinit var btnProductAdd: Button
        lateinit var llEmptyView: LinearLayout
        lateinit var llMain: LinearLayout
        lateinit var recyclerView: RecyclerView
        private lateinit var llFab: LinearLayout
        private lateinit var linearLayoutManager: LinearLayoutManager
        private lateinit var gridLayoutManager: GridLayoutManager
        private lateinit var adapter: CustomAdapter
        private var isforlist = true
    
        companion object {
            var handler: Handler = Handler()
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            activity = this
            initView()
            onClicks()
            setUpData()
    
            handler = @SuppressLint("HandlerLeak")
            object : Handler() {
                override fun handleMessage(msg: Message) {
                    if (msg.what == 111) {
                        val temp: Temp = msg.obj as Temp
    
                        if (temp.id == "") {
                            userList.add(
                                ProductInfoGetSet(
                                    (userList.size + 1).toString(),temp.image,temp.name,temp.quantity,temp.price,)
                            )
                            adapter = CustomAdapter(activity,userList,isforlist)
                            recyclerView.adapter = adapter
                        } else {
                            for (i in userList.indices) {
                                if (userList[i].id == temp.id) {
                                    userList[i].id = temp.id
                                    userList[i].image = temp.image
                                    userList[i].name = temp.name
                                    userList[i].quantity = temp.quantity
                                    userList[i].price = temp.price
                                }
                            }
                            adapter.notifyDataSetChanged()
                        }
                    }
                    if (userList.size > 0) {
                        llEmptyView.visibility = View.GONE
                        llMain.visibility = View.VISIBLE
                    } else {
                        llEmptyView.visibility = View.VISIBLE
                        llMain.visibility = View.GONE
                    }
                }
            }
        }
    
        private fun changeLayoutManager() {
            if (recyclerView.layoutManager == linearLayoutManager) {
                recyclerView.layoutManager = gridLayoutManager
            } else {
                recyclerView.layoutManager = linearLayoutManager
            }
        }
    
        private fun initView() {
            btnProductAdd = findViewById(R.id.btn_product_add)
            llFab = findViewById(R.id.ll_fab)
            llEmptyView = findViewById(R.id.llEmptyView)
            llMain = findViewById(R.id.llMain)
            recyclerView = findViewById(R.id.recycler_view)
            recyclerView.layoutManager = LinearLayoutManager(this)
            linearLayoutManager = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)
            gridLayoutManager = GridLayoutManager(this,2)
        }
    
        private fun onClicks() {
            btnProductAdd.setOnClickListener {
                val intent = Intent(this@MainActivity,AddDetails::class.java)
                intent.putExtra("isFor","Add")
                startActivity(intent)
            }
            llFab.setOnClickListener {
                val intent = Intent(this@MainActivity,"Add")
                startActivity(intent)
            }
        }
    
        private fun setUpData() {
            if (userList.size > 0) {
                llEmptyView.visibility = View.GONE
                llMain.visibility = View.VISIBLE
            } else {
                llEmptyView.visibility = View.VISIBLE
                llMain.visibility = View.GONE
            }
        }
    
        override fun onCreateOptionsMenu(menu: Menu): Boolean {
            menuInflater.inflate(R.menu.menu_main,menu)
            return true
        }
    
        override fun onOptionsItemSelected(item: MenuItem): Boolean {
            if (item.itemId == R.id.menu_view) {
                if (userList.size > 0) {
                    changeLayoutManager()
                }
                return true
            }
            return super.onOptionsItemSelected(item)
        }
    }

CustomAdapter:

    package com.example.itemgetset
    
    import android.app.Activity
    import android.app.AlertDialog
    import android.content.ContentValues.TAG
    import android.content.Intent
    import android.os.Build
    import android.util.Log
    import android.view.LayoutInflater
    import android.view.View
    import android.view.ViewGroup
    import android.widget.ImageView
    import android.widget.LinearLayout
    import android.widget.PopupMenu
    import android.widget.TextView
    import androidx.annotation.RequiresApi
    import androidx.recyclerview.widget.RecyclerView
    import com.google.android.material.snackbar.Snackbar
    
    @Suppress("UNREACHABLE_CODE")
    class CustomAdapter(
        private var activity: Activity,private val userList: ArrayList<ProductInfoGetSet>,private var isforlist: Boolean,) :
        RecyclerView.Adapter<CustomAdapter.ViewHolder>() {
    
        override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): ViewHolder {
            val itemview =
                LayoutInflater.from(parent.context).inflate(R.layout.list_layout,parent,false)
            return ViewHolder(itemview)
        }
    
        @RequiresApi(Build.VERSION_CODES.N)
        override fun onBindViewHolder(holder: ViewHolder,position: Int) {
    
            val productInfoGetSet: ProductInfoGetSet = userList[position]
    
            holder.txtId.text = productInfoGetSet.id
            holder.txtName.text = productInfoGetSet.name
            holder.txtQuantity.text = productInfoGetSet.quantity
            holder.txtPrice.text = productInfoGetSet.price
    
            val id = userList[position].id
            Log.e(TAG,"List item ID: $id")
    
    
            holder.buttonViewOption.setOnClickListener {
    
                val popup = PopupMenu(activity,holder.buttonViewOption)
                popup.inflate(R.menu.pop_menu)
                popup.setOnMenuItemClickListener { item ->
                    when (item.itemId) {
                        R.id.edit -> {
                            val intent = Intent(activity,AddDetails::class.java)
                            intent.putExtra("isFor","Update")
                            intent.putExtra("id",productInfoGetSet.id)
                            intent.putExtra("image",productInfoGetSet.image)
                            intent.putExtra("name",productInfoGetSet.name)
                            intent.putExtra("quantity",productInfoGetSet.quantity)
                            intent.putExtra("price",productInfoGetSet.price)
                            activity.startActivity(intent)
                        }
                        R.id.delete -> {
                            val builder = AlertDialog.Builder(activity)
                            builder.setTitle("Delete")
                            builder.setMessage("Do you want to delete the item?")
    
                            builder.setPositiveButton("Yes") { _,_ ->
                                userList.removeAt(position)
                                notifyItemRemoved(position)
                                val snack = Snackbar
                                    .make(
                                        holder.linearly,"Item was removed from the list.",Snackbar.LENGTH_SHORT
                                    )
                                snack.show()
                            }
                            builder.setNegativeButton("No") { _,_ ->
                            }
                            val dialog: AlertDialog = builder.create()
                            dialog.show()
                        }
                    }
                    false
                }
                popup.show()
            }
        }
    
        override fun getItemId(position: Int): Long {
            return position.toLong()
        }
    
        override fun getItemCount(): Int {
            return userList.size
        }
    
        class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
            val txtName = itemView.findViewById<TextView>(R.id.txt_name)
            val txtId = itemView.findViewById(R.id.txt_id) as TextView
            var imgList = itemView.findViewById(R.id.img_list) as ImageView
            val txtQuantity = itemView.findViewById(R.id.txt_quantity) as TextView
            val txtPrice = itemView.findViewById(R.id.txt_price) as TextView
            val linearly: LinearLayout = itemView.findViewById(R.id.linearlayout)
            val buttonViewOption = itemView.findViewById<View>(R.id.txt_Options) as TextView
        }
    }

添加详细信息:

    package com.example.itemgetset
    
    import android.annotation.SuppressLint
    import android.app.Activity
    import android.content.Intent
    import android.content.pm.PackageManager
    import android.database.Cursor
    import android.graphics.Bitmap
    import android.graphics.BitmapFactory
    import android.net.Uri
    import android.os.Build
    import android.os.Bundle
    import android.os.Message
    import android.provider.MediaStore
    import android.widget.Button
    import android.widget.EditText
    import android.widget.ImageView
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    
    class AddDetails : AppCompatActivity() {
    
        private lateinit var btnSubmit: Button
        private lateinit var edtName: EditText
        private lateinit var edtQuantity: EditText
        private lateinit var edtPrice: EditText
        private lateinit var imageview: ImageView
    
    
        companion object {
            private const val IMAGE_PICK_CODE = 1000
            private const val PERMISSION_CODE = 1001
        }
    
        @SuppressLint("SetTextI18n","ResourceType")
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.add_item)
            supportActionBar?.hide()
            findViewById()
            onclick()
    
            if (intent.getStringExtra("isFor").equals("Update")) {
                intent.getStringExtra("image")?.toInt()?.let { imageview.setImageResource(it) }
                edtName.setText(intent.getStringExtra("name"))
                edtQuantity.setText(intent.getStringExtra("quantity"))
                edtPrice.setText(intent.getStringExtra("price"))
            }
        }
    
        private fun findViewById() {
            btnSubmit = findViewById(R.id.btn_submit)
            edtName = findViewById(R.id.edt_name)
            edtQuantity = findViewById(R.id.edt_quantity)
            edtPrice = findViewById(R.id.edt_price)
            imageview = findViewById(R.id.img_add)
        }
    
        @SuppressLint("ResourceType")
        private fun onclick() {
    
            btnSubmit.setOnClickListener {
                when {
                    edtName.text.trim().isEmpty() -> {
                        edtName.error = "Please Enter Product Name"
                        Toast.makeText(
                            applicationContext,"Please Enter Product Name",Toast.LENGTH_SHORT
                        )
                            .show()
                    }
                    edtQuantity.text.trim().isEmpty() -> {
                        edtQuantity.error = "Please Enter Product Quantity"
                        Toast.makeText(
                            applicationContext,"Please Enter Product Quantity",Toast.LENGTH_SHORT
                        ).show()
                    }
                    edtPrice.text.trim().isEmpty() -> {
                        edtPrice.error = "Please Enter Product Price"
                        Toast.makeText(
                            applicationContext,"Please Enter Product Price",Toast.LENGTH_SHORT
                        )
                            .show()
                    }
                    else -> {
                        Toast.makeText(
                            applicationContext,"Product Added Successfully ",Toast.LENGTH_SHORT
                        ).show()
    
                        val temp = Temp()
                        temp.image = imageview.()
                        temp.name = edtName.text.toString()
                        temp.quantity = edtQuantity.text.toString()
                        temp.price = edtPrice.text.toString()
    
                        if (intent.getStringExtra("isFor").equals("Update")) {
                            temp.id = intent.getStringExtra("id").toString()
                        }
    
                        val message: Message = Message.obtain()
                        message.what = 111
                        message.obj = temp
                        MainActivity.handler.sendMessage(message)
                        finish()
                    }
                }
            }
            imageview.setOnClickListener {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE) ==
                        PackageManager.PERMISSION_DENIED
                    ) {
                        val permissions = arrayOf(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                        requestPermissions(permissions,PERMISSION_CODE)
                    } else {
                        pickImageFromGallery()
                    }
                } else {
                    pickImageFromGallery()
                }
            }
        }
    
        override fun onRequestPermissionsResult(
            requestCode: Int,permissions: Array<out String>,grantResults: IntArray,) {
            when (requestCode) {
                PERMISSION_CODE -> {
                    if (grantResults.isNotEmpty() && grantResults[0] ==
                        PackageManager.PERMISSION_GRANTED
                    ) {
                        pickImageFromGallery()
                    } else {
                        Toast.makeText(this,"Permission denied",Toast.LENGTH_SHORT).show()
                    }
                }
            }
            super.onRequestPermissionsResult(requestCode,permissions,grantResults)
        }
    
        private fun pickImageFromGallery() {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            startActivityForResult(intent,IMAGE_PICK_CODE)
        }
    
        override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
            super.onActivityResult(requestCode,resultCode,data)
    
            if (requestCode == IMAGE_PICK_CODE && resultCode == RESULT_OK && data != null) {
    
                val pickedImage: Uri? = data.data
    
                val filePath = arrayOf(MediaStore.Images.Media.DATA)
                val cursor: Cursor? =
                    pickedImage?.let { contentResolver.query(it,filePath,null,null) }
                cursor?.moveToFirst()
                val imagePath: String = cursor?.getString(cursor.getColumnIndex(filePath[0]))!!
                val options = BitmapFactory.Options()
                options.inPreferredConfig = Bitmap.Config.ARGB_8888
                val bitmap = BitmapFactory.decodeFile(imagePath,options)
    
                // Do something with the bitmap
                intent = Intent(applicationContext,CustomAdapter::class.java)
                intent.putExtra("image",bitmap)
                startActivity(intent)
    
                // At the end remember to close the cursor or you will end with the RuntimeException!
                cursor.close()
            }
        }
    }

温度Kt:

package com.example.itemgetset

    class Temp {
        var id: String = ""
        var image = ""
        var name: String = ""
        var quantity: String = ""
        var price: String = ""
    }

ProductInfoGetSet: -

    package com.example.itemgetset
    
    import android.widget.ImageView
    
    class ProductInfoGetSet(
        var id: String,var image: String,var name: String,var quantity: String,var price: String
    )

Logcat:

2020-09-10 17:33:00.170 9328-9328/? E/mple.itemgetse: Unknown bits set in runtime_flags: 0x28000
2020-09-10 17:33:11.669 9328-9328/com.example.itemgetset E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/Instagram/IMG_20200830_174335_408.jpg: open failed: EACCES (Permission denied)
2020-09-10 17:33:11.672 9328-9328/com.example.itemgetset E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.itemgetset,PID: 9328
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,request=1000,result=-1,data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/498/ORIGINAL/NONE/image/jpeg/1143469803 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F498/ORIGINAL/NONE/image%2Fjpeg/1143469803} }} to activity {com.example.itemgetset/com.example.itemgetset.AddDetails}: java.lang.NullPointerException: BitmapFactory.decodeFile(imagePath,options) must not be null
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4973)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:5014)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2131)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7707)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
     Caused by: java.lang.NullPointerException: BitmapFactory.decodeFile(imagePath,options) must not be null
        at com.example.itemgetset.AddDetails.onActivityResult(AddDetails.kt:173)
        at android.app.Activity.dispatchActivityResult(Activity.java:8145)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4966)

如何在临时文件中定义imageview?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-