не отвечающая ошибка в вызове Api базы данных фильма в ViewModel - PullRequest
0 голосов
/ 05 апреля 2019

Я пытаюсь работать с модифицированной архитектурой и архитектурой viewmodel, однако я не могу выполнить вызов из Api базы данных фильма

В проекте при создании моего фрагмента добавлен вызов getPopularMovies() метод ViewModel, который отвечает за вызов интерфейса, в котором он содержит метод @GET для API.Но повторные попытки точно возвращают onError в RepositoryImpl и в ViewModel

interface TMDbService{

    @GET("movie/popular")
    fun getPopuparMovies(@Query("api_key") apiKey: String,
                         @Query("language") lang: String,
                         @Query("page") page: Int): Call<MovieResponse>

}

interface OnGetMoviesCallback{
    fun onSuccess(movies: List<Movie>)
    fun onError()
}

RepositoryImpl

open class MovieRepositoryImpl: MovieRepository {
    private var service: TMDbService

    companion object {
        const val BASE_URL = "https://api.themoviedb.org/3/"
        const val LANGUAGE = "pt-BR"
        const val API_KEY = "XXX"
        const val DEFAULT_PAGE_VALUE = 1
    }

    init {
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        service = retrofit.create(TMDbService::class.java)
    }

    override fun getPopularMovies(callback: OnGetMoviesCallback) {
        service.getPopuparMovies(API_KEY, LANGUAGE, DEFAULT_PAGE_VALUE)
            .enqueue(object : Callback<MovieResponse>{
                override fun onResponse(call: Call<MovieResponse>, response: Response<MovieResponse>) {

                    if (response.isSuccessful){
                        val movieResponse = response.body()
                        if (movieResponse?.movies != null){
                            callback.onSuccess(movieResponse.movies)
                        } else {
                            callback.onError()
                            Log.e("Response", javaClass.simpleName + " response null")
                        }
                    } else {
                        callback.onError()
                        Log.e("Response", javaClass.simpleName + " not response 1")
                    }

                }

                override fun onFailure(call: Call<MovieResponse>, t: Throwable) {
                    callback.onError()
                    Log.e("Response", javaClass.simpleName + " not response 2")
                }
            })
    }

}

ViewModel.kt

class HomeViewModel(private val repository: MovieRepository = MovieRepositoryImpl()) : ViewModel() {

    fun verifyConnectivity(activity: HomeActivity): Boolean {
        val connectivityManager = activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }

    fun getPopularMovies(){

        repository.getPopularMovies(object : OnGetMoviesCallback{
            override fun onSuccess(movies: List<Movie>) {
                Log.d("OnSuccess", "Its Ok")
            }

            override fun onError() {
                Log.e("ErrorViewModel", "Error in viewmodel call")
            }
        })

    }

}

Models

data class Movie(
    @SerializedName("id")
    @Expose
    val id: Int = 0,

    @SerializedName("title")
    @Expose
    val title: String? = null,

    @SerializedName("poster_path")
    @Expose
    val posterPath: String? = null,

    @SerializedName("release_date")
    @Expose
    val releaseDate: String? = null,

    @SerializedName("vote_average")
    @Expose
    val rating: Float = 0.toFloat(),

    @SerializedName("genre_ids")
    @Expose
    val genreIds: List<Int>? = null,

    @SerializedName("backdrop_path")
    @Expose
    val backdropPath: String? = null)

data class MovieResponse(
    @SerializedName("page")
    @Expose
    val page: Int = 0,

    @SerializedName("total_results")
    @Expose
    val totalResults: Int = 0,

    @SerializedName("results")
    @Expose
    val movies: List<Movie>? = null,

    @SerializedName("total_pages")
    @Expose
    val totalPages: Int = 0
)

В этом случае начало вызова происходит в ViewModel в методе getPopularMovies (), который при вызове возвращает в журнал ошибок журналы с описаниями: «not response 2» в репозитории и «Error in viewmodel»вызов "во ViewModel.Я надеюсь, что мой сервис в конце может ВЫЗВАТЬ этот URL: https://api.themoviedb.org/3/movie/popular?api_key=XXX&language=en&page=1

с равным возвратом Json ниже:

{
    "page": 1,
    "total_results": 19779,
    "total_pages": 989,
    "results": [
        {
            "vote_count": 1267,
            "id": 166428,
            "video": false,
            "vote_average": 7.7,
            "title": "Como Treinar o Seu Dragão 3",
            "popularity": 493.655,
            "poster_path": "/5uqxMHM7YLKk6yni4bOE0D6DVz8.jpg",
            "original_language": "en",
            "original_title": "How to Train Your Dragon: The Hidden World",
            "genre_ids": [
                16,
                10751,
                12
            ],
            "backdrop_path": "/h3KN24PrOheHVYs9ypuOIdFBEpX.jpg",
            "adult": false,
            "overview": "Soluço busca realizar seu grande sonho de encontrar um lar pacífico onde os dragões possam viver em segurança. Lá, Banguela descobre uma companheira, assim como ele, mas um tanto selvagem. Mas é quando o perigo começa a rondar o lar, que a dupla Banguela e Soluço é testada e precisa tomar decisões difíceis para salvar suas espécies.",
            "release_date": "2019-01-03"
        },
        {
            "vote_count": 3316,
            "id": 299537,
            "video": false,
            "vote_average": 7.2,
            "title": "Capitã Marvel",
            "popularity": 369.741,
            "poster_path": "/hVgLHgnsO46oSHJy5I4ekhqtoYv.jpg",
            "original_language": "en",
            "original_title": "Captain Marvel",
            "genre_ids": [
                28,
                12,
                878
            ],
            "backdrop_path": "/w2PMyoyLU22YvrGK3smVM9fW1jj.jpg",
            "adult": false,
            "overview": "A história segue Carol Danvers e como ela se torna um dos heróis mais poderosos do universo quando a Terra é pega no meio de uma guerra galáctica entre duas raças alienígenas. Situado na década de 1990, Capitã Marvel é uma nova aventura de um período inédito na história do universo cinematográfico da Marvel.",
            "release_date": "2019-03-06"
        },
        {
            "vote_count": 632,
            "id": 458723,
            "video": false,
            "vote_average": 7.4,
            "title": "Nós",
            "popularity": 185.833,
            "poster_path": "/ioceyCFcOC9LfUCkOGZNMbsuc2o.jpg",
            "original_language": "en",
            "original_title": "Us",
            "genre_ids": [
                53,
                27
            ],
            "backdrop_path": "/ADJ6V8W96It4KElY2SPZvkKPBR.jpg",
            "adult": false,
            "overview": "O casal Gabe e Adelaide Wilson leva seus filhos para uma casa de praia, esperando se desconectar e descontrair com os amigos. Mas à medida que a noite cai, sua serenidade se transforma em tensão e caos quando alguns visitantes chocantes chegam sem serem convidados.",
            "release_date": "2019-03-14"
        },

Ошибка журнала printStackTrace ()

W/System.err: javax.net.ssl.SSLException: SSL handshake aborted: ssl=0xb93b5090: I/O error during system call, Connection reset by peer
W/System.err:     at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
        at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)
        at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:281)
        at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:251)
        at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:151)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:192)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
        at java.lang.Thread.run(Thread.java:841)
...