использовать картинки с JSON не используя библиотеки
Как лучше выгрузить картинки из JSON в PhotoAdaper? Использую RecyclerView, создал отдельную функцию в ViewHolder. В Activity обработал загрузку альбома и фото, которые надо выгрузить из JSON.
class PhotosAdapter : RecyclerView.Adapter<PhotosAdapter.PhotosViewHolder>() {
var photos: List<Photo> = mutableListOf()
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PhotosViewHolder {
val view = LayoutInflater.from(parent.context).inflate(
R.layout.item_photo,
parent,
false
)
return PhotosViewHolder(view)
}
override fun onBindViewHolder(holder: PhotosViewHolder, position: Int) {
holder.bind(photos[position])
}
override fun getItemCount(): Int = photos.size
class PhotosViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val imageViewPhoto: ImageView = itemView.findViewById(R.id.imageViewPhoto)
private val textViewTitle: TextView = itemView.findViewById(R.id.textViewTitle)
fun bind(photo: Photo) {
textViewTitle.text = photo.title
loadPhotoIntoImageView(photo.url, imageViewPhoto)
}
private fun loadPhotoIntoImageView(url: String, imageView: ImageView) {
//Тут как-то надо загрузить фото в ImageView
}
}
}
Вот код из самой активности:
class PhotoActivity : AppCompatActivity() {
private val mapper = Mapper()
private val adapter = PhotosAdapter()
private lateinit var recyclerViewPhotos: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_photo)
recyclerViewPhotos = findViewById(R.id.recyclerViewPhotos)
recyclerViewPhotos.adapter = adapter
val id = intent.getIntExtra(EXTRA_USER_ID, -1)
DownloadPhotosTask(id, adapter, mapper).execute()
}
class DownloadPhotosTask(
private val userId: Int,
private val adapter: PhotosAdapter,
private val mapper: Mapper
) : AsyncTask<Void, Void, List<Photo>>() {
override fun doInBackground(vararg params: Void?): List<Photo> {
return try {
val albumList = loadAlbum(userId)
val albumIds = albumList.map { it.id }
return loadPhotos(albumIds)
} catch (e: Exception) {
emptyList()
}
}
override fun onPostExecute(result: List<Photo>?) {
super.onPostExecute(result)
if (result == null) return
adapter.photos = result
}
private fun loadAlbum(userId: Int): List<Albums> {
val url = URL("$LOAD_USER_ALBUM?${Albums.KEY_USERID}=$userId")
val urlConnection = url.openConnection()
val inputStreamReader = BufferedReader(
InputStreamReader(urlConnection.getInputStream())
)
val builder = StringBuilder()
var line = inputStreamReader.readLine()
while (line != null) {
builder.append(line)
line = inputStreamReader.readLine()
}
return mapper.mapJSONToAlbumsList(JSONArray(builder.toString()))
}
private fun loadPhotos(albumIds: List<Int>): List<Photo> {
val idsToPhotoUrlBuilder = StringBuilder()
for (i in albumIds.indices) {
if (i == 0) {
idsToPhotoUrlBuilder.append("?")
} else {
idsToPhotoUrlBuilder.append("&")
}
idsToPhotoUrlBuilder.append("${Photo.KEY_ALBUMID}=${albumIds[i]}")
}
val url = URL(LOAD_USER_PHOTO + idsToPhotoUrlBuilder.toString())
val urlConnection = url.openConnection()
val inputStreamReader = BufferedReader(
InputStreamReader(urlConnection.getInputStream())
)
val builder = StringBuilder()
var line = inputStreamReader.readLine()
while (line != null) {
builder.append(line)
line = inputStreamReader.readLine()
}
return mapper.mapJSONToPhotoList(JSONArray(builder.toString()))
}
}
companion object {
const val EXTRA_USER_ID = "extra_user_id"
const val LOAD_USER_PHOTO = "https://jsonplaceholder.typicode.com/photos"
private const val LOAD_USER_ALBUM = "https://jsonplaceholder.typicode.com/albums"
fun newIntent(context: Context, userId: Int): Intent {
val intent = Intent(context, PhotoActivity::class.java)
intent.putExtra(EXTRA_USER_ID, userId)
return intent
}
}
}