Skip to main content
3 de 6
adicionou 250 caracteres ao conteúdo
Carlos Rocha
  • 4mil
  • 2
  • 23
  • 65

Retrofit = Manipulando o response

Bom, estou pedindo mais essa ajuda aos amigos poi realmente, não estou conseguindo entende a dinâmica.

Seguindo tutoriais e explicações aqui do fórum estou TENTANDO usar o Retrofit mas não está dando certo.

Tenho o seguinte JSON abaixo,

{
  "clientes":
     [
        {"idClientesT":"1","tipo":"s","nome":"Carlos"},
        {"idClientesT":"2","tipo":"s","nome":"Rogério"}
     ]
} 

Que recebo quando acesso a URL abaixo,

http://hotplateprensas.com.br/ws/clientest.php

Estou usando assim:

Interface:

package carcleo.com.radiosingular.classes;

import java.util.List;

import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface ClientesI {
    @GET("clientest.php")
    Call<List<Clientes>> listClientes();
}

Activity:

package carcleo.com.radiosingular;

import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.List;

import carcleo.com.radiosingular.classes.Clientes;
import carcleo.com.radiosingular.classes.ClientesI;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class retrofit extends AppCompatActivity {

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

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://www.hotplateprensas.com.br/ws/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ClientesI service = retrofit.create(ClientesI.class);


        service.listClientes().enqueue(new Callback<List<Clientes>>() {
            @Override public void onResponse(Call<List<Clientes>> call, Response<List<Clientes>> response) {

                int code = response.code();
                if (code == 200) {
                    for (Clientes cli : response.body()) {
                        Toast.makeText(getBaseContext(), "Id do cliente: " + cli.getIdClientesT(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getBaseContext(), "Tipo do cliente: " + cli.getTipo(), Toast.LENGTH_LONG).show();
                        Toast.makeText(getBaseContext(), "Nome do cliente: " + cli.getNome(), Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getBaseContext(), "Falha: " + String.valueOf(code), Toast.LENGTH_LONG).show();
                }

            }

            @Override public void onFailure(Call<List<Clientes>> call, Throwable t) {
                Log.v("Errado: ", t.toString());
                Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

   }

}

A classe de Clientes:

package carcleo.com.radiosingular.classes;

public class Clientes {
    private int idClientesT;
    private String tipo;
    private String nome;

    public Clientes(int idClientesT, String tipo, String nome) {
        this.idClientesT = idClientesT;
        this.tipo = tipo;
        this.nome = nome;
    }

    public int getIdClientesT() {
        return idClientesT;
    }

    public String getTipo() {
        return tipo;
    }

    public String getNome() {
        return nome;
    }
}

O objetivo é percorrer o array JSON obtido pelo acesso ao webservice e retornar uma lista de objetos da classe Clientes.

O erro só ocorre em tempo de execução.

Mas para mim o erro é de codificação mesmo. De lógica.

Obs.: Eu NÃO consigo receber

code == 200

Está entrando direto nesse bloco:

@Override public void onFailure(Call<List<Clientes>> call, Throwable t) {
   Log.v("Errado: ", t.toString());
   Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}

Mas não consigo manipular o retorno (response)

Erro no console RUN:

12/21 08:32:21: Launching app
$ adb install-multiple -r -t -p carcleo.com.radiosingular D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_8.apk 
Split APKs installed in 1 s 51 ms
$ adb shell am start -n "carcleo.com.radiosingular/carcleo.com.radiosingular.login" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 16355 on device motorola-moto_g_play-0027377835
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
I/art: Rejecting re-init on previously-failed class java.lang.Class<android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper>: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener;
        at void android.support.v4.view.ViewCompat.setBackground(android.view.View, android.graphics.drawable.Drawable) (ViewCompat.java:2341)
        at void android.support.v7.widget.ActionBarContainer.<init>(android.content.Context, android.util.AttributeSet) (ActionBarContainer.java:62)
        at java.lang.Object java.lang.reflect.Constructor.newInstance0!(java.lang.Object[]) (Constructor.java:-2)
        at java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[]) (Constructor.java:430)
        at android.view.View android.view.LayoutInflater.createView(java.lang.String, java.lang.String, android.util.AttributeSet) (LayoutInflater.java:645)
        at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:787)
        at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet) (LayoutInflater.java:727)
        at void android.view.LayoutInflater.rInflate(org.xmlpull.v1.XmlPullParser, android.view.View, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:858)
        at void android.view.LayoutInflater.rInflateChildren(org.xmlpull.v1.XmlPullParser, android.view.View, android.util.AttributeSet, boolean) (LayoutInflater.java:821)
        at android.view.View android.view.LayoutInflater.inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean) (LayoutInflater.java:518)
        at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean) (LayoutInflater.java:426)
        at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup) (LayoutInflater.java:377)
        at android.view.ViewGroup android.support.v7.app.AppCompatDelegateImpl.createSubDecor() (AppCompatDelegateImpl.java:607)
        at void android.support.v7.app.AppCompatDelegateImpl.ensureSubDecor() (AppCompatDelegateImpl.java:518)
        at void android.support.v7.app.AppCompatDelegateImpl.setContentView(int) (AppCompatDelegateImpl.java:466)
        at void android.support.v7.app.AppCompatActivity.setContentView(int) (AppCompatActivity.java:140)
        at void carcleo.com.radiosingular.retrofit.onCreate(android.os.Bundle) (retrofit.java:27)
        at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:6687)
        at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1140)
        at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2631)
        at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:2743)
        at void android.app.ActivityThread.-wrap12(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
        at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1490)
        at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102)
        at void android.os.Looper.loop() (Looper.java:154)
        at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6165)
        at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2)
        at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:888)
        at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:778)
    Caused by: java.lang.ClassNotFoundException: Didn't find class "android.view.View$OnUnhandledKeyEventListener" on path: DexPathList[[zip file "/data/app/carcleo.com.radiosingular-2/base.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_dependencies_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_0_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_1_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_2_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_3_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_4_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_5_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_6_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_7_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_8_apk.apk", zip file "/data/app/carcleo.com.radiosingular-2/split_lib_slice_9_
        at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:56)
        at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:380)
        at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:312)
        at void android.support.v4.view.ViewCompat.setBackground(android.view.View, android.graphics.drawable.Drawable) (ViewCompat.java:2341)
        at void android.support.v7.widget.ActionBarContainer.<init>(android.content.Context, android.util.AttributeSet) (ActionBarContainer.java:62)
        at java.lang.Object java.lang.reflect.Constructor.newInstance0!(java.lang.Object[]) (Constructor.java:-2)
        at java.lang.Object java.lang.reflect.Constructor.newInstance(java.lang.Object[]) (Constructor.java:430)
        at android.view.View android.view.LayoutInflater.createView(java.lang.String, java.lang.String, android.util.AttributeSet) (LayoutInflater.java:645)
        at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:787)
        at android.view.View android.view.LayoutInflater.createViewFromTag(android.view.View, java.lang.String, android.content.Context, android.util.AttributeSet) (LayoutInflater.java:727)
        at void android.view.LayoutInflater.rInflate(org.xmlpull.v1.XmlPullParser, android.view.View, android.content.Context, android.util.AttributeSet, boolean) (LayoutInflater.java:858)
        at void android.view.LayoutInflater.rInflateChildren(org.xmlpull.v1.XmlPullParser, android.view.View, android.util.AttributeSet, boolean) (LayoutInflater.java:821)
        at android.view.View android.view.LayoutInflater.inflate(org.xmlpull.v1.XmlPullParser, android.view.ViewGroup, boolean) (LayoutInflater.java:518)
        at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup, boolean) (LayoutInflater.java:426)
        at android.view.View android.view.LayoutInflater.inflate(int, android.view.ViewGroup) (LayoutInflater.java:377)
        at android.view.ViewGroup android.support.v7.app.AppCompatDelegateImpl.createSubDecor() (AppCompatDelegateImpl.java:607)
        at void android.support.v7.app.AppCompatDelegateImpl.ensureSubDecor() (AppCompatDelegateImpl.java:518)
        at void android.support.v7.app.AppCompatDelegateImpl.setContentView(int) (AppCompatDelegateImpl.java:466)
        at void android.support.v7.app.AppCompatActivity.setContentView(int) (AppCompatActivity.java:140)
        at void carcleo.com.radiosingular.retrofit.onCreate(android.os.Bundle) (retrofit.java:27)
        at void android.app.Activity.performCreate(android.os.Bundle) (Activity.java:6687)
        at void android.app.Instrumentation.callActivityOnCreate(android.app.Activity, android.os.Bundle) (Instrumentation.java:1140)
        at android.app.Activity android.app.ActivityThread.performLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent) (ActivityThread.java:2631)
        at void android.app.ActivityThread.handleLaunchActivity(android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:2743)
        at void android.app.ActivityThread.-wrap12(android.app.ActivityThread, android.app.ActivityThread$ActivityClientRecord, android.content.Intent, java.lang.String) (ActivityThread.java:-1)
        at void android.app.ActivityThread$H.handleMessage(android.os.Message) (ActivityThread.java:1490)
        at void android.os.Handler.dispatchMessage(android.os.Message) (Handler.java:102)
        at void android.os.Looper.loop() (Looper.java:154)
        at void android.app.ActivityThread.main(java.lang.String[]) (ActivityThread.java:6165)
        at java.lang.Object java.lang.reflect.Method.invoke!(java.lang.Object, java.lang.Object[]) (Method.java:-2)
        at void com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run() (ZygoteInit.java:888)
        at void com.android.internal.os.ZygoteInit.main(java.lang.String[]) (ZygoteInit.java:778)
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/ViewConfigCompat: Could not find method getScaledScrollFactor() on ViewConfiguration
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/OpenGLRenderer: endAllActiveAnimators on 0x9a465680 (RippleDrawable) with handle 0x9a5fd370
V/Errado:: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Alguém pode me ajuda?

Carlos Rocha
  • 4mil
  • 2
  • 23
  • 65