how to pass a lot of data to SimpleAdapter (Android | Kotlin) - android

How to pass all elements from "data" to "simpleData" for SimpleAdapter? For instance we have 100+ elements, it is not resonable to write elements by one. (should i use a loop? but how?)
TITLE doesn't show properly when simpleAdapter has used:[https://i.stack.imgur.com/W1kgJ.png]
hope you can help me, thanks in advance <3
val data = listOf<Book>(
Book("Memory", R.drawable.cover_1),
Book("The king of drugs", R.drawable.cover_2),
Book("SIN", R.drawable.cover_4),
Book("The martian", R.drawable.cover_5),
Book("No place like here", R.drawable.cover_6),
)
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater).also { setContentView(it.root) }
super.onCreate(savedInstanceState)
setupMyBookAdapter()
setupMySimpleAdapter()
}
private fun setupMySimpleAdapter() {
val simpleData = mutableListOf(
mapOf(TITLE to data[0].title, PHOTO to data[0].thumbnail),
mapOf(TITLE to data[1].title, PHOTO to data[1].thumbnail),
...
...
mapOf(TITLE to data[n].title, PHOTO to data[n].thumbnail)
)
val adapter2 = SimpleAdapter(this, simpleData, R.layout.cardview_item, arrayOf(TITLE, PHOTO), intArrayOf(R.id.book_title,R.id.book_cover))
binding.mylistview2.adapter = adapter2
}

Set title and cover of books as equal resources, for example R.string.title_0, R.drawable.cover_0.
Next use loop:
int i=0;
while( true ){
int id = getResources().getIdentifier( "title_"+i, "string", getPackageName() );
if( id > 0){
String title = getString(id);
// add to List here
i++;
}else{
break;
}
}

Related

How to implement For-loop logic in Spinner (android Kotlin)

I have 6 repetitive codes and I just want to use for-loop logic.
I tried to use "getIdentifier" and "findViewById" But I failed.
val sb_spinner_secret_p1: Spinner = findViewById(R.id.sb_secret1)
ArrayAdapter.createFromResource(this, R.array.secret, android.R.layout.simple_spinner_item
).also { adapter ->
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
sb_spinner_secret_p1.adapter = adapter
}
I tried this but it never works
for(i in 1..7){
val sb_spinner = "sb_spinner_secret_p$i"
val sbsecret = "sb_secret$i"
val sb_spinner_resId = resources.getIdentifier(sb_spinner,"id", packageName)
val sbsecret_resId = resources.getIdentifier(sbsecret,"id", packageName)
}

How to update recyclerview element and retrieve sum all updated elements

