How to show image from an external database (kotlin) - android

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

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

Related

Can I press a button in Activity A to filter a RecyclerView in Activity B?

What I want to reach is that the same RecyclerView shows different data depending on which button the App user pressed before in the MainActivity.kt.
In my MainActivity.kt I have two buttons, which both send the user to the same RecyclerView Activity (RecyclerViewLayout.kt) via Intent.
Example: The RecyclerView contains a picture of an apple and a banana. By pressing button A in MainActivity.kt, the RecyclerView in RecyclerViewLayout.kt should only show the apple. By pressing button B it should only show the banana. In my real app there are no fruits. but Tutorials, which should be filtered like described.
I gently ask for help here how to do that. Maybe there is also a better way to reach my target to filter the RecyclerView?
Thanks in Advance!
MainActivity.kt
class MainActivity : AppCompatActivity() {
private var binding:ActivityMainBinding? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding?.root)
val buttonRecyclerView = findViewById<Button>(R.id.btn_recyclerview)
buttonRecyclerView.setOnClickListener {
val intent = Intent(this, RecyclerViewLayout::class.java)
startActivity(intent)
}
}}
RecyclerViewLayout.kt
class RecyclerViewLayout : AppCompatActivity() {
private lateinit var newRecylerview : RecyclerView
private lateinit var newArrayList : ArrayList<RecyclerViewDataClass>
private lateinit var tempArrayList : ArrayList<RecyclerViewDataClass>
lateinit var imageId : Array<Int>
lateinit var tutorialHeading : Array<String>
lateinit var tutorialText : Array<String>
lateinit var url : Array<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view_layout)
imageId = arrayOf(
R.drawable.brake,
R.drawable.brake,
)
tutorialHeading = arrayOf(
getString(R.string.scheibenbremse_lüften_heading),
getString(R.string.felgenbremse_richten_heading),
)
tutorialText = arrayOf(
getString(R.string.scheibenbremse_lüften_text),
getString(R.string.felgenbremse_richten_text),
)
url = arrayOf(
getString(R.string.url_a),
getString(R.string.url_b),
)
newRecylerview =findViewById(R.id.recyclerView)
newRecylerview.layoutManager = LinearLayoutManager(this)
newRecylerview.setHasFixedSize(true)
newArrayList = arrayListOf<RecyclerViewDataClass>()
tempArrayList = arrayListOf<RecyclerViewDataClass>()
getUserdata()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_item,menu)
val item = menu?.findItem(R.id.search_action)
val searchView = item?.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
TODO("Not yet implemented")
}
override fun onQueryTextChange(newText: String?): Boolean {
tempArrayList.clear()
val searchText = newText!!.toLowerCase(Locale.getDefault())
if (searchText.isNotEmpty()){
newArrayList.forEach {
if (it.heading.toLowerCase(Locale.getDefault()).contains(searchText)){
tempArrayList.add(it)
}
}
newRecylerview.adapter!!.notifyDataSetChanged()
}else{
tempArrayList.clear()
tempArrayList.addAll(newArrayList)
newRecylerview.adapter!!.notifyDataSetChanged()
}
return false
}
})
return super.onCreateOptionsMenu(menu)
}
private fun getUserdata() {
for(i in imageId.indices){
val news = RecyclerViewDataClass(imageId[i],tutorialHeading[i],url[i])
newArrayList.add(news)
}
tempArrayList.addAll(newArrayList)
val adapter = RecyclerViewAdapter(tempArrayList)
newRecylerview.adapter = adapter
adapter.setOnItemClickListener(object : RecyclerViewAdapter.onItemClickListener{
override fun onItemClick(position: Int) {
val intent = Intent(this#RecyclerViewLayout,TutorialsActivity::class.java)
intent.putExtra("tutorialHeading",newArrayList[position].heading)
intent.putExtra("imageId",newArrayList[position].titleImage)
intent.putExtra("url",newArrayList[position].url)
intent.putExtra("tutorialText",tutorialText[position])
startActivity(intent)
}
})
}}
RecyclerViewAdapter.kt
class RecyclerViewAdapter(private val newsList : ArrayList<RecyclerViewDataClass>) : RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>(),
Filterable {
private lateinit var mListener : onItemClickListener
interface onItemClickListener{
fun onItemClick(position : Int)
}
fun setOnItemClickListener(listener: onItemClickListener){
mListener = listener
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.list_item,
parent,false)
return MyViewHolder(itemView,mListener)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentItem = newsList[position]
holder.titleImage.setImageResource(currentItem.titleImage)
holder.tvHeading.text = currentItem.heading
}
override fun getItemCount(): Int {
return newsList.size
}
class MyViewHolder(itemView : View, listener: onItemClickListener) : RecyclerView.ViewHolder(itemView){
val titleImage : ShapeableImageView = itemView.findViewById(R.id.title_image)
val tvHeading : TextView = itemView.findViewById(R.id.tvHeading)
init {
itemView.setOnClickListener {
listener.onItemClick(adapterPosition)
}
}
}
override fun getFilter(): Filter {
TODO("Not yet implemented")
}}
RecyclerViewDataClass.kt
data class RecyclerViewDataClass(var titleImage: Int, var heading: String, val url: String)
**Tutorials Activity**
class TutorialsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tutorials)
val headingNews : TextView = findViewById(R.id.heading)
val mainNews : TextView = findViewById(R.id.news)
val imageNews : ImageView = findViewById(R.id.image_heading)
val bundle : Bundle?= intent.extras
val tutorialHeading = bundle!!.getString("tutorialHeading")
val imageId = bundle.getInt("imageId")
val tutorialText = bundle.getString("tutorialText")
val url = bundle.getString("url")
headingNews.text = tutorialHeading
mainNews.text = tutorialText
imageNews.setImageResource(imageId)
imageNews.setOnClickListener {
val openURL = Intent(Intent.ACTION_VIEW)
openURL.data = Uri.parse(url.toString())
startActivity(openURL)
}
}}
I believe you can pass data about which button is clicked using intents. Here's a link about that:
How to Pass custom object via intent in kotlin
For example, you can pass "A" if button A is clicked and "B" if button B is clicked, and then get that string in RecyclerViewLayout.kt to determine which elements should be shown.
According to me the simplest solution for doing this is you should have a boolean in preferences you can set preferences according to the button clicked and set data in your adapter to by getting the preferences value.
If you want to set data according to the button clicked
Other way is to pass the action onClick while starting a new Activity and getAction() in your second Activity.
This way you can also set data of your recyclerView by passing different data

