1

Quiero enviar y recibir datos por Retrofit, pero solo un dato en específico, solo una letra o un número para realizar una acción a partir de eso..

private void EnviarDatos(String dato) {
        ConnectivityManager conectivity=(ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifi = conectivity.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo mobile = conectivity.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if(String.valueOf(wifi.getState()).equals ("CONNECTED")||(String.valueOf(mobile.getState()).equals("CONNECTED"))){
            //Toast.makeText(getBaseContext(), "Si hay conexion disponible", Toast.LENGTH_SHORT).show();
            if(wifi.isConnected()||(mobile.isConnected())) {

                Call<Receiver> dat = SmartApiAdapter.getApiService().Receiver(1);
                dat.enqueue(new Callback<Receiver>() {
                    @Override
                    public void onResponse(Call<Receiver> call, Response<Receiver> response) {
                        if(response.isSuccessful()) {
                            Receiver receiver = response.body();
                            String ds = receiver.getDato();
                            puente.obtainMessage(Integer.parseInt(ds));
                            Toast.makeText(getBaseContext(), "Alerta enviada, Mantenga la calma", Toast.LENGTH_LONG).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Receiver> call, Throwable t) {
                        Toast.makeText(getBaseContext(), "Mensaje no enviado", Toast.LENGTH_LONG).show();
                    }
                });
            }
        }
        else
            Toast.makeText(getBaseContext(), "Sin conexion", Toast.LENGTH_LONG).show();
    }

Aquí intento recibir un dato de Retrofit para luego mostrarlo en mi método handler()

private Handler puente = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            BT2.setText((Integer) msg.obj);
            BT2.setTextColor(BT2.getContext().getResources().getColor(R.color.ROJO));
            //Mostramos el mensage recibido del servidor en pantalla
            //Toast.makeText(getApplicationContext(), (String) msg.obj,
                    //Toast.LENGTH_LONG).show();
        }
    };

Y en el caso del envío no entiendo bien el procedimiento para subir por ejemplo la letra "A" al servidor.

2
  • 1
    Hola David, te damos la bienvenida a Stack Overflow en español (completa el recorrido de bienvenida para aprender más sobre el sitio y ganar tu primera medalla). Deberías editar la pregunta para añadir algo más de información (¿qué resultado obtienes? ¿recibes algún error?) y cambiar el texto en mayúsculas (que es más difícil de leer y en Internet se considera equivalente a gritos). Lee Cómo preguntar para más información. Un saludo.
    – Alvaro Montoro
    el 5 jun. 2018 a las 14:42
  • gracias por la corrección el 5 jun. 2018 a las 14:58

1 respuesta 1

2

Primero que nada no me entero si haras una solicitud POST o GET, ya que tienes una clase Receiver pero solo enviaras y reciviras una letra.Creo que para este caso calza mejor GET. Para la solicitud necesitas una clase y una interfase he aqui un ejemplo:

Clase solicitud retrofit:

public class webapi {
private static  final String urlBase="http://urlejemplo/servicio/api/";

    final OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();

    public Retrofit retrofitPeticion(){
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(urlBase)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();
        return retrofit;
    }
}

Interfase:

public interface interfase {

    @GET("metodoapi")
    Call<String> metodoapi(@Query("letra") String letra);

}

Llamada:

private void llamada(String letra) {
        interfase service = ws.retrofitPeticion().create(interfase.class);
        Call<String> RespuestaCall = service.metodoapi(letra);
        RespuestaCall.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                  Log.i("recibido ",response.body().toString());
                } 
            }

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

            }
        });
    }

Si me he equivocado en algo, me avisan please ;)

1
  • intentare de esa manera, lo que sucede es que no habia visto una forma de enviar o recibir una sola letra, intento y en caso de que haya un error respondere por esta misma pregunta. el 7 jun. 2018 a las 15:22

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.