(Android Kotlin) Как извлечь изображение «Имя» из хранилища Firebase по нажатию кнопки в программе recyclerView? - PullRequest
0 голосов
/ 03 мая 2020

Цель:
Чтобы извлечь «имя» изображения по умолчанию из изображений, имеющихся в хранилище Firebase, по нажатию кнопки, чтобы имя можно было сохранить в локальном текстовом файле. (который будет использоваться для фильтрации изображений в дальнейшем).

Настройка до сих пор:

  • Создан просмотр recycler, который отображает изображения из хранилища базы данных в cardView.
  • Каждая карта в программе recyclerView содержит только изображение и кнопку "doneButton".
  • Имеет функцию сохранения строк в локальном текстовом файле.

Где я застрял:

  • Невозможно получить имя изображения из хранилища при нажатии кнопки, оба из которых (кнопка & image) присутствуют на карте в программе recyclerView.

  • После того, как имя получено, при нажатии одной и той же кнопки необходимо передать имя изображения в функцию сохранения имени запишите его в локальный текстовый файл.

Было бы очень полезно, если кто-то может помочь с этим. Спасибо. (К вашему сведению: я новичок в android разработке)


Основная активность:

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


    //firebase
    val storage = FirebaseStorage.getInstance()
    val storageRef = storage.reference.child("Images")
    val imageList:ArrayList<CoronaImages> = ArrayList()


    val listAllTask: Task<ListResult> = storageRef.listAll()
    listAllTask.addOnCompleteListener{ result ->
        val items: List<StorageReference> = result.result!!.items

        //cycle for adding image URL to list
        items.forEachIndexed { index, item ->
            item.downloadUrl.addOnSuccessListener {
                Log.d("item","$it")
                imageList.add(CoronaImages(it.toString()))
            }.addOnCompleteListener{

                ImageRecyclerView.adapter = ImageAdapter(imageList, this)
                ImageRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true)
            }
        }
    }
}

Адаптер (с попытка создать OnClickListener для имени изображения):

class ImageAdapter (
        private var coronaImage: List<CoronaImages>, private val context: Context):
        RecyclerView.Adapter<ImageAdapter.ViewHolder>(){

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            LayoutInflater.from(context).inflate(R.layout.corona_images, parent, false)
        )
    }

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val item = coronaImage[position]
    Picasso.get()
        .load(item.imageUrl)
        .into(holder.imageView)
}

override fun getItemCount(): Int {
    return coronaImage.size
}

class ViewHolder(view: View):RecyclerView.ViewHolder(view), View.OnClickListener {
        val imageView: ImageView=view.findViewById(R.id.imageView1)


// this is where I'm stuck:
        val doneButton: CardView=view.findViewById(R.id.doneButton)

        init {
            doneButton.setOnClickListener {
                object : View.OnClickListener {
                        override fun onClick(v: View?) {


             // how can I retrieve the image name and pass it to the writeToFile ()??


                        writeToFile(????)
                        }
                    }
                }
            }

            // Function to Write to a File
            fun writeToFile(FirebaseImageName: String) {
            try {
                var writeData = FileWriter("doneCoronaImages.txt", true)
                writeData.write(FirebaseImageName +"\n")
                writeData.close()
            }
            catch (ex: Exception) {
                print("Could not save the image name.")
            }
        }
    }
}

Класс данных для URL-адресов изображений:

data class CoronaImages(
    var imageUrl: String
)

coronaImage XML

<com.google.android.material.card.MaterialCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card"
    android:layout_width="match_parent"
    android:layout_height="455dp"
    android:layout_margin="8dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <!-- Media -->
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="390dp"
            android:scaleType="centerCrop" />

        <!-- Buttons -->
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:orientation="horizontal">

            <Button
                android:id="@+id/coronaButton"               style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
                android:layout_width="90sp"
                android:layout_height="55sp"
                android:layout_marginStart="0dp"
                android:layout_marginEnd="8dp"
                android:layout_marginBottom="0dp"
                android:text="@string/coronaButtonTitle"
                android:textSize="16sp"/>
        </LinearLayout>
    </LinearLayout>
</com.google.android.material.card.MaterialCardView>

1 Ответ

0 голосов
/ 03 мая 2020
doneButton.setOnClickListener {
      val item = coronaImage[adapterPosition] // get image item
      val imageName = File(item.imageUrl).name // get image name
      writeImageNameToFile(context, "doneCoronaImages.txt", imageName)
}

или

view.setOnClickListener {
      val item = coronaImage[adapterPosition] // get image item
      val imageName = File(item.imageUrl).name // get image name
      writeImageNameToFile(context, "doneCoronaImages.txt", imageName)
}

Создание папки и запись в файл.

fun writeImageNameToFile(
context: Context,
fileName: String?,
imageName: String?
) {
    try {
        val root = File(context.getExternalFilesDir(null), "YourFolder")
        if (!root.exists()) {
            root.mkdirs() // create folder if you want
        }
        // val root = File(context.getExternalFilesDir(null)?.absolutePath) // use this line if you don't want to create folder
        val txtFile = File(root, fileName)
        val writer = FileWriter(txtFile, true)
        writer.appendln(imageName)
        writer.flush()
        writer.close()
        Toast.makeText(context, "Saved image", Toast.LENGTH_SHORT).show()
    } catch (e: IOException) {
        e.printStackTrace()
    }
}

Device File Explorer -> хранилище -> эмулировано -> 0 -> Android -> Данные -> YourPackageName -> Файлы -> YourFolder -> doneCoronaImages.txt

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...