Get request with id in Retrofit is not working

69 Views Asked by At

i am building a BookShelf app with Google Books api and i am making two Get requests first for search for books which is working and second for getting the details of specific book with id in viewModel it is not working it is even not reaching to the second function here is my code

BooksApiService.kt

private const val BASE_URL = "https://www.googleapis.com/books/v1/"

private val retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build()

interface BooksApiService {
    @GET("volumes")
    suspend fun getBooks(@Query(value = "q") q: String): Response<Books>

    @GET("volumes/{id}")
    suspend fun getBookById(@Path("id") id: String): Response<BookInformation>
}

object BooksApi {
    val retrofitService : BooksApiService by lazy {
        retrofit.create(BooksApiService::class.java)
    }
}

ViewModel.kt


class BookShelfViewModel : ViewModel() {
    private val _books = MutableLiveData("")
    val books: LiveData<String> = _books
    private val _imageUrl = MutableLiveData("")
    val imageUrl: LiveData<String> = _imageUrl
    init {
        getBooks()
    }
    private fun getBooks() {
        viewModelScope.launch {
            try {
                val listResult = BooksApi.retrofitService.getBooks("jazz+history")
                _books.value = listResult.body()?.items?.get(0)?.id
                _books.value?.let { getBookDetails(it) }
            } catch (e: IOException) {
                Log.d("App error","Network connection failed")
            }
        }
    }

    private fun getBookDetails(bookId: String) {
        viewModelScope.launch {
            try {
                val listResult = BooksApi.retrofitService.getBookById(bookId)
                Log.d("BookDetails","${listResult.body()}")

                if (listResult.isSuccessful) {
                    Log.d("ImageUrl","${listResult.body()?.volumeInfo?.imageLinks?.thumbnail}")
                    _imageUrl.value = listResult.body()?.volumeInfo?.imageLinks?.thumbnail
                } else {
                    Log.d("BookDetails","Network call failed with code ${listResult.code()}")
                }
            } catch (e: IOException) {
                Log.d("App error","Network in second time is failed")
            }
        }
    }
}

CheckingFragment.kt

class CheckingFragment : Fragment() {
    private var _binding: FragmentCheckingBinding? = null
    val binding
        get() = _binding!!

    private val viewModel : BookShelfViewModel by viewModels()
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentCheckingBinding.inflate(inflater,container,false)
        val view = binding.root
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.books.observe(viewLifecycleOwner) { newBooks ->
            binding.responseText.text = newBooks
        }
        viewModel.imageUrl.observe(viewLifecycleOwner) { imageUrl ->
            binding.responseImage.load(imageUrl)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }

I add logging it is not even reaching to getBookDetails() function why is that and i want to show image on the screen?

if you want to understand better here is specification how you will implement that?

Create a Retrofit service to get data from the Google Books API. Add methods for the service to get a list of books and get information about a specific book. Use Gson to extract meaningful data from the JSON response returned by the API. Let's briefly go over the methods of the Google Books API that you need for this project.

Search for books The Google Books API provides a method that returns a list of books based on a particular search term, as described in Using the API.

For example, this URL returns search results for the term "jazz history".

Example

https://www.googleapis.com/books/v1/volumes?q=jazz+history There are several query parameters to filter your search. For the Bookshelf app, the q parameter (short for query) is sufficient.

The documentation also shows the expected JSON response. For the Bookshelf app, you need to extract the book's id.

Request info for a specific book You need to make a request to get info on a specific book. This endpoint takes the id you extracted from the previous response.

https://www.googleapis.com/books/v1/volumes/<volume_id> You can find thumbnail links in the imageLinks object in the volumeInfo object. For this app, the images you want to download are under the thumbnail key.

Tip: Because you need to make two sets of requests to get the image URLs, getting the list of book images is more involved than what you did in the Mars photos app.

The following approach might help you implement this app:

Perform the first request to search for books. Perform the requests to get individual book data one after another in the same coroutine. This way, each request is performed one after the other until the coroutine finishes. After all the requests have finished, store each thumbnail in a MutableList. Load each of the thumbnails in the AsyncImage composables. Download book thumbnails After you have the thumbnail URL, it can be provided to the AsyncImage composable in each grid item.

0

There are 0 best solutions below