Skip to content

Instantly share code, notes, and snippets.

View kelmer44's full-sized avatar
🤔

Gabriel Sanmartín kelmer44

🤔
View GitHub Profile
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)
}
interface FlickrService {
fun search(
apiKey: String, term: String, perPage: Int, page: Int
): ApiResponse
}
fun load(url: String, imageView: ImageView, @DrawableRes loader: Int, height: Int) {
imageViews[imageView] = url
queuePhoto(url, imageView, height)
imageView.setImageResource(loader)
}
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")
class GsonSerializer(private val gson: Gson): Serializer{
override fun deserialize(json: String): ApiResponse {
return gson.fromJson<ApiResponse>(json, ApiResponse::class.java)
}
}
val inputStream = connection.inputStream ?: throw HttpException(
responseCode,
"Error executing request"
)
reader = BufferedReader(InputStreamReader(inputStream))
val readLines = reader.readLines()
if (readLines.isEmpty()) {
return ""
}
override fun getSearch(apiKey: String, term: String): Single<ApiResponse> {
return Single.fromCallable {
searchRequest(apiKey, term) ?: throw Exception("Could not retrieve")
}
}
private fun searchRequest(apiKey: String, term: String) : ApiResponse?{
val fullUrl =
"$baseUrl/services/rest?method=flickr.photos.search&format=json&nojsoncallback=1&api_key=$apiKey&text=$term"
val response = client.doGet(fullUrl) ?: return null
return deserialize(response)
}
class StringResponseHttpClient : HttpClient {
override fun doGet(serviceUrl: String) : String? {
var reader: BufferedReader? = null
try {
val url = URL(serviceUrl)
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connect()
interface ServiceLocator {
companion object {
private val LOCK = Any()
private var instance: ServiceLocator? = null
fun instance(context: Context): ServiceLocator {
synchronized(LOCK) {
if (instance == null) {
instance = DefaultServiceLocator(