如何从外部数据库(Kotlin)显示图像

发布于 2025-02-11 01:25:59 字数 5697 浏览 1 评论 0原文

大家好,我想使用外部数据库制作应用程序,我用SQLite浏览器制作了数据库,将图像放在可绘制的情况下,我需要显示图像和文字 (图像也不显示这不是任何错误日志) 有关更多指导,我在适配器中有一些代码 我也放了gitlab链接 任何帮助都会很感激。谢谢


    class model {
        var id:Int?=null
        var name:String?=null
        var image:String?=null
    }


    object info_db {
    
        val dbName="country"
        val dbversion=2
        val dbId="id"
        val dbcname="name"
        val dbimage="image"
        val packageData="data/data/com.alialim.countrylist_sample/databases/"
        val source ="country.sqlite"
    
    }


    class Database(val context: Context): SQLiteOpenHelper(context,info_db.dbName,null,info_db.dbversion)  {
        override fun onCreate(p0: SQLiteDatabase?) {
        }
    
        override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
    
        }
    
        init {
            initDatabase()
        }
        private fun initDatabase() {
    
            var file = File(info_db.packageData)
    
            if (file.exists()) {
    
            } else {
                file.mkdirs()
            }
    
            file = context.getDatabasePath(info_db.dbName)
            if (file.exists()) {
    
            } else {
                copyDataBase()
            }
    
        }
    
        private fun copyDataBase() {
            val inputStream = context.assets.open(source)
            val outFile = packageData + dbName
            val uotPutStream = FileOutputStream(outFile)
            val buffer = ByteArray(1024)
            var lenght = 0
            while (inputStream.read(buffer).also({ lenght = it }) > 0)
                uotPutStream.write(buffer, 0, lenght)
            uotPutStream.flush()
            uotPutStream.close()
            inputStream.close()
        }
    
        @SuppressLint("Range")
        fun getAll(): ArrayList<model> {
            val db = readableDatabase
            val query = "SELECT * FROM countrylist"
            var list: ArrayList<model> = ArrayList()
            val cursor = db.rawQuery(query, null)
            if (cursor.moveToFirst()) {
                do {
                    val lmodel = model()
                    lmodel.id=cursor.getInt(cursor.getColumnIndex(info_db.dbId))
                    lmodel.name=cursor.getString(cursor.getColumnIndex(info_db.dbcname))
    
                    lmodel.image=cursor.getString(cursor.getColumnIndex(info_db.dbimage))
                    list.add(lmodel)
                    Log.d(
                        "massage",
                        "log Database name ==>${lmodel.name} and category ==> ${lmodel.image}  "
                    )
                } while (cursor.moveToNext())
            }
            cursor.close()
            db.close()
            return list
        }
    }


    object Base: Application() {
        var database: Database?=null
        var activity: Activity?=null
    
        override fun onCreate() {
            super.onCreate()
        }
    }


    class AdapterCountry(val context: Context, val countrylists:ArrayList<model>): RecyclerView.Adapter<AdapterCountry.HolderCountry>() {
    
        class HolderCountry(itemView: View): RecyclerView.ViewHolder(itemView){
            val imagerecy=itemView.findViewById<ImageView>(R.id.recycler_main_image)
            val txtfname=itemView.findViewById<TextView>(R.id.recycler_main_text)
    
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HolderCountry {
            val layout= LayoutInflater.from(parent.context).inflate(R.layout.item,parent,false)
            return HolderCountry(layout)
        }
        override fun onBindViewHolder(holder: HolderCountry, position: Int) {
            val countrylist=countrylists.get(position)
            holder.txtfname.text=countrylist.name
            //code that should display the images but dosent work
            val img=countrylist.image
            val Image: Int = Base.activity!!.getResources()
                .getIdentifier(img, "drawable", Base.activity!!.getPackageName())
            holder.imagerecy.setImageResource(Image)
            //////////////
        }
        override fun getItemCount()=countrylists.size
    }


    class MainActivity : AppCompatActivity() {
    
        var btnclick: Button?=null
        var recycler: RecyclerView?=null
        var adaptecounry: AdapterCountry?=null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            btnclick=findViewById(R.id.showcountrye)
            recycler=findViewById(R.id.mainactivity_recy_image)
            Base.activity=this
            Base.database= Database(this)
            btnclick!!.setOnClickListener {
                recycler!!.setHasTransientState(true)
                recycler!!.layoutManager= LinearLayoutManager(Base.activity)
                val list= Base.database!!.getAll()
                adaptecounry = AdapterCountry(Base.activity!!,list)
                recycler!!.adapter=adaptecounry
    
            }
    
        }
    
    }

sqlitebrowser drawable

请访问: https://gitlab.com/salin1/country_list//tree/master/master