RecyclerView make endless scrolling with JSON

I'm trying to make my Android App (I'm only experienced in iOS).
I created a RecyclerView that gets the data from a web. I tried everything to implement endless scrolling to load more items, but when I call the function to get the items, the entire RecyclerView loads again and no attach the new results on the bottom.
This is my code:
ConversationUser.kt
data class ConversationUser(
val message_nickname: String,
val message_image_thumb: String,
val message_large_thumb: String,
val message_modified: String,
val message_status: String,
val message_unread: Int,
val conv_id: String,
val message_dest: String) {
}
ConversacionesActivity.kt
class ConversacionesActivity : AppCompatActivity() {
// MARK: Variables
var user_token = ""
var user_id = ""
override fun onCreate(savedInstanceState: Bundle?) {
// User Defaults
val sharedPreferences = getSharedPreferences("Preferences", Context.MODE_PRIVATE)
user_token = sharedPreferences.getString("user_token", "")!!
user_id = sharedPreferences.getString("user_id", "")!!
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_conversaciones)
recyclerConv.addItemDecoration(DividerItemDecoration(this, LinearLayoutManager.VERTICAL))
getConversationsData()
recyclerConv.setLoadingListener(object : LoadingListener {
override fun onRefresh() {
//refresh data here
}
override fun onLoadMore() {
// load more data here
getConversationsData()
}
})
}
fun getConversationsData() {
val httpAsync = "https://mywebsite.com/conversations/${user_token}"
.httpPost()
.responseString { request, response, result ->
when (result) {
is Result.Failure -> {
val ex = result.getException()
println(ex)
}
is Result.Success -> {
val data = result.get()
runOnUiThread {
val conversaciones = processJson(data)
show(conversaciones)
return#runOnUiThread
}
}
}
}
httpAsync.join()
}
fun processJson(json: String): List<ConversationUser> {
val gson: Gson = GsonBuilder().create()
val conversaciones: List<ConversationUser> = gson.fromJson(
json,
Array<ConversationUser>::class.java
).toList()
return conversaciones
}
fun show(conversaciones: List<ConversationUser>) {
recyclerConv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
recyclerConv.adapter = AdaptadorConv(conversaciones, this, user_token, user_id)
}
AdaptadorConv.kt
class AdaptadorConv(
val conversaciones: List<ConversationUser> = ArrayList(),
val context: Context,
val user_token: String,
val user_id: String) : RecyclerView.Adapter<AdaptadorConv.ConvViewHolder>() {
override fun onBindViewHolder(holder: ConvViewHolder, position: Int) {
holder.convName.text = conversaciones[position].message_nickname
holder.convTime.text = conversaciones[position].message_modified
}
override fun getItemCount(): Int {
return conversaciones.size - 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ConvViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(
R.layout.conversaciones,
parent,
false
)
return ConvViewHolder(view)
}
class ConvViewHolder(vista: View): RecyclerView.ViewHolder(vista) {
val convImg: ImageView = itemView.findViewById(R.id.convImg)
val convStatus: ImageView = itemView.findViewById(R.id.convStatus)
val convName: TextView = itemView.findViewById(R.id.convName)
val convUnread: TextView = itemView.findViewById(R.id.convUnread)
val convTime: TextView = itemView.findViewById(R.id.convTime)
}
Thanks for any help or hint.
Please check your show () method, you are creating new Adapter every time with the new dataset. You have to append the new items to the adapter's list and adapter should be set to list once. Helpful tutorial can be found at here.

Android Kotlin RecyclerView Search Item with EditText with data from Data Class

So I have a RecyclerView which data is populated with data from some Data Class. I want to Apply a search item function for this recyclerview. Back when I don't use Data Classes, I followed this tutorial (The tutorial is in Java).
Now that I'm using a data class since I fetch the data that populate the recyclerview from an API endpoint, I'm quite confused on how to apply the search function in the current recyclerview.
(I fetch the data using library Retrofit if you wondering.)
This is the code snippet from the fragment:
RefundListFragment.kt
private fun fetchRefundListData() {
NetworkConfig().getRefundListDetailService().getRefundList().enqueue(object :
Callback<RefundListPOJODataClass> {
override fun onFailure(call: Call<RefundListPOJODataClass>, t: Throwable) {
...
...
...
}
override fun onResponse(
call: Call<RefundListPOJODataClass>,
response: Response<RefundListPOJODataClass>
) {
binding.refundProgressBar.visibility = View.GONE
binding.rvRefundList.adapter =
response.body()?.let { RefundListAdapter(it, this#RefundListFragment) }
fun filterString(text: String) {
val filteredList: List<RefundListPOJODataClass> = ArrayList()
for (item in response.body()?.data!!) {
if (item != null) {
if (item.buyerName?.toLowerCase()?.contains(text.toLowerCase())!!) {
filteredList.add(item)
}
}
}
adapter.filterList(filteredList)
}
binding.refundListSearchBar.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
filterString(s.toString())
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
})
}
However it returned an error:
Unresolved reference: add
This is the recyclerview Adapter:
RefundListAdapter.kt
class RefundListItemHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val refundedOrderId: TextView = itemView.refundedOrderId
private val orderDateTime: TextView = itemView.orderDateTime
private val refundedCustomerName: TextView = itemView.refundedCustomerName
fun bind(
refundHistory: RefundListPOJODataClassDataItem,
clickListener: RefundListOnItemClickListener
) {
refundedOrderId.text = refundHistory.orderId
orderDateTime.text = refundHistory.orderDate
refundedCustomerName.text = refundHistory.buyerName
itemView.setOnClickListener {
clickListener.onItemClicked(refundHistory)
}
}
}
class RefundListAdapter(
private var refundList: RefundListPOJODataClass,
private val itemClickListener: RefundListOnItemClickListener
) : RecyclerView.Adapter<RefundListItemHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RefundListItemHolder {
val v = LayoutInflater.from(parent.context)
.inflate(R.layout.refund_list_item_layout, parent, false)
return RefundListItemHolder(v)
}
override fun getItemCount(): Int {
if (refundList.data != null) {
return refundList.data!!.size
} else {
return 0
}
}
override fun onBindViewHolder(holder: RefundListItemHolder, position: Int) {
val refundHistory = refundList.data?.get(position)
if (refundHistory != null) {
holder.bind(refundHistory, itemClickListener)
}
}
fun filterList(filteredList: List<RefundListPOJODataClass>) { //This is the function I called in the fragment
refundList = filteredList.get(0)
notifyDataSetChanged()
}
}
interface RefundListOnItemClickListener {
fun onItemClicked(refundHistory: RefundListPOJODataClassDataItem)
}
And this is how the data class looks like
RefundListPOJODataClass.kt
data class RefundListPOJODataClass(
#field:SerializedName("data")
val data: List<RefundListPOJODataClassDataItem?>? = null,
#field:SerializedName("error")
val error: Error? = null
)
data class RefundListPOJODataClassError(
#field:SerializedName("msg")
val msg: String? = null,
#field:SerializedName("code")
val code: Int? = null,
#field:SerializedName("status")
val status: Boolean? = null
)
data class RefundListPOJODataClassDataItem(
#field:SerializedName("order_date")
val orderDate: String? = null,
#field:SerializedName("buyer_name")
val buyerName: String? = null,
#field:SerializedName("phone_number")
val phoneNumber: String? = null,
#field:SerializedName("status_refund")
val statusRefund: String? = null,
#field:SerializedName("order_id")
val orderId: String? = null,
#field:SerializedName("refund")
val refund: Int? = null,
#field:SerializedName("refund_date")
val refundDate: String? = null
)
I want to search the recyclerview item by the attribute buyerName. How can I achieve it ? What should i change in my code? If there's any detail I missed to tell, Just let me know.
Your filtered list is of type List, which is immutable.
Change it to array list or MutableList:
val filteredList: ArrayList<RefundListPOJODataClass> = ArrayList()

problem populate spinner android kotlin with room database

I want to populate spinner with room database in kotlin but items in spinner are different. the number of items are true. exactly I want to make ArrayList of title in Category Class and show them in spinner in a fragment
#Entity(tableName = "cat_table")
class Category(val title: String,
val fulType: Int,
val SaleP: Long,
val BuyP: Long,
var created: Date = Date()
) {
#PrimaryKey(autoGenerate = true)
var id: Int = 0
}`
by this an want to show all title in ArrayList and set to spinner
private fun initData() {
val packageTypesAdapter = context?.let {ArrayAdapter<Any>(it,android.R.layout.simple_spinner_item)}
catViewModel!!.allCats.observe(viewLifecycleOwner, Observer { packageTypes ->
packageTypes?.forEach {packageTypesAdapter!!.add(it)}
})
spinner2.adapter = packageTypesAdapter
spinner2.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) {
Toast.makeText(context, "$packageTypesAdapter", Toast.LENGTH_SHORT).show()
//if (i == 0) {
// loadAllTodos()
//} else {
// val string: String = parent.getItemAtPosition(position).toString()
// loadFilteredTodos(string)
//}
}
override fun onNothingSelected(adapterView: AdapterView<*>) {
}
}
}`
if use this query
#get:Query("SELECT * FROM cat_table WHERE title ")
val allCatTitle: LiveData<List<Category>>
spinner nothing to show and below query are like this picture
#get:Query("SELECT * FROM cat_table ORDER BY created DESC")
val allCatByDate: LiveData<List<Category>>
Please check the photo
In case someone else bumps into the same issue. Here's how I did it a while ago (Kotlin).
Dao
#Query("SELECT deviceName FROM device_table WHERE deviceType = :deviceType")
fun getDevice(deviceType: String): LiveData<List<String>>
Repository
fun getDevice(deviceType: String): LiveData<List<String>> {
return deviceDao.getDevice(deviceType)
}
ViewModel
fun getDevice(deviceType: String): LiveData<List<String>> {
return repository.getDevice(deviceType)
}
And finally in my fragment:
private fun initSpinnerData() {
val spinner3 = view?.findViewById<Spinner>(R.id.spinnerRecord_devices)
if (spinner3 != null) {
val allDevices = context?.let {
ArrayAdapter<Any>(it, R.layout.spinner_text)
}
mDevicesViewModel.getDevice("Appliance")
.observe(viewLifecycleOwner, { devices ->
devices?.forEach {
allDevices?.add(it)
}
})
spinner3.adapter = allDevices
spinner3.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
Toast.makeText(requireContext(), "$allDevices", Toast.LENGTH_LONG).show()
}
override fun onNothingSelected(parent: AdapterView<*>?) {
TODO("Not yet implemented")
}
}
}
}

