Jump to content
carcleo

Tratar JSON no Android Studio

Recommended Posts

carcleo

Em uma tentativa (sem êxito) de ler uma string em formato JSON fiz assim:

    package carcleo.com.radiosingular;
    
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import carcleo.com.radiosingular.classes.JsonClass;
    
    public class form extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.form);
    
            String url = "http://hotplateprensas.com.br/ws/clientest.php";
            JSONObject clientesLista = null;
            JsonClass json = new JsonClass();
            clientesLista = json.getJSONFromUrl(url);
    
            clientes(clientesLista);
    
        }
    
        public void clientes(JSONObject jsonCli) {
    
            try {
    
                JSONArray arrayPlanetas = jsonCli.getJSONArray("clientes");
    
                for (int i = 0; i < arrayPlanetas.length(); i++) {
    
                    JSONObject cliente = arrayPlanetas.getJSONObject(i);
    
                    Log.d("idClientesT", cliente.getString("idClientesT"));
                    Log.d("tipo", cliente.getString("tipo"));
                    Log.d("nome", cliente.getString("nome"));
    
                }
    
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
    }


    
A URL me retorna:

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

e a classe JsonClass

    package carcleo.com.radiosingular.classes;
    
    import android.util.Log;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    
    import cz.msebera.android.httpclient.HttpEntity;
    import cz.msebera.android.httpclient.HttpResponse;
    import cz.msebera.android.httpclient.client.ClientProtocolException;
    import cz.msebera.android.httpclient.client.methods.HttpPost;
    import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
    
    public class JsonClass {
    
        InputStream input = null;
        JSONObject jObect = null;
        String json = "";
    
        //Recebe sua url
        public JSONObject getJSONFromUrl(String url) {
    
            //HTTP request
            try {
                // default HttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                input = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        input, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                input.close();
                json = sb.toString();
                Log.i("JRF", json);
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // Transforma a String de resposta em um JSonObject
            try {
                jObect = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // retorna o objeto
            return jObect;
    
        }
    }

Isso me dá o seguinte erro:

    12/14 14:25:05: 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 53 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..Connected to process 13274 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/System: ClassLoader referenced unknown path: /data/app/carcleo.com.radiosingular-2/lib/arm
    I/InstantRun: starting instant run server: is main process
    I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8916_32_LA.BR.1.2.9_RB1__release_AU (I750f7f2fa6)
        OpenGL ES Shader Compiler Version: XE031.09.00.03
        Build Date: 02/18/17 Sat
        Local Branch: 
        Remote Branch: quic/LA.BR.1.2.9_rb1.12
        Local Patches: NONE
        Reconstruct Branch: NOTHING
    I/OpenGLRenderer: Initialized EGL, version 1.4
    D/OpenGLRenderer: Swap behavior 1
    W/Adreno-ES20: <get_gpu_clk:229>: open failed: errno 13
    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;
    I/art:     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.form.onCreate(android.os.Bundle) (form.java:18)
            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.form.onCreate(android.os.Bundle) (form.java:18)
            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
    D/AndroidRuntime: Shutting down VM
    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: carcleo.com.radiosingular, PID: 13274
        java.lang.RuntimeException: Unable to start activity ComponentInfo{carcleo.com.radiosingular/carcleo.com.radiosingular.form}: android.os.NetworkOnMainThreadException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2678)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2743)
            at android.app.ActivityThread.-wrap12(ActivityThread.java)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:154)
            at android.app.ActivityThread.main(ActivityThread.java:6165)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
         Caused by: android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1317)
            at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
            at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
            at java.net.InetAddress.getAllByName(InetAddress.java:752)
            at cz.msebera.android.httpclient.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44)
            at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:259)
            at cz.msebera.android.httpclient.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
            at cz.msebera.android.httpclient.impl.conn.ManagedClientConnectionImpl.open(ManagedClientConnectionImpl.java:304)
            at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:611)
            at cz.msebera.android.httpclient.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:446)
            at cz.msebera.android.httpclient.impl.client.AbstractHttpClient.doExecute(AbstractHttpClient.java:860)
            at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
            at cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
            at carcleo.com.radiosingular.classes.JsonClass.getJSONFromUrl(JsonClass.java:35)
            at carcleo.com.radiosingular.form.onCreate(form.java:23)
            at android.app.Activity.performCreate(Activity.java:6687)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2631)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2743) 
            at android.app.ActivityThread.-wrap12(ActivityThread.java) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1490) 
            at android.os.Handler.dispatchMessage(Handler.java:102) 
            at android.os.Looper.loop(Looper.java:154) 
            at android.app.ActivityThread.main(ActivityThread.java:6165) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778) 

 