Hello guys I want to make app with an External Database, I made my Database with SQLite browser, Put my image to drawable, I need to show image and text but it just shows text I mean it works
(Image does not show also this is not any error log about it )
For more guidance I have some code in Adapter
also I put gitlab link
any help would be appreciate. Thank you


    class model {
        var id:Int?=null
        var name:String?=null
        var image:String?=null
    }


    object info_db {
    
        val dbName="country"
        val dbversion=2
        val dbId="id"
        val dbcname="name"
        val dbimage="image"
        val packageData="data/data/com.alialim.countrylist_sample/databases/"
        val source ="country.sqlite"
    
    }


    class Database(val context: Context): SQLiteOpenHelper(context,info_db.dbName,null,info_db.dbversion)  {
        override fun onCreate(p0: SQLiteDatabase?) {
        }
    
        override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
    
        }
    
        init {
            initDatabase()
        }
        private fun initDatabase() {
    
            var file = File(info_db.packageData)
    
            if (file.exists()) {
    
            } else {
                file.mkdirs()
            }
    
            file = context.getDatabasePath(info_db.dbName)
            if (file.exists()) {
    
            } else {
                copyDataBase()
            }
    
        }
    
        private fun copyDataBase() {
            val inputStream = context.assets.open(source)
            val outFile = packageData + dbName
            val uotPutStream = FileOutputStream(outFile)
            val buffer = ByteArray(1024)
            var lenght = 0
            while (inputStream.read(buffer).also({ lenght = it }) > 0)
                uotPutStream.write(buffer, 0, lenght)
            uotPutStream.flush()
            uotPutStream.close()
            inputStream.close()
        }
    
        @SuppressLint("Range")
        fun getAll(): ArrayList<model> {
            val db = readableDatabase
            val query = "SELECT * FROM countrylist"
            var list: ArrayList<model> = ArrayList()
            val cursor = db.rawQuery(query, null)
            if (cursor.moveToFirst()) {
                do {
                    val lmodel = model()
                    lmodel.id=cursor.getInt(cursor.getColumnIndex(info_db.dbId))
                    lmodel.name=cursor.getString(cursor.getColumnIndex(info_db.dbcname))
    
                    lmodel.image=cursor.getString(cursor.getColumnIndex(info_db.dbimage))
                    list.add(lmodel)
                    Log.d(
                        "massage",
                        "log Database name ==>${lmodel.name} and category ==> ${lmodel.image}  "
                    )
                } while (cursor.moveToNext())
            }
            cursor.close()
            db.close()
            return list
        }
    }


    object Base: Application() {
        var database: Database?=null
        var activity: Activity?=null
    
        override fun onCreate() {
            super.onCreate()
        }
    }


    class AdapterCountry(val context: Context, val countrylists:ArrayList<model>): RecyclerView.Adapter<AdapterCountry.HolderCountry>() {
    
        class HolderCountry(itemView: View): RecyclerView.ViewHolder(itemView){
            val imagerecy=itemView.findViewById<ImageView>(R.id.recycler_main_image)
            val txtfname=itemView.findViewById<TextView>(R.id.recycler_main_text)
    
        }
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HolderCountry {
            val layout= LayoutInflater.from(parent.context).inflate(R.layout.item,parent,false)
            return HolderCountry(layout)
        }
        override fun onBindViewHolder(holder: HolderCountry, position: Int) {
            val countrylist=countrylists.get(position)
            holder.txtfname.text=countrylist.name
            //code that should display the images but dosent work
            val img=countrylist.image
            val Image: Int = Base.activity!!.getResources()
                .getIdentifier(img, "drawable", Base.activity!!.getPackageName())
            holder.imagerecy.setImageResource(Image)
            //////////////
        }
        override fun getItemCount()=countrylists.size
    }


    class MainActivity : AppCompatActivity() {
    
        var btnclick: Button?=null
        var recycler: RecyclerView?=null
        var adaptecounry: AdapterCountry?=null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            btnclick=findViewById(R.id.showcountrye)
            recycler=findViewById(R.id.mainactivity_recy_image)
            Base.activity=this
            Base.database= Database(this)
            btnclick!!.setOnClickListener {
                recycler!!.setHasTransientState(true)
                recycler!!.layoutManager= LinearLayoutManager(Base.activity)
                val list= Base.database!!.getAll()
                adaptecounry = AdapterCountry(Base.activity!!,list)
                recycler!!.adapter=adaptecounry
    
            }
    
        }
    
    }

SQLitebrowser
drawable

please visit : https://gitlab.com/salin1/country_list/-/tree/master

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

动听の歌 2025-02-18 01:25:59

大家好,我可以解决我的问题,因为我还是很短的时间
我在这里写我的正确代码,也许有一天有人需要它,我的鳕鱼是正确的,但是您需要将此代码放入您的recyclerview适配器中,

   

override fun onBindViewHolder(holder: HolderCountry, position: Int) {

        val countrylist=countrylists.get(position)
        Log.i("imaaagee","${countrylist.image}")
        holder.txtfname.text=countrylist.name
        val img=countrylist.name
        img!!.trim()
        val identifier=context.resources.getIdentifier(img,"drawable",
        context!!.getPackageName())
        holder.imagerecy.setImageResource(identifier)

    }

我还会在图像列中查看我在图像列中看到的数据库图像,我也会放置链接和图像。带有格式(.png)的图像名称,但它的错误,因为GetIdentifier不需要图像格式,您应该做的所有事情就是将图像放置在可绘制的地方,并使用适配器代码恢复
为了进一步了解,我放置了我的gitlab链接,您可以下载并查看代码
如果您有任何疑问,请问我会回答
谢谢

Hello everybody I could fix my problem because I was Short of time anyway
I writ my correct code here maybe one day somebody like me needed it, My cod is correct but you need to put this code in your RecyclerView Adapter

   

override fun onBindViewHolder(holder: HolderCountry, position: Int) {

        val countrylist=countrylists.get(position)
        Log.i("imaaagee","${countrylist.image}")
        holder.txtfname.text=countrylist.name
        val img=countrylist.name
        img!!.trim()
        val identifier=context.resources.getIdentifier(img,"drawable",
        context!!.getPackageName())
        holder.imagerecy.setImageResource(identifier)

    }

also I put link and image if you look at my database image you see in image column I write image name with format (.png) but its mistake because getIdentifier does not need image format the all thing you should do is put your image to drawable and recover with your adapter code
for more understanding I put my gitlab link you can download and see code
if you have any question just ask I will respond
Thank you

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文