Kotlin RecyclerView no adapter attached skipping layout

I don't know what the problem is but same code works fine in java
Here is my adapter class:
class MainAdapter(private val context: Context, private val firebaseVisionlabel: ArrayList<FirebaseVisionLabel>) : RecyclerView.Adapter<CustomViewHolder>() {
override fun getItemCount(): Int {
return firebaseVisionlabel.size
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): CustomViewHolder {
val v = LayoutInflater.from(context).inflate(R.layout.list_items,p0,false)
return CustomViewHolder(v)
}
override fun onBindViewHolder(p0: CustomViewHolder, p1: Int) {
val firebaseVisionLabel = firebaseVisionlabel?.get(p1)
val label = firebaseVisionLabel?.label
val confidence =firebaseVisionLabel?.confidence.toString()
p0.itemView.textView.text = label
p0.itemView.confidence.text = confidence
}
}
class CustomViewHolder(v:View) : RecyclerView.ViewHolder(v)
MainActivity: (Global declaration)
var fileUri: Uri? = null
var TAG = "MainActivity"
var firebaseVisionLabels : ArrayList<FirebaseVisionLabel>? = null
In onCreate :
rec_view.layoutManager = LinearLayoutManager(this)
rec_view.setHasFixedSize(true)
Button :
detect_button.setOnClickListener{
imageRecognition()
}
Function :
private fun imageRecognition() {
var bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, fileUri)
var image = FirebaseVisionImage.fromBitmap(bitmap)
val labeler = FirebaseVision.getInstance().visionLabelDetector
labeler.detectInImage(image)
.addOnSuccessListener { labels ->
for (label in labels) {
val text = label.label
val entityId = label.entityId
val confidence = label.confidence
Log.d("TAG", "$text $confidence") //logcat works
firebaseVisionLabels?.add(label)
//Main problem??
rec_view.adapter = firebaseVisionLabels?.let { MainAdapter(this, it) }
}
}.addOnFailureListener { e ->
// Task failed with an exception
// ...
detect_button.isEnabled = true
Log.d(TAG,e.toString())
}
}
Logcat prints the expected outputs but I don't know what the problem is in recyclerview. I don't want to put bunch of camera and gallery intents codes, they works fine. Thanks for helping.
I solved by changing RecyclerView to BaseAdapter and the parameter to ArrayList. I guess RecyclerView can work same with the Basedapter by changing the parameter private val firebaseVisionlabel: ArrayList<FirebaseVisionLabel> to private val labeltext : ArrayList<String> I think it is a bug between FirebaseVisionLabel and Kotlin
Modified part for MainActivity :
for (label in labels) {
for(i in 1..1){
val text = label.label
val entityId = label.entityId
val confidence = label.confidence
new_list.add(text)
}
list_view.adapter =MainAdapter(this,new_list)

Categories

Resources