Share this post


Link to post
Share on other sites
carcleo

Descobri que adicionando o código abaixo ao oncreate, o sistema funciona corretamente.

if (android.os.Build.VERSION.SDK_INT > 9){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

Mas não entendi muito bem.

Pelo código, a impressão que tenho é a de que só funcionará para Dispositivos com versões do Android acima de 9.0?

Está certo isso?

E para versões anteriores? O que fazer?

Obs: Se eu não colocar esse bloco de código dá o seguinte erro:

D/NetworkSecurityConfig: No Network Security Config specified, using platform default

 

Edited by carcleo

Share this post


Link to post
Share on other sites
iron

Bem, antes de mais, pedidos http na main thread do android não são recomendados. Como o pedido pode ser demorado, a plataforma, pode "matar" a aplicação.
 

Em vez disso, recomendo usares o retrofit (existem outras)
http://www.vogella.com/tutorials/Retrofit/article.html
 

Essa biblioteca já se preocupa em realizar os pedidos asincronos, poupando bastante trabalho nesse ponto.

Quanto à tua dúvida, esse if só irá correr se a versão do sdk for superior à versão 9.
Mas ao usares o retrofit, já não deves ter problemas.


Cumprimentos,
iron

Share this post


Link to post
Share on other sites
carcleo

Então, o que eu fiz?

Seguindo o teu concelho, para testes, criei:

Uma Activity que chamei de retrofit e um BUTTON nela

package carcleo.com.radiosingular;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

public class retrofit extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.retrofit);
        Button btnRf = (Button) findViewById(R.id.btnRf);
        btnRf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClientesI clientes = ClientesI.retrofit.create(ClientesI.class);
                final Call<Clientes> call = clientes.getIdClientesT("");
                call.enqueue(new Callback<Clientes>() {
                    @Override
                    public void onResponse(Call<Clientes> call, Response<Clientes> response) {
                        int code = response.code();
                        if (code == 200) {
                            Clientes cliente = response.body();
                            Toast.makeText(getBaseContext(), "Id do cliente: " + cliente.getIdClientesT(), Toast.LENGTH_LONG).show();
                            Toast.makeText(getBaseContext(), "Tipo do cliente: " + cliente.getTipo(), Toast.LENGTH_LONG).show();
                            Toast.makeText(getBaseContext(), "Nome do cliente: " + cliente.getNome(), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getBaseContext(), "Falha: " + String.valueOf(code), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Clientes> call, Throwable t) {
                        Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                    }

                });
            }
        }
        );
    }

}

Uma Interface ClientesI

package carcleo.com.radiosingular.classes;

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

public interface ClientesI {
    @GET()

    Call<Clientes> getIdClientesT(@Path("") String cliente);
    // Essa url já entrega uma string em formato JSON, a mesma do incio do post
    public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://hotplateprensas.com.br/ws/clientest.php/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

}

Acontece que quando chega na linha

final Call<Clientes> call = clientes.getIdClientesT("");

está dando erro no console.


E/AndroidRuntime: FATAL EXCEPTION: main
    Process: carcleo.com.radiosingular, PID: 20298
    java.lang.IllegalArgumentException: @Path can only be used with relative url on @GET (parameter #1)
        for method ClientesI.getIdClientesT
        at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:720)
        at retrofit2.ServiceMethod$Builder.methodError(ServiceMethod.java:711)
        at retrofit2.ServiceMethod$Builder.parameterError(ServiceMethod.java:729)
        at retrofit2.ServiceMethod$Builder.parseParameterAnnotation(ServiceMethod.java:390)
        at retrofit2.ServiceMethod$Builder.parseParameter(ServiceMethod.java:333)
        at retrofit2.ServiceMethod$Builder.build(ServiceMethod.java:202)
        at retrofit2.Retrofit.loadServiceMethod(Retrofit.java:166)
        at retrofit2.Retrofit$1.invoke(Retrofit.java:145)
        at java.lang.reflect.Proxy.invoke(Proxy.java:813)
        at $Proxy0.getIdClientesT(Unknown Source)
        at carcleo.com.radiosingular.retrofit$1.onClick(retrofit.java:27)
        at android.view.View.performClick(View.java:5640)
        at android.view.View$PerformClick.run(View.java:22455)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6165)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)

