Consume Rest webservice on Android

Asked

Viewed 969 times

1

I’m trying to consume a Rest webservice on Android. I’ve done all the steps of the tutorial, but keeps falling into onFailure and presenting the error message. I have already checked all the code, but since I am a beginner I could not identify the error. If anyone can help me I am putting the code here. (Note: log does not return errors, only when executed falls into onFailure function.)

Rest

package br.com.imobile2.Venda;

import java.util.List;

import br.com.imobile2.Imovel;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;



interface ImovelREST {

    @GET("ImobWS/webresources/imovel/get/imovel")
    Call<List<Imovel>> getImovel();

    //@GET("Livros/webresources/br.ufs.tep.livros/buscar/{id}")
    //  Call<Imovel> getImovelPorId(@Path("id") String id);

    public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://127.0.0.1:8080/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

}

XML sale

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Venda.VendaFragment"
    android:orientation="vertical">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="65dp">



            <ImageButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/btSearchv"
                android:src="@drawable/iconsearch"
                android:layout_gravity="right|center_vertical" />
        </FrameLayout>



        <ListView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/lvVenda"
            android:choiceMode="singleChoice" />
    </LinearLayout>
</ScrollView>

Venda Java

package br.com.imobile2.Venda;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import br.com.imobile2.Imovel;
import br.com.imobile2.ImovelAdapter;
import br.com.imobile2.MainActivity;
import br.com.imobile2.R;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class VendaFragment extends Fragment {

    ProgressDialog dialog;

    public VendaFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_venda, container, false);


        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        final ListView lvVenda = (ListView) getView().findViewById(R.id.lvVenda);
        ImovelREST imovelREST = ImovelREST.retrofit.create(ImovelREST.class);
        dialog = new ProgressDialog(getContext());
        dialog.setMessage("Carregando...");
        dialog.setCancelable(false);
        dialog.show();
        final Call<List<Imovel>> call = imovelREST.getImovel();
        call.enqueue(new Callback<List<Imovel>>() {
            @Override
            public void onResponse(Call<List<Imovel>> call, Response<List<Imovel>> response) {
                if (dialog.isShowing())
                    dialog.dismiss();
                final List<Imovel> listImoveis = response.body();
                if (listImoveis != null) {
                    ImovelAdapter adapter = new ImovelAdapter(getActivity(), listImoveis);
                    lvVenda.setAdapter(adapter);
                    lvVenda.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                            Intent intent = new Intent(getContext(),VendaDetailsFragment.class);
                            intent.putExtra("ID", listImoveis.get(i).getId());
                            startActivity(intent);
                        }
                    });
                }
            }
            @Override
            public void onFailure(Call<List<Imovel>> call, Throwable t) {
                if (dialog.isShowing())
                    dialog.dismiss();
                Toast.makeText(getActivity(), "Problema de acesso", Toast.LENGTH_LONG).show();
            }
        });

    }


}

Webservice (is working and active while testing the application)

package ws;

import com.google.gson.Gson;
import dao.ImovelDAO;
import java.sql.SQLException;
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
import modelo.Imovel;


@Path("imovel")
public class ImovelWS {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of ImobiWS
     */
    public ImovelWS() {
    }

    /**
     * Retrieves representation of an instance of ws.ImobiWS
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("application/json")
    public String getJson() {
        //TODO return proper representation object
        throw new UnsupportedOperationException();
    }

    @GET
    @Produces("application/json")
    @Path("get/imovel")
    public String getImovel() throws ClassNotFoundException, SQLException{
        Gson g = new Gson();
        ImovelDAO idao = new ImovelDAO();
        List<Imovel> imovel = idao.getImovel();
        return g.toJson(imovel);

    }

}
  • Internet permission on the manifest, you’ve seen this?

  • You’re already with permission.

1 answer

-1

When you fall in onFailure, you can see what the error is, this way:

@Override
public void onFailure(Call<List<Imovel>> call, Throwable t) {
   if (dialog.isShowing())
      dialog.dismiss();

    String message = t.getMessage();
    Log.d("failure", message);

}
  • that wouldn’t be the answer to his problem, it would be more of a comment

  • I agree, it should be a comment.

  • How do I put this code in the comment? Explain it to me

  • The war for reputation is spoiling Sopt more and more

  • 1

    Thank you, Leonardo. I checked the following error: 06-02 19:07:45.021 4037-4037/br.com.imobile2 D/Failure: failed to connect to /10.0.2.2 (port 8080) after 10000ms ----- I will check if there is something wrong in the connection with the database or the webservice.

  • There must be some problem related to the connection of the API, take a look if it is not the https://

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.