Почему в Retrofit возвращается нулевое значение? - PullRequest
0 голосов
/ 17 апреля 2020

У меня была проблема в baseUrl, которая не возвращает никакого значения. Не могли бы вы, ребята, помочь мне, пожалуйста? Мне не удалось решить эту проблему. Я только что установил Java version_1_8 на своем Gradle, но он все еще не работает

    public class MainActivity extends AppCompatActivity {

    private static final String TAG = "POKEDEX";
    private RecyclerView recyclerView;
    private ListaPokemonAdapter listaPokemonAdapter;
    private Retrofit retrofit;

    private int offset;
    private boolean aptoParaCarregar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recyclerView);

        listaPokemonAdapter = new ListaPokemonAdapter(this);
        recyclerView.setHasFixedSize(true);
        final GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager( layoutManager );
        recyclerView.setAdapter( listaPokemonAdapter );

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (dy > 0){
                    int visibleItemCount = layoutManager.getChildCount();
                    int totalItemCount = layoutManager.getItemCount();
                    int pastVisibleItems = layoutManager.findFirstVisibleItemPosition();

                    if (aptoParaCarregar){
                        if ( (visibleItemCount + pastVisibleItems) >= totalItemCount ){
                            Log.i(TAG, "Chegamos ao final");

                            offset += 20;
                            recuperarDados( offset );
                            aptoParaCarregar = false;
                        }
                    }
                }
            }
        });

Независимо от того, что я здесь пишу, он всегда будет возвращать нулевое значение, всякий раз, когда я настраиваю Retrofit

        retrofit = new Retrofit.Builder()
                .baseUrl("https://pokeapi.co/api/v2/")
                .addConverterFactory(GsonConverterFactory.create()) //Escolher o conversor a ser utilizado
                .build();

        aptoParaCarregar = true;
        offset = 0;
        recuperarDados(offset);
    }

    private void recuperarDados(int offset) {

        PokemonService service = retrofit.create(PokemonService.class);
        Call<PokemonResposta> call = service.recuperarListaPokemon(20, offset);

        call.enqueue(new Callback<PokemonResposta>() {
            @Override
            public void onResponse(Call<PokemonResposta> call, Response<PokemonResposta> response) {

                aptoParaCarregar = true;
                if (response.isSuccessful()){

                    PokemonResposta pokemonResposta = response.body();
                    ArrayList<Pokemon> listaPokemon = pokemonResposta.getResults();

                    listaPokemonAdapter.adicionarListaPokemon( listaPokemon ); //Passando a lista de objetos para o Adapter


                }else {

                    Log.e(TAG, "onResponse: " + response.errorBody() );
                }
            }

            @Override
            public void onFailure(Call<PokemonResposta> call, Throwable t) {

                Log.e(TAG, "onFailure: " + t.getMessage() );

            }
        });


    }
}

Java Interface:

    import retrofit2.Call;
    import retrofit2.http.GET;
    import retrofit2.http.Query;
    import williamlopes.cursoandroid.requisicoeshttp.pokemon.models.PokemonResposta;

    public interface PokemonService {

        @GET("pokemon")
        Call<PokemonResposta> recuperarListaPokemon(@Query("limit") int limit,
                                                    @Query("offset") int offset);
    }

PokemonResposta Class:

public class PokemonResposta {

    private ArrayList<Pokemon> results;

    public ArrayList<Pokemon> getResults() {
        return results;
    }

    public void setResults(ArrayList<Pokemon> results) {
        this.results = results;
    }
}

Pokemon Class:

publi c class Pokemon {

 private int number;
    private String name;
    private String url;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public int getNumber() {
        String[] urlPartes = url.split("/");
        return Integer.parseInt(urlPartes[urlPartes.length -1]);
    }

    public void setNumber(int number) {
        this.number = number;
    }
}

logcat response:

2020-04-17 12:47:18.317 8946-9007/williamlopes.cursoandroid.requisicoeshttp.pokemon E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1

JSON Данные:

{"count":964,"next":"https://pokeapi.co/api/v2/pokemon/?offset=20&limit=20","previous":null,"results":[{"name":"bulbasaur","url":"https://pokeapi.co/api/v2/pokemon/1/"},{"name":"ivysaur","url":"https://pokeapi.co/api/v2/pokemon/2/"},{"name":"venusaur","url":"https://pokeapi.co/api/v2/pokemon/3/"},{"name":"charmander","url":"https://pokeapi.co/api/v2/pokemon/4/"},{"name":"charmeleon","url":"https://pokeapi.co/api/v2/pokemon/5/"},{"name":"charizard","url":"https://pokeapi.co/api/v2/pokemon/6/"},{"name":"squirtle","url":"https://pokeapi.co/api/v2/pokemon/7/"},{"name":"wartortle","url":"https://pokeapi.co/api/v2/pokemon/8/"},{"name":"blastoise","url":"https://pokeapi.co/api/v2/pokemon/9/"},{"name":"caterpie","url":"https://pokeapi.co/api/v2/pokemon/10/"},{"name":"metapod","url":"https://pokeapi.co/api/v2/pokemon/11/"},{"name":"butterfree","url":"https://pokeapi.co/api/v2/pokemon/12/"},{"name":"weedle","url":"https://pokeapi.co/api/v2/pokemon/13/"},{"name":"kakuna","url":"https://pokeapi.co/api/v2/pokemon/14/"},{"name":"beedrill","url":"https://pokeapi.co/api/v2/pokemon/15/"},{"name":"pidgey","url":"https://pokeapi.co/api/v2/pokemon/16/"},{"name":"pidgeotto","url":"https://pokeapi.co/api/v2/pokemon/17/"},{"name":"pidgeot","url":"https://pokeapi.co/api/v2/pokemon/18/"},{"name":"rattata","url":"https://pokeapi.co/api/v2/pokemon/19/"},{"name":"raticate","url":"https://pokeapi.co/api/v2/pokemon/20/"}]}

