Skip to content

Commit

Permalink
Added coroutines for the httpreq function and handled exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
ayanchavand committed Dec 24, 2023
1 parent b5e01ad commit f6f9850
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 40 deletions.
92 changes: 53 additions & 39 deletions app/src/main/java/com/example/app/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ import android.widget.Button
import android.widget.ImageView
import android.widget.Switch
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Callback
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException


Expand All @@ -29,58 +31,68 @@ class MainActivity : AppCompatActivity() {
val apiToggle: Switch = findViewById(R.id.apiToggle)
val apiText: TextView = findViewById(R.id.apiText)

fun showToast( message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

submitCat.setOnClickListener {
Glide.with(this).clear(image)
if(apiToggle.isChecked()){
apiText.text = "API: cataas.com"
val imageUrl = "https://cataas.com/cat?timestamp=${System.currentTimeMillis()}"
Glide.with(this).load(imageUrl).into(image)
}

else{
apiText.text = "API: thecatapi.com"
val response = httpReq("null", "https://api.thecatapi.com/v1/images/search")
Log.d("LOG!", response)
val imageUrl = jsonParserCat(response)
Log.d("LOG!", imageUrl)
Glide.with(this).load(imageUrl).into(image)
GlobalScope.launch(Dispatchers.Main) {
Glide.with(this@MainActivity).clear(image)
if (apiToggle.isChecked()) {
apiText.text = "API: cataas.com"
val imageUrl = "https://cataas.com/cat?timestamp=${System.currentTimeMillis()}"
Glide.with(this@MainActivity).load(imageUrl).into(image)
} else {
apiText.text = "API: thecatapi.com"
try {
val response = httpReq("null", "https://api.thecatapi.com/v1/images/search")
Log.d("LOG!", response)
val imageUrl = jsonParserCat(response)
Log.d("LOG!", imageUrl)
Glide.with(this@MainActivity).load(imageUrl).into(image)
} catch (e: Exception) {
// Handle exceptions, e.g., network errors
Log.e("LOG!", "Error fetching data", e)
showToast("Something went wrong: Error fetching data")
}
}
}
}

submitDog.setOnClickListener {
apiText.text = "API: dog.ceo"
val response = httpReq("", "https://dog.ceo/api/breeds/image/random")
val imageUrl = jsonParserDog(response)
Log.d("LOG!", imageUrl)
Glide.with(this).load(imageUrl).into(image)

GlobalScope.launch(Dispatchers.Main) {
apiText.text = "API: dog.ceo"
try {
val response = httpReq("", "https://dog.ceo/api/breeds/image/random")
val imageUrl = jsonParserDog(response)
Log.d("LOG!", imageUrl)
Glide.with(this@MainActivity).load(imageUrl).into(image)
} catch (e: Exception) {
// Handle exceptions, e.g., network errors
Log.e("LOG!", "Error fetching data", e)
showToast("Something went wrong: Error fetching data")
}
}
}
}
}

private fun httpReq(apiKey: String, url: String): String{

private suspend fun httpReq(apiKey: String, url: String): String = withContext(Dispatchers.IO) {
val client = OkHttpClient()
val request = Request.Builder().url(url).build()
var jsonResponse = ""

client.newCall(request).enqueue(object :Callback{
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
//On successful request
override fun onResponse(call: Call, response: Response) {
if(response.isSuccessful){
jsonResponse = response.body!!.string()
Log.d("LOG", jsonResponse)

return@withContext try {
client.newCall(request).execute().use { response ->
if (response.isSuccessful) {
response.body!!.string()
} else {
throw IOException("Unexpected HTTP code: ${response.code}")
}
}
})
while(jsonResponse == ""){
continue
} catch (e: IOException) {
throw IOException("Error during HTTP request", e)
}
return jsonResponse
}

private fun jsonParserCat(responseString: String): String{
Expand All @@ -106,3 +118,5 @@ private fun jsonParserDog(responseString: String): String{
return dogData.message;
}



2 changes: 1 addition & 1 deletion app/src/main/res/layout/activity_main.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
android:id="@+id/textView2"
android:layout_width="144dp"
android:layout_height="31dp"
android:text="Kitty"
android:text="Pets"
android:textAlignment="center"
android:textSize="20sp"
android:textStyle="bold"
Expand Down

0 comments on commit f6f9850

Please sign in to comment.