Skip to content

Instantly share code, notes, and snippets.

View kelmer44's full-sized avatar
🤔

Gabriel Sanmartín kelmer44

🤔
View GitHub Profile
val inputStream = connection.inputStream ?: throw HttpException(
responseCode,
"Error executing request"
)
reader = BufferedReader(InputStreamReader(inputStream))
val readLines = reader.readLines()
if (readLines.isEmpty()) {
return ""
}
class GsonSerializer(private val gson: Gson): Serializer{
override fun deserialize(json: String): ApiResponse {
return gson.fromJson<ApiResponse>(json, ApiResponse::class.java)
}
}
override fun deserialize(json: String): ApiResponse {
val root = JSONObject(json)
val stat = root.getString("stat")
val photos = root.getJSONObject("photos")
val page = photos.getInt("page")
val pages = photos.getInt("pages")
val perPage = photos.getInt("perpage")
fun load(url: String, imageView: ImageView, @DrawableRes loader: Int, height: Int) {
imageViews[imageView] = url
queuePhoto(url, imageView, height)
imageView.setImageResource(loader)
}
interface FlickrService {
fun search(
apiKey: String, term: String, perPage: Int, page: Int
): ApiResponse
}
override fun search(term: String, page: Int): PhotoListPage {
val apiResponse = flickrService.search(apiKey, term, PERPAGE, page)
return PhotoListPage(term,
page, apiResponse.photos.photo.map(adapter::convert), page<apiResponse.photos.pages)
}
private val executor: ExecutorService = Executors.newSingleThreadExecutor()
private val handler: Handler = Handler(Looper.getMainLooper())
interface Callback {
fun onFinished(photoListPage: PhotoListPage)
}
private val adapter = PhotoAdapter()
override fun search(term: String, page: Int, callback: Callback) {
executor.submit {
val apiResponse = flickrService.search(apiKey, term, PERPAGE, page)
callback.onFinished(PhotoListPage(term, page, apiResponse.photos.photo.map(adapter::convert), page < apiResponse.photos.pages))
private fun getBitmap(url: String, height: Int): Bitmap? {
return try {
val imageUrl = URL(url)
val connection = imageUrl.openConnection() as HttpURLConnection
connection.instanceFollowRedirects = true
val inputStream = connection.inputStream
val outputStream = FileOutputStream(f)
copyStream(inputStream, outputStream)
outputStream.close()
private fun decodeFile(f: File, height: Int): Bitmap? {
try {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeStream(FileInputStream(f), null, options)
// Width and height of the bitmap
val bmpWidth = options.outWidth
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.2.0-alpha03'
implementation 'androidx.core:core-ktx:1.1.0'
// Reactive Programming