안드로이드 토이 프로젝트#3 - 이미지 로드 HTTPConnection, Picasso 라이브러리
- 안드로이드
- 2019. 4. 4. 21:01
Http Connection을 이용한 이미지 로드
Picasso 라이브러리를 이용한 이미지 로드
HTTP Connection을 이용한 이미지 로드
RequestHttpURLConnection 클래스에 getImageFromURL(url :String)함수를 추가한다.
fun getImageFromURL(url :String) : Bitmap? {
var imgBitmap : Bitmap? = null
try {
val url = URL(url)
val conn = url.openConnection()
val nSize :Int = conn.getContentLength()
val bis :java.io.BufferedInputStream = java.io.BufferedInputStream(conn.getInputStream(), nSize)
imgBitmap = BitmapFactory.decodeStream(bis)
bis.close()
}catch (e: java.lang.Exception) {
e.printStackTrace()
}
return imgBitmap
}
URL(url) : URL인스턴스 생성
url.openConnection : URL인스턴스에서 Connection 설정
conn.getInputStream() : URLConnection인스턴스에서 입력스트림 설정
연결을 원하는 URL로 URL클래스 객체를 생성하고, openConnection()메서드를 통해 URLConnection의 접속객체를 생성하여 주어진 URL에 접속 하고 있다. 그리고 URLConnection객체로 부터 InputStream을 구한 뒤, 이를 BitmapFactory를 이용해서 비트맵 데이터로 변경 하였다.
getImageFromURL(url: String)을 호출하는 부분은 ViewHolder에서 해주었다. url로 부터 이미지를 받아오는 것도 네트워크 작업이므로 AsyncTask를 이용하여 구현하였다.
class MainViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val imgBook = itemView?.findViewById<ImageView>(R.id.imgBook)
private val txtBookName = itemView?.findViewById<TextView>(R.id.txtBookName)
private val txtBookPrice = itemView?.findViewById<TextView>(R.id.txtBookPrice)
lateinit var networkTask : NetworkTask
fun bind ( book: Book, context: Context) {
txtBookName.text = book.name
txtBookPrice.text = book.price
networkTask = NetworkTask(book.photo)
imgBook.setImageBitmap(networkTask.execute().get())
}
class NetworkTask(url: String) : AsyncTask<Void, Void, Bitmap?>() {
private val url = url
override fun doInBackground(vararg p0: Void?): Bitmap? {
var result: Bitmap?
val requestHttpURLConnection = RequestHttpURLConnection()
result = requestHttpURLConnection.getImageFromURL(url)
Log.d("MainActivity", "result : $result")
return result
}
}
}
Picasso 라이브러리 이용하기
URL로 부터 이미지를 로드하는 기능을 Picasso라이브러리를 이용하여 구현해 보도록 하겠다.
우선 Picasso라이브러리를 이용할 수 있도록 Module단 Gradle에 아래 부분을 추가한다.
implementation 'com.squareup.picasso:picasso:2.5.2'
그리고 다시 ViewHolder로 돌아와서 아래 부분 처럼 구현 해주면 된다.
class MainViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val imgBook = itemView?.findViewById<ImageView>(R.id.imgBook)
private val txtBookName = itemView?.findViewById<TextView>(R.id.txtBookName)
private val txtBookPrice = itemView?.findViewById<TextView>(R.id.txtBookPrice)
fun bind ( book: Book, context: Context) {
txtBookName.text = book.name
txtBookPrice.text = book.price
Picasso.with(context)
.load(book.photo)
.into(imgBook)
}
}
book.photo는 이미지 url이고 이것으로 부터 이미지를 load해서 imgBook(ImageView)에 적용한다.
완료된 화면은 다음과 같다.
'안드로이드' 카테고리의 다른 글
안드로이드 토이 프로젝트#4 - Rtrofit2 적용 (0) | 2019.04.08 |
---|---|
안드로이드 토이 프로젝트#2 - HTTP Connection HttpURLConnection 사용하기 (0) | 2019.03.27 |
안드로이드 토이 프로젝트#1 - RecyclerView 적용 (0) | 2019.03.25 |
이 글을 공유하기