no método OnResponse, é feita uma referência Call<Clientes>

 public void onResponse(Call<Clientes> call, Response<Clientes> response) {

 E parece que é feita uma busca e nada é retornado. Pois busca por um parâmetro na url que não existe. 

Onde estou errando?

Edited by carcleo

Share this post


Link to post
Share on other sites
iron

Experimenta isto,

Aqui vais alterar para isto :

public interface ClientesI {
  

    @GET("clientest.php")
    Call<Clientes> getIdClientesT();
    // Essa url já entrega uma string em formato JSON, a mesma do incio do post
    public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://hotplateprensas.com.br/ws/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

}

 

 

package carcleo.com.radiosingular;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

public class retrofit extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.retrofit);
        Button btnRf = (Button) findViewById(R.id.btnRf);
        btnRf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClientesI clientes = ClientesI.retrofit.create(ClientesI.class);
                final Call<Clientes> call = clientes.getIdClientesT();
                call.enqueue(new Callback<Clientes>() {
                    @Override
                    public void onResponse(Call<Clientes> call, Response<Clientes> response) {
                        int code = response.code();
                        if (code == 200) {
                            Clientes cliente = response.body();
                            Toast.makeText(getBaseContext(), "Id do cliente: " + cliente.getIdClientesT(), Toast.LENGTH_LONG).show();
                            Toast.makeText(getBaseContext(), "Tipo do cliente: " + cliente.getTipo(), Toast.LENGTH_LONG).show();
                            Toast.makeText(getBaseContext(), "Nome do cliente: " + cliente.getNome(), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getBaseContext(), "Falha: " + String.valueOf(code), Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Clientes> call, Throwable t) {
                        Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                    }

                });
            }
        }
        );
    }

}

 


Cumprimentos,
iron

Share this post


Link to post
Share on other sites
carcleo

Também não funcionou. Mas seguindo o raciocínio cheguei em:

package carcleo.com.radiosingular.classes;

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

public interface ClientesI {

    @GET("{url}")

    Call<Clientes> getIdClientesT(@Path("url") String url);

    static final String url = "clientest.php";

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

}

 e,

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.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;

public class retrofit extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.retrofit);
        Button btnRf = (Button) findViewById(R.id.btnRf);
        btnRf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
             ClientesI clientes = ClientesI.retrofit.create(ClientesI.class);
             final Call<List<Clientes>> call = clientes.getIdClientesT(clientes.url);
             call.enqueue(new Callback<List<Clientes>>() {
                 @RequiresApi(api = Build.VERSION_CODES.N)
                 @Override
                 public void onResponse(Call<List<Clientes>> call, Response<List<Clientes>> response) {
                     int code = response.code();
                     if (code == 200) {
                         List<Clientes> cliente = response.body();
                         for (Clientes cli : cliente) {
                             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) {
                     Toast.makeText(getBaseContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                 }

             });
            }
            }
        );
    }

}

Desta forma entra no bloco do 

