Home » Java » java – Getting return value from a Volley request-Exceptionshub

java – Getting return value from a Volley request-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have seen many response on the subject matter but none is enough for what I want.

I want to be able to return a response like a list from a volley response and pass that list to another class to be added to my database.

I have tried use an interface and a callback function but the response still hangs in another interface.

I want something like this

class Big:Interface{
  override fun A():List<Model> = getResponseFromVolley()
  fun getResponseFromVolley(){ setUp Volley request return List}

}

How can I do this

Code

class RemoteDataSourceManager: ServiceCall {

    override suspend fun getMovies(context: Context): Result<List<MovieEntity>> {

        var results: Result<List<MovieEntity>>

      getRemoteMovies(context, object : VolleyCallBack{
          override fun onResponse(result: Result<List<MovieEntity>>): Result<List<MovieEntity>> {
              results = result
              return results
          }

      })

        return results //result mustbe initialized


    }

    private fun getRemoteMovies(context: Context, callBack: VolleyCallBack): Result<List<MovieEntity>> {
        val responseBool = MutableLiveData<Boolean>(false)
        var listResult: Result<List<MovieEntity>>
        val listOfMovies = ArrayList<MovieEntity>()

        val url =
            "https://api.themoviedb.org/3/movie/popular?api_key=f1e256985ebc2be710bf1f4ed754da11&language=en-US&page=1"
        val request: JsonObjectRequest =
            JsonObjectRequest(
                Request.Method.GET,
                url, null,
                Response.Listener { response ->

                    try {
                        val results = response.getJSONArray("results")
                        val size = results.length()
                        var title = ""
                        var movieImage = ""
                        var rating = 0
                        var overView = ""
                        var releaseDate = ""
                        var movieId = ""

                        for (movie in 0 until results.length()) {
                            val eachMovie = results.getJSONObject(movie)
                            movieImage = "https://image.tmdb.org/t/p/w500"
                            title = eachMovie.getString("title")
                            movieImage +=eachMovie.getString("poster_path")
                            rating  = eachMovie.getInt("vote_average")
                            overView = eachMovie.getString("overview")
                            releaseDate = eachMovie.getString("release_date")
                            movieId = eachMovie.getInt("id").toString()

                            val newMovie =  MovieEntity(
                                title,
                                movieImage,
                                rating,
                                overView,
                                releaseDate
                            )
                            newMovie.movieId = movieId
                            newMovie.id = movieId.toInt()
                            listOfMovies.add(newMovie)

                            responseBool.value = true


                        }

                        listResult = getResult(Result.Success(listOfMovies.toList()))


                        callBack.onResponse(listResult)
                        Log.i("insideList", "$listOfMovies")

                    } catch (e: Exception) {
                        Log.i("error", "Response $e")

//                        Toast.makeText(context!!.applicationContext, "No activity", Toast.LENGTH_SHORT).show()
                    }
                }, Response.ErrorListener { error ->

                    val errroMessage = VolleyErrorHandler.instance.erroHandler(error)
                    CoroutineScope(Dispatchers.Main).launch {
//                        Toast.makeText(context, errroMessage, Toast.LENGTH_LONG).show()
                    }

                })

        context.applicationContext.let {
            VolleySingleton.getInstance(it).addToRequestQueue(request)

        }

        Log.i("listOfMovies", "$listResult")
        return listResult
    }

    override suspend fun saveMovies(movieEntity: MovieEntity) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    interface VolleyCallBack{
        fun onResponse(result:Result<List<MovieEntity>>): Result<List<MovieEntity>>

    }

    private fun getResult(result: Result<List<MovieEntity>>):Result<List<MovieEntity>>{
        return result
    }



}
How to&Answers:
  1. Your interface should not have return value, that’s useless.
interface VolleyCallBack{
        fun onResponse(result: Result<List<MovieEntity>>)

    }
  1. You’re querying data from internet, so will need time to receive it. I recommend you only send data to other class. Like this:

In your original class:

fun getMovies() {
// start request data from internet. Should have something to notify user that i'm requesting data (loading dialog for example)
//loadingdialog.show()
RemoteDataSorceManager().getRemoteMovies(context, object : VolleyCallBack{
          override fun onResponse(result: Result<List<MovieEntity>>) {
// this is when you receive data
// loadingdialog.hide()
              sendDataToOtherClassAndSaveToDatabase(result)
              [email protected]
          }

      })
}

I’m not familiar with Volley. Just my opinion.