Ответ отладки:

    04/17 16:48:46: Launching 'app' on Pixel API 28.
$ adb shell am start -n "williamlopes.cursoandroid.requisicoeshttp.pokemon/williamlopes.cursoandroid.requisicoeshttp.pokemon.activity.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: williamlopes.cursoandroid.requisicoeshttp.pokemon | williamlopes.cursoandroid.requisicoeshttp.pokemon.test
Waiting for application to come online: williamlopes.cursoandroid.requisicoeshttp.pokemon | williamlopes.cursoandroid.requisicoeshttp.pokemon.test
Waiting for application to come online: williamlopes.cursoandroid.requisicoeshttp.pokemon | williamlopes.cursoandroid.requisicoeshttp.pokemon.test
Waiting for application to come online: williamlopes.cursoandroid.requisicoeshttp.pokemon | williamlopes.cursoandroid.requisicoeshttp.pokemon.test
Connecting to williamlopes.cursoandroid.requisicoeshttp.pokemon
Waiting for application to start debug server
Waiting for application to come online: williamlopes.cursoandroid.requisicoeshttp.pokemon | williamlopes.cursoandroid.requisicoeshttp.pokemon.test
Connecting to williamlopes.cursoandroid.requisicoeshttp.pokemon
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/ActivityThread: Application williamlopes.cursoandroid.requisicoeshttp.pokemon is waiting for the debugger on port 8100...
I/System.out: Sending WAIT chunk
W/oeshttp.pokemo: Suspending all threads took: 17.127ms
I/System.out: Debugger has connected
    waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
Connected to the target VM, address: 'localhost:8600', transport: 'socket'
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1398)
W/oeshttp.pokemo: Accessing hidden method Landroid/graphics/drawable/Drawable;->getOpticalInsets()Landroid/graphics/Insets; (light greylist, linking)
W/oeshttp.pokemo: Accessing hidden field Landroid/graphics/Insets;->left:I (light greylist, linking)
    Accessing hidden field Landroid/graphics/Insets;->right:I (light greylist, linking)
    Accessing hidden field Landroid/graphics/Insets;->top:I (light greylist, linking)
    Accessing hidden field Landroid/graphics/Insets;->bottom:I (light greylist, linking)
W/oeshttp.pokemo: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection)
W/oeshttp.pokemo: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)
W/oeshttp.pokemo: Accessing hidden method Landroid/widget/TextView;->getTextDirectionHeuristic()Landroid/text/TextDirectionHeuristic; (light greylist, linking)
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/oeshttp.pokemo: Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setUseSessionTickets(Z)V (light greylist, reflection)
    Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setHostname(Ljava/lang/String;)V (light greylist, reflection)
W/oeshttp.pokemo: Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->getAlpnSelectedProtocol()[B (light greylist, reflection)
    Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setAlpnProtocols([B)V (light greylist, reflection)
W/oeshttp.pokemo: Accessing hidden method Ldalvik/system/CloseGuard;->get()Ldalvik/system/CloseGuard; (light greylist, reflection)
    Accessing hidden method Ldalvik/system/CloseGuard;->open(Ljava/lang/String;)V (light greylist, reflection)
    Accessing hidden method Ldalvik/system/CloseGuard;->warnIfOpen()V (light greylist, reflection)
D/OpenGLRenderer: Skia GL Pipeline
D/HostConnection: HostConnection::get() New Host Connection established 0xdf019f60, tid 11062
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
I/ConfigStore: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
    android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasHDRDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
D/EGL_emulation: eglCreateContext: 0xdde6bae0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xdde6bae0: ver 3 0 (tinfo 0xcba07860)
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xcb74c1e0, tid 11062
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
E/eglCodecCommon: GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1
D/EGL_emulation: eglMakeCurrent: 0xdde6bae0: ver 3 0 (tinfo 0xcba07860)
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 1 2
I/OpenGLRenderer: Davey! duration=875ms; Flags=0, IntendedVsync=26459706342367, Vsync=26459939675691, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=26459956359240, AnimationStart=26459956878140, PerformTraversalsStart=26459957004640, DrawStart=26459998057040, SyncQueued=26460053698040, SyncStart=26460193549240, IssueDrawCommandsStart=26460193764740, SwapBuffers=26460426420740, FrameCompleted=26460721931740, DequeueBufferDuration=311000, QueueBufferDuration=10690000, 

1 Ответ

0 голосов
/ 17 апреля 2020

java.lang.BootstrapMethodError: Exception from call site #4 bootPstrap method

Просмотр https://github.com/square/okhttp/issues/4597, java .lang.BootstrapMethodError: Исключение из метода вызова # 2 bootstrap в CameraX (1.0. 0-alpha06) , вы должны добавить в build.gradle:

android {
    compileOptions {
        targetCompatibility = JavaVersion.VERSION_1_8
        sourceCompatibility = JavaVersion.VERSION_1_8
    }
}

и, возможно (в android ветви)

kotlinOptions {
    jvmTarget = "1.8"
}

Очистить и собрать проект.

...