Akshay Sood
Akshay Sood

Reputation: 150

Android Retrofit failure()

Hello I am trying to make an app that will get the lat long from web url

http://akshay.site90.net/getLats.php?username=rakesh

And result will be in the form

{"lat":"30.1328064900","longitude":"77.2865304300"}

I am doing this using Android Retrofit.. But When I am opening the app the failure() of retrofit is called everytime but not the success() I dont know what is going wrong.. it should call onSucces()

interface  api.java
package com.example.akshay.parentapp;

    import retrofit.http.GET;

    /**
     * Created by Akshay on 9/8/2015.
     */
    public interface api {
        @GET("/getLats.php?username=rakesh")
        public void getData( retrofit.Callback<getGSONData> response);
    }

getGSONData.java

package com.example.akshay.parentapp;

import android.util.Log;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by Akshay on 9/8/2015.
 */
public class getGSONData {

    @SerializedName("lat")
    @Expose
    public String lat;

    @SerializedName("longitude")
    @Expose
    public String longitude;

    public void getlat(String lat) {
        this.lat = lat;
    }

    public Double setLat() {
        Log.e("====LAT", lat);
        return Double.parseDouble(lat);
    }

    public void getlongitude(String longitude) {
        this.longitude = longitude;
    }

    public Double setLong() {
        Log.e("====LONG", longitude);
        return Double.parseDouble(longitude);
    }

}

Map.java

package com.example.akshay.parentapp;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.PolylineOptions;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by Akshay on 8/31/2015.
 */
public class Map extends FragmentActivity {
    public final String URL = "http://akshay.site90.net";
    LatLng prev = null;
    LatLng current = null;
    int flag = 0;
    GoogleMap googleMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
      LocationManager  locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                Log.e("OnLocationChanged" , "===========0");
                RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(URL).build();
               api api = restAdapter.create(api.class);
                api.getData( new Callback<getGSONData>() {
                    @Override
                    public void success(getGSONData getGSONData, Response response) {
                        Double LAT = getGSONData.setLat();
                        Double LONG = getGSONData.setLong();
                        current =  new LatLng(LAT , LONG);

                       Log.e("===LAT" , String.valueOf(LAT));
                        Log.e("===LONG" , String.valueOf(LONG));
                         if (flag == 0 & LAT!=null & LONG != null)
                         {
                             prev = current;
                             flag = 1;
                         }
                        CameraUpdate cm = CameraUpdateFactory.newLatLngZoom(current, 18);

                        PolylineOptions polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED).add(prev,current).width(20).visible(true);
                        googleMap.addPolyline(polylineOptions);
                        googleMap.animateCamera(cm);
                        prev = current;
                        current = null;


                    }

                    @Override
                    public void failure(RetrofitError error) {
Log.e("====" , "Something gone wrong");
                    }
                });

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        });


    }
}

Upvotes: 1

Views: 14131

Answers (6)

Raed
Raed

Reputation: 904

Use or call Call<ResponseBody> instead of the object that you have created to show all the JSON string and make sure that everything works fine before you check your code because that may not be showing in Postman or online sites.

Upvotes: 0

VIKAS SHARMA
VIKAS SHARMA

Reputation: 84

print

t.getCause()

in onFailed and let me know to help you

Upvotes: 4

Thiru
Thiru

Reputation: 1

Your setter and getter methods wrong, check it out. it should be like

public void setlat(String lat) {
    this.lat = lat;
}

public Double getlat() {
    Log.e("====LAT", lat);
    return Double.parseDouble(lat);
}

Try to use addConverterFactory(GsonConverterFactory.create()) in retrofit so that it values can be directly mapped to your POJO class.

private static Retrofit.Builder builder =
new Retrofit.Builder()
        .baseUrl(API_BASE_URL)
        .addConverterFactory(GsonConverterFactory.create());

Upvotes: 0

Faruk
Faruk

Reputation: 5831

in retrofit2 u can do it easily like this :

  1. in your interface, Api.class :

    public interface Api {  
      @GET("/getLats.php")
      Call<List<getGSONData>> getData(@Query("username") String username);
    }
    
  2. in your Service class, let say ServiceGenerator.class :

    public class ServiceGenerator {
    
      public static final String API_BASE_URL = "http://your.api-base.url";
    
      private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    
      private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create());
    
      public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
      }
    }
    
  3. And in your activity, to calling asynchronously use enqueue :

     //prepare variable to contain result
     List<getGSONData> resultList;
    
     //create service
     Api myApi = ServiceGenerator.createService(Api.class);
    
     //instantiate the call and set parameters
     Call<List<getGSONData>> call = myApi.getData("rakesh");
    
     //enqueue for doing asynchronous, if you want to synchronous use 
     //execute().body() with try catch:
     //
     // resultList = call.execute().body();
    
     call.enqueue(new Callback<List<getGSONData>>() {
       @Override
       public void onResponse(Response<List<getGSONData>> response, 
              Retrofit retrofit) 
       {
             // handle success 
             //code 200 ..300
             if(response.isSuccesful())
               resultList = response.body();
       }
    
       @Override
       public void onFailure(Throwable t) 
       {
          // handle failure
       }
     });
    

Upvotes: 0

Akshay Sood
Akshay Sood

Reputation: 150

Thanks All For your support

The Web URL Was returning

{"lat":"30.1329624300","longitude":"77.2864860400"}
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->

So I cleared the In Activity Adds from my free hosting 000.webhost.com And that works

Upvotes: 0

Moonbloom
Moonbloom

Reputation: 7918

I can see a few things that could cause some issues:

1) Your web API returns the data as 'text/html', not as 'application/json', so Retrofit might not be able to read it correctly.

2) Try and add a '/' at the end of your base URL, so it looks like this:

public final String URL = "http://akshay.site90.net/";

3) Your setter/getters are wrong in the 'getGSONData' class. Your getters are setting the values and your setters are getting the values.

Upvotes: 2

Related Questions