if (code == 200) {

Mas aí estou com outro problema;

Meu json que chega do site é no formato:

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

E tem  mais de 1 retorno.

Porém não estou conseguindo tratar o onResponse para mais que 1 retorno.

Pode me ajudar?

Em tempo:

A mensagem de erro do console é:


12/17 20:37:47: Launching app
$ adb install-multiple -r -t D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_6.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_1.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\dep\dependencies.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_5.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_7.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_8.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_9.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_4.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_3.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_2.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\split-apk\debug\slices\slice_0.apk D:\Trabalhos\AndroidStudio\RadioSingular\app\build\intermediates\instant-run-apk\debug\app-debug.apk 
Split APKs installed in 2 s 642 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 25557 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.
I/art: Late-enabling -Xcheck:jni
W/System: ClassLoader referenced unknown path: /data/app/carcleo.com.radiosingular-2/lib/arm
I/InstantRun: starting instant run server: is main process
I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8916_32_LA.BR.1.2.9_RB1__release_AU (I750f7f2fa6)
    OpenGL ES Shader Compiler Version: XE031.09.00.03
    Build Date: 02/18/17 Sat
    Local Branch: 
    Remote Branch: quic/LA.BR.1.2.9_rb1.12
    Local Patches: NONE
    Reconstruct Branch: NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/Adreno-ES20: <get_gpu_clk:229>: open failed: errno 13
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:24)
        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:24)
        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)
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 0xafb5d300 (RippleDrawable) with handle 0x99c7fe50
D/NetworkSecurityConfig: No Network Security Config specified, using platform default

A mensagem de erro que aparece no dispositivo é:

Expected BEGIN_OBJECT but was STRING at line 1 column 1

 

Edited by carcleo

Share this post


Link to post
Share on other sites
iron



Vamos entender o JSON:

 

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

 

O JSON é um objecto que contém uma propriedade do tipo array de objectos (vamos chamar assim por enquanto) com o nome clientes.
Esse array de "objectos" é um objecto que tem as propriedades:

   - idClientesT
   - tipo
   - nome

Todas estas propriedades são do tipo String.

Sabendo isto, é necessário criar um modelo, que contenha as propriedade que vêm no JSON, para que a biblioteca Gson possa mapear.

Depois de criares isso, se não funcionar, coloca aqui o teu modelo também.


Cumprimentos,
iron

Share this post


Link to post
Share on other sites
carcleo

Ainda assim não funcionou.

 

Vamos por partes:

Lá no Webservice, minha classe PHP que gera o JSON:

<?php

  header('Content-Type: application/json');
  ini_set("display_errors",true);
  ini_set("display_startup_erros",1);
  error_reporting(E_ALL && E_NOTICE);
  error_reporting( E_ALL | E_STRICT ); // PHP 5.3
  error_reporting( E_ALL ); // Todas as outras versões 

  require_once "../_controlls/_conexao/Conexao.php";
  
  $conection = new Conexao();
  $conexao = $conection->abreConexao();

  function pesquisaClientesT($conexao) {
        
         $clientes = ""; 
         
         $string = "SELECT 
                      idClientesT,
                      tipo,  
                      nome
                    FROM clientest";
      
         $registros = $conexao->query($string);
                   
         $quantasLinhas = $registros->num_rows;
      
         if ($quantasLinhas > 0) {        
        
             $clientes .= "{\"clientes\":[";                 
             
             while (
                 list ( 
                        $idCliente, 
                        $tipo,  
                        $nome            
                 ) = $registros->fetch_row() ){
                       $cliente = array(
                         "idClientesT"=>$idCliente,
                         "tipo"=>$tipo,
                         "nome"=>$nome
                       );
                 
                       $clientes .= json_encode($cliente, JSON_UNESCAPED_UNICODE).",";
                    }
             
             $clientes = substr($clientes,0, strlen($clientes)-1);
             $clientes .= "]}"; 
         }
                 
          return  $clientes;
         
     }

     $todos = pesquisaClientesT($conexao);
  
     echo $todos;


?>

Gera uma saída assim:

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

Classe Clientes no Android (App)
 

package carcleo.com.radiosingular.classes;

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

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

    public String getIdClientesT() {
        return idClientesT;
    }

    public String getTipo() {
        return tipo;
    }

    public String getNome() {
        return nome;
    }
}

A execução está saindo no bloco de falha com o erro abaixo na tela do Android.

Expected BEGIN_OBJECT but was STRING at line 1 column 2 path$

Será possível ser problema na conexão com a internet?

No primeiro post dessa pergunta, la em cima, eu usei jsonArray e deu certo. Enfim, não usei Retrofit.

Mas foi necessário o uso de 

if (android.os.Build.VERSION.SDK_INT > 9){
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

Não seria esse o caso? Se sim, aonde coloco ele na nova forma usando Retrofit?

Obs..: já tem permissão de internet no AndroidManifest

Edited by carcleo

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.