0

У меня есть recyclerview в который я добавляю элементы с помощью FAB, который открывает DialogAlert и туда я ввожу URL картинки и описание. Если я не добавлю описание и добавлю только URL, то приложение не крашнется, а добавит в список картинку, если же я добавлю описание и не добавлю картинку - приложение крашнется. В чем может быть причина?

Activity

class ActivityThree : AppCompatActivity() {

var itemList = mutableListOf<ProductItem>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_three)
    initRecyclerView()

    val recyclerAdapter = ActivityThreeAdapter(itemList)
    rv_recycler.adapter = recyclerAdapter

    btn_fab.setOnClickListener {
        val alertDialog = AlertDialog.Builder(this)

        val inflater = layoutInflater
        val dialogLayout = inflater.inflate(R.layout.edit_text_alert_dialog, null)

        val editTextURL = dialogLayout.findViewById<EditText>(R.id.edt_url)
        val editTextDescription = dialogLayout.findViewById<EditText>(R.id.edt_description)

        with(alertDialog) {
            setTitle("Add Element")
            setPositiveButton("Ок") { _: DialogInterface, _: Int ->
                val imageURL = editTextURL.text.toString()
                val item = editTextDescription.text.toString()
                itemList.add(ProductItem(imageURL, item))
                recyclerAdapter.notifyDataSetChanged()
            }
            setNegativeButton("Отмена") { _: DialogInterface, _: Int ->
            }
            setView(dialogLayout)
        }
        alertDialog.show()
    }
}

private fun initRecyclerView() {
    rv_recycler.layoutManager = LinearLayoutManager(this)
   }
}

Adapter

class ActivityThreeAdapter(private val items: List<ProductItem>) :
RecyclerView.Adapter<ActivityThreeAdapter.ExampleViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExampleViewHolder {
    val exampleViewHolder = LayoutInflater.from(parent.context).inflate(R.layout.item_recycler, parent, false)
    return ExampleViewHolder(exampleViewHolder)
}

override fun onBindViewHolder(holder: ExampleViewHolder, position: Int) {
    holder.bindItems(items[position])
}

override fun getItemCount() = items.size

inner class ExampleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bindItems(items: ProductItem) {
        val picture: ImageView = itemView.findViewById(R.id.img_list)
        val txtItem: TextView = itemView.findViewById(R.id.txt_item)
        txtItem.text = items.text
        Picasso.with(itemView.context)
            .load(items.image)
            .placeholder(R.mipmap.ic_launcher_round)
            .error(R.drawable.ic_launcher_foreground)
            .into(picture)
    }
  }
}

Log

    java.lang.IllegalArgumentException: Path must not be empty.
    at com.squareup.picasso.Picasso.load(Picasso.java:297)
    at com.example.test2.activityThree.ActivityThreeAdapter$ExampleViewHolder.bindItems(ActivityThreeAdapter.kt:33)
    at com.example.test2.activityThree.ActivityThreeAdapter.onBindViewHolder(ActivityThreeAdapter.kt:22)
    at com.example.test2.activityThree.ActivityThreeAdapter.onBindViewHolder(ActivityThreeAdapter.kt:13)

P.S. Я нашел решение на англоязычном форуме stackoverflow. Но спасибо за ответы, думаю тем, кто столкнется с этой проблемой - будет ее проще решить, так как ответ есть уже и на русскоязычном форуме.

3
  • Здравствуйте,покажите,пожалуйста логи :) 26 апр 2021 в 15:14
  • @Tony Добавил логи. Добрый вечер) 26 апр 2021 в 15:17
  • дал ответ и решение :) 26 апр 2021 в 15:19

1 ответ 1

2

Ваше приложение крашится по причине того, что items.image в адаптере пустой. В метод load() библиотеки Picasso нельзя передавать пустую строку, именно по этому у вас возникает ошибка.

Какое решение:

if (items.image.isEmpty()) {
     picture.setImageResource(R.drawable.placeholder);
}else{
     Picasso.get().load(items.image).into(picture);
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.