'2020/04/17'에 해당되는 글 1건

728x90

서버에서 사진 정보를 가져오는데 사진 파일이 존재하는지 URL 로 확인하는 코드이다.

RecyclerView 에 사진을 보여주는 cardView Item 작성할 때 적용했다.

메인쓰레드에서 처리하면 에러가 발생하므로 AsyncTask 를 이용한다.



앱 build.gradle

// 이미지 출력용 Glide
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'

    inner class URLExistTask : AsyncTask<String, Void, Boolean>() {
        override fun doInBackground(vararg params: String?): Boolean {
            return try {
                HttpURLConnection.setFollowRedirects(false)
                val con: HttpURLConnection = URL(params[0]).openConnection() as HttpURLConnection
                con.setConnectTimeout(1000)
                con.setReadTimeout(1000)
                con.setRequestMethod("HEAD")
                con.getResponseCode() === HttpURLConnection.HTTP_OK
            } catch (e: Exception) {
                e.printStackTrace()
                false
            }
        }
    }
 


사용법

val mImage: ImageView? = itemView?.findViewById(R.id.listitem_image)

val imageUri: String = "http://www.abc.com/photos/${person.idx}.jpg"

if (mImage != null) {
    val urlexist: Boolean = URLExistTask().execute(imageUri).get()
    if (urlexist) {
        Glide.with(context).load(imageUri).override(126, 160).into(mImage)
    } else {
        val resourceId: Int = R.drawable.photo_base
        Glide.with(context).load(resourceId).override(126, 160).into(mImage)
    }
};


#### 함수를 만드는 과정 ####

먼저 Java 로 된 함수를 찾는다.

public static boolean exists(String URLName) {
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}


그런데 메인쓰레드에서 처리하면 android.os.NetworkOnMainThreadException kotlin 에러가 발생하므로 AsyncTask 에서 동작하도록 코드를 수정해야 한다.

'안드로이드 > Kotlin 기능' 카테고리의 다른 글

[코틀린] PrefsHelper  (0) 2020.05.04
[코틀린] ViewPager 만들기  (0) 2020.04.24
[코틀린] webView 예제1  (0) 2020.04.20
[코틀린] RecyclerView Part 1  (0) 2020.04.19
Splash Screen with Kotlin  (0) 2020.04.09
블로그 이미지

Link2Me

,