Updating value of recyclerview but unable to update corresponding data in model class
Model classes
#Parcelize
class GetStockListData : ArrayList<GetStockListDataItem>(), Parcelable
#Parcelize
data class GetStockListDataItem(
var Qty:#RawValue Double,
var selectedQty: Double
): Parcelable
able to change recyclerview element using alertbox as follows
private fun showAlertDialog(stockListData: GetStockListData, position: Int) {
val layoutInflater = LayoutInflater.from(context)
val customView =
layoutInflater.inflate(R.layout.change_qty_dialog, null)
val myBox: android.app.AlertDialog.Builder = android.app.AlertDialog.Builder(context)
myBox.setView(customView)
val dialog = myBox.create()
dialog.show()
val etQuantity = customView.findViewById<AppCompatEditText>(R.id.et_quantity)
if (stockListData[position].Qty < args.getListDetailsByRNumberModelItem.ReqQty) {
val df = DecimalFormat("#.##")
df.roundingMode = RoundingMode.CEILING
etQuantity.setText(df.format(stockListData[position].Qty).toString())
} else
etQuantity.setText(args.getListDetailsByRNumberModelItem.ReqQty.toString())
etQuantity.setSelection(etQuantity.text.toString().length)
etQuantity.requestFocus()
requireContext().showKeyboard()
customView.findViewById<Button>(R.id.btnDone).setOnClickListener {
if(!etQuantity.text.isNullOrEmpty()) {
val qtyStr = etQuantity.text.toString().trim()
var qtyDouble = qtyStr.toDouble()
stockListData[position].selectedQty = qtyDouble
adapter.notifyDataSetChanged()
dialog.dismiss()
}
}
}
for (i in 0 until stockListData.size){
sum += stockListData[i].selectedQty
}
here if user edit Recyclerview list item multiple times, each value added to list. Finally if i try to retrieve sum of all recyclerview elements getting wrong value because in model class values are added when i try to replace element.
Instead of passing whole list as parameter to showAlertDialog() method, you could just pass single item which has to be updated. And one more thing, you should not call adapter.notifyDataSetChanged() for single item updation, rather call adapter.notifyItemChanged(position). Look at below code, I am getting correct sum :
private fun showRecipeMeasureDialog(recipeItem: RecipeItem?,position: Int){
val dialogView = LayoutInflater.from(context).inflate(R.layout.add_recipe_measure_dialog, null)
val dialog = AlertDialog.Builder(context, R.style.RoundedCornersDialog).setView(dialogView).show()
dialog.setCancelable(false)
val displayRectangle = Rect()
val window = activity?.window
window?.decorView?.getWindowVisibleDisplayFrame(displayRectangle)
dialog.window?.setLayout(
(displayRectangle.width() * 0.5f).toInt(),
dialog.window!!.attributes.height
)
context?.resources?.let {
dialogView.findViewById<TextView>(R.id.recipe_measure_title).text = java.lang.String.format(it.getString(R.string.addRecipeMeasure), unitsArray[currentMeasurementUnits - 1])
}
val doneBtn = dialogView.findViewById<ImageButton>(R.id.recipe_measure_done_btn)
val closeBtn = dialogView.findViewById<ImageButton>(R.id.close_btn_add_recipe)
val conversionEditText = dialogView.findViewById<ClearFocusEditText>(R.id.recipe_conversion_tie)
doneBtn.isEnabled = false
if (recipeItem != null ){
conversionEditText.setText("${recipeItem.conversionRatio}")
}
closeBtn.setOnClickListener {
context?.hideKeyboard(it)
dialog.dismiss() }
doneBtn.setOnClickListener {
context?.hideKeyboard(it)
val conversionRatio = conversionEditText.text.toString().toFloat()
if (recipeItem != null){
recipeItem.conversionRatio = conversionRatio
recipeItemList[position] = recipeItem
recipeAdapter.notifyItemChanged(position)
}else{
recipeItemList.add(0,RecipeItem(0,0,conversionRatio,0)) // Use your data class in place of RecipeItem
recipeAdapter.notifyItemInserted(0) // new Item is added to index zero, so adapter has to be updated at index zero
}
// calculating sum
val sum = recipeItemList.map { it.conversionRatio }.sum()
Log.d("tisha==>>","Conversion ratio sum = $sum")
dialog.cancel()
}
}

How to keep modified object within list after filter is made on adapter?

I will try to be as explicit as I can. What I am trying to do is implement a filter on my adapter, modify some object attribute and then clean the filter. at this point, if I filter once again the object would have the change I made. The problem I have is that when I filter, I apply a clear to the list.
This is my adapter
private fun buildProductAdapter(filter: String) {
productList = Product().getProductsByFilter(filter)
productListAdapter = ProductListAdapter(applicationContext, productList, cashOrCredit)
rcvProducts.adapter = productListAdapter
}
this is when I do some filter
private fun notifyProductListFilterChanged() {
val filter: String = if (edtSearchProduct.text.toString() != "") edtSearchProduct.text.toString() else ""
productList.clear()
productList.addAll(Product().getProductsByFilter(filter))
productListAdapter!!.notifyDataSetChanged()
}
I was thinking to use a second list and then update de original list, do the filter over the first, duplicate over the second and this would be the one shown in the adapter.
Any help or suggestions would be great thanks
try
private fun notifyProductListFilterChanged() {
val filter: String = if (edtSearchProduct.text.toString() != "") edtSearchProduct.text.toString() else ""
productList.clear()
productList.addAll(filteredProductList(filter))
productListAdapter!!.notifyDataSetChanged()
}
private fun filteredProductList(filter: String): Collection<Product> {
return productListBaseAdapter.filter { it.nameProduct.contains(filter) || it.category.contains(filter) || it.descriptionProduct.contains(filter) }
}

SearchView does not show suggestions

So I want to show a suggestion in a searchView which is now inside a toolbar. So I created this adapter and it doesn't seem to work and the app is also crashing with this error StringIndexOutOfBoundsException
Adapter
class SearchHitchAdapter(context: Context, cursor: Cursor) : CursorAdapter(context, cursor, false) {
private val dataSet = arrayListOf<String>(*context.resources.getStringArray(R.array.city_states))
override fun newView(context: Context?, cursor: Cursor?, parent: ViewGroup?): View {
val inflater = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
return inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false)
}
override fun bindView(view: View?, context: Context?, cursor: Cursor?) {
val position = cursor!!.position
val textView = view!!.findViewById(android.R.id.text1) as TextView
textView.text = dataSet[position]
}
}
This function is being called inside onQueryTextChange
private fun setUpSearchSuggestions(query: String) {
val dataSet = getCityList()
val columns = arrayOf("_id", "text")
val temp = arrayOf(0, "default")
val cursor = MatrixCursor(columns)
for (i in 0 until dataSet.size) {
val city = dataSet[i]
if (city.toLowerCase(Locale.US).contains(query.toLowerCase(Locale.US))) {
temp[0] = i
temp[1] = city[i]
cursor.addRow(temp)
}
}
searchVIew.suggestionsAdapter = SearchAdapter(context!!, cursor)
}
This is not working can somebody help me or suggest me something.
This line in your code looks suspicious:
temp[1] = city[i]
This is the same as writing temp[i] = city.get(i): you are trying to get the character from city at position i.
Since i is the loop variable, and you're looping over dataset, this is very likely a mistake. There's no guarantee that every string in the data set is as long as the data set itself. Imagine that you have a list of a thousand cities; chances are very good that each city's name is less than one thousand characters long.
The exception "StringIndexOutOfBoundsException" says that you are accessing the data which doesn't exists. Check if your dataset has the right list.

How to pick every time new or unique random item from a array list in android?

I need to pick a new item from a list that hasn't been picked already until there are no more.
Here is my code:
private var quizQuestionList: ArrayList<Quiz>
private var pickedItems: ArrayList<Int>
private var random: Random = Random()
private fun pickItem(): Quiz {
var index = random?.nextInt(quizQuestionList!!.size)
if (pickedItems.contains(index)) {
index = random?.nextInt(quizQuestionList!!.size)
pickedItems.add(index)
} else {
pickedItems.add(index)
}
val item = quizQuestionList!!.get(index!!)
return item
}
Please suggest any solution that gives me a new item every time. I used an int list for all previously picked items and check every time when picked new item but I didn't get success.
It isn't obvious what you are looking for, but it looks like you want to show different Quiz question from ArrayList. In condition of, when that question is shown, no more same question will be shown. Here is how you should do, I will give you just the logic you could try it yourself:
import java.util.Random
fun main(args: Array<String>) {
val random = Random()
var randomInt: Int
var pickedInt: MutableSet<Int> = mutableSetOf()
fun rand(from: Int, to: Int): Int{
do{
randomInt = random.nextInt(to - from) + from
}while(pickedInt.contains(randomInt))
pickedInt.add(randomInt)
return randomInt
}
while(pickedInt.size < 9){
var differentNumber = rand(1,11)
println(differentNumber)
}
}
This will print nine different Number. The way I choosing MutableSet is because it will only have unique values, no duplicated value. Hope it helps!
here is code for same::
val arrayList = ArrayList<String>()
arrayList.add("a")
arrayList.add("b")
arrayList.add("c")
arrayList.add("d")
arrayList.add("e")
arrayList.add("f")
arrayList.add("g")
arrayList.add("h")
arrayList.add("i")
arrayList.add("j")
arrayList.add("k")
random = Random()
Low = 0
High = arrayList.size
val generateRandom = findViewById<View>(R.id.generateRandom) as Button
generateRandom.setOnClickListener {
val Result = random.nextInt(High - Low) + Low
Log.v("check", arrayList[Result])
}
Please let me know if need more!!
Try this way
class MainActivity : AppCompatActivity() {
private var arrayList = ArrayList<String>()
private var lastItem = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
for (i in 0..9) {
arrayList.add(i.toString())
}
btnData.setOnClickListener {
Log.e("RANDOM_NUMBER", "" + getRandomItemFromList())
}
}
private fun getRandomItemFromList(): Int {
val randomValue = Random().nextInt(arrayList.size)
return if (randomValue != lastItem) {
lastItem = randomValue
randomValue
} else {
getRandomItemFromList()
}
}
}
I made this extension for the ArrayList class in Kotlin you can use it multiple times in only one line.
fun <T> ArrayList<T>.generateRandomItems(numberOfItems: Int): ArrayList<T> {
val range = if(numberOfItems > this.size){this.size}else{numberOfItems}
val randomItems = ArrayList<T>()
for (i in 0..range) {
var randomItem: T
do {
randomItem = this.random()
} while (randomItems.contains(randomItem))
randomItems.add(randomItem)
}
return randomItems
}
Usage:
val randomUsersList = usersList.generateRandomItems(20)
Note: the usersList is the list that has items to generate random items from.

Categories

Resources