0

I have problem with parsing Json in Retrofit. My URL: http://192.168.0.102:8000/api/get_services?keyword=someword

Someword here is the word which user writes in dialog window.

I need only

  • coords
  • address
  • company_name

Here I have null in coords. I want to take the results and show it Google Maps.

What's wrong? How I can fix problem?

JSON:

JSON Data Screenshot

LocationActivity.java

private void showInputDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        final LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_search, null);
        builder.setView(dialogView);

        final EditText inputSearch = (EditText) dialogView.findViewById(R.id.input_service);
        inputSearch.setInputType(InputType.TYPE_CLASS_TEXT);

        builder.setPositiveButton("Поиск", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                final String SearchPosition = inputSearch.getText().toString();

                if (SearchPosition.matches("")) { //Check if EditText is empty
                    Toast.makeText(getApplicationContext(), "Space is empty!", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    NetworkFactory.getInstance().getApiCall().getPosition(new Words(SearchPosition), new Callback<PositionResponse>() {
                        @Override
                        public void success(PositionResponse positionResponse, Response response) {
                            Log.d("Result: ", Arrays.toString(positionResponse.getPosition()).replaceAll("\\[|\\]", ""));
                            if (positionResponse.getPosition() == null) {
                                //Toast Message
                                Toast.makeText(getApplicationContext(), "There is no such result! Try again!", Toast.LENGTH_LONG).show();
                            } else {
                                String mLatLng = Arrays.toString(positionResponse.getPosition()).replaceAll("\\[|\\]", "");

                                String[] arrayLatLng = mLatLng.split(","); //separate out lat and lon
                                LatLng positionLatLon = new LatLng(Double.parseDouble(arrayLatLng[0]), Double.parseDouble(arrayLatLng[1])); //create the LatLng object

                                mGoogleMap.addMarker(new MarkerOptions().position(positionLatLon)
                                        .title("Result")
                                        .snippet("Result of search: " + SearchPosition)
                                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location)));

                                CameraPosition cameraPosition = new CameraPosition.Builder().target(positionLatLon).zoom(17).build();
                                mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            error.toString();
                        }
                    });
                }
            }
        });
        builder.show();
    }

NetworkFactory.java

public class NetworkFactory {
    public static final String API_URL = "http://192.168.0.102:8000";
    private static NetworkFactory ourInstance = new NetworkFactory();
    private ApiCalls apiCalls;

    private NetworkFactory() {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL)
                .build();
        apiCalls = restAdapter.create(ApiCalls.class);
    }

    public static NetworkFactory getInstance() {
        return ourInstance;
    }

    public ApiCalls getApiCall() {
        return apiCalls;
    }
}

ApiCalls.java

    public interface ApiCalls {
        @GET("/api/get_services")
        void getPosition(@Query("keyword") Words words, Callback<PositionResponse> responseCallback);
    }

PositionResponse.java

public class PositionResponse {
    private double[] coords;
    private String address;
    private String company_name;

    public double[] getPosition() {
        return coords;
    }

    public void setPosition(double[] coords) {
        this.coords = coords;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCompanyName() {
        return company_name;
    }

    public void setCompanyName(String company_name) {
        this.company_name = company_name;
    }
}
JNYRanger
  • 6,829
  • 12
  • 53
  • 81
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193

2 Answers2

1

As dabluck told you, you web service is responding with a JSONArray, so you will need to wrap your response around a List (for example).

Something like this should work:

public class ListPositionResponse { 

    private List<PositionResponse> service_list;
    public ListPositionResponse(List<PositionResponse> service_list){
        this.service_list = service_list;
    }
} 

So you retrofit call will be:

public interface ApiCalls { 
        @GET("/api/get_services") 
        void getPosition(@Query("keyword") Words words, Callback<ListPositionResponse> responseCallback);
}

Hope it will help you.

EDIT: To get the coords for each PositionResponse:

public class ListPositionResponse { 

        private List<PositionResponse> service_list;
        public ListPositionResponse(List<PositionResponse> service_list){
            this.service_list = service_list;
        }

        public List<PositionResponse> getPositions(){
            return this.service_list;
    } 



// And In your Activity
public void showCoords(ListPositionResponse positionResponse){
    for(PositionResponse position : positionResponse.getPositions()){
        doSomethingWithPosition(position);
    }
}


public void doSomethingWithPosition(PositionResponse position){
    double[] coords = position.getPosition();
    LatLng positionLatLon = new LatLng(double[0], double[1]);
}
SekthDroid
  • 140
  • 1
  • 9
  • Hello man! I have some questions... what mean position value here. I am now sure that I have it... Can you explaine it please! – Nurzhan Nogerbek May 03 '15 at 01:51
  • 1
    Sorry Nurzhan, I did it so fast and I failed creating the constructor. Now i have fixed it. To be able to save the response you are getting, you need a List with the same variable name as the JSON, in this case, is "service_list". Now the Gson will create an object with the response of your JSON correctly. Hope it helps ;) – SekthDroid May 03 '15 at 17:20
  • Hello man again! Thanks for your reply. I am little bit confused in my LocationActivity.java document cause before my Callback was PositionResponse in which I described coordinates as a coords value. Now as I understand Callback will be ListPositionResponse and I dont know how to take coords from it. Can you help me one more time please! – Nurzhan Nogerbek May 05 '15 at 14:24
  • Hi Nurzhan, I have updated the response with something that may help you – SekthDroid May 05 '15 at 16:02
0

your positionresponse object isn't correct. you need a servicelist object in there. use jsonschema2pojo.org to generate objects and try again

dabluck
  • 1,641
  • 2
  • 13
  • 20
  • take the json output. drop it in to jschema2pojo.org (fill out all the fields how you want them). download the jar. export the classes and drop them into your project. you'll have to do a bit of cleanup, but once they're configured properly retrofit will just work – dabluck May 02 '15 at 23:57