0
votes

I am trying to Geocode an address and get the coordinates. I don't need it to be displayed on the map for which, as per my searching, does not require an API key. On running my code, I was getting NullPointerException so I have put server connecting code in a separate thread but now I am getting 0.0, 0.0 as my latitude and longitude. So, where I am making the mistake?

Here's my code:

public class MainActivity extends Activity {

    private TextView myAddress;
    private EditText addressET;
    private Button okButton;

    GeocodeResponse gr;
    Button hiButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myAddress = (TextView) findViewById(R.id.myAdrs);
        addressET = (EditText) findViewById(R.id.addressEditText);
        okButton = (Button) findViewById(R.id.OK);

        okButton.setOnClickListener(new OnClickListener() {

            double lattitude;
            double longitude;
            private String address;

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                address = addressET.getText().toString();
                if (address == null) {
                    Toast.makeText(getApplicationContext(), "Enter address",
                            Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            gr.gecodeResponse(address);
                        }
                    });

                    if(lattitude!=0)lattitude = gr.lattitude();
                    if(longitude!=0)longitude = gr.longitude();

                    myAddress.setText(lattitude + " " + longitude);
                }
            }
        });
    }
}

GeocodeResponse.java:

public class GeocodeResponse {

     double lng;
     double lat;


    public void gecodeResponse(String address) {
        // TODO Auto-generated method stub
        String uri = "http://maps.google.com/maps/api/geocode/json?address="+address+"&sensor=false";
        HttpGet httpGet = new HttpGet(uri);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        StringBuilder stringBuilder = new StringBuilder();

        try {
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream stream = entity.getContent();
            int b;
            while ((b = stream.read()) != -1) {
                stringBuilder.append((char) b);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());

            lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lng");

            lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getJSONObject("geometry").getJSONObject("location")
                    .getDouble("lat");

             Log.e("lattitude"+"", lat+"");
             Log.e("longitude", lng+""); 
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    double lattitude() {
        return lat;

    }

    double longitude() {
        return lng;
    }

}

json response:

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA

2
Post your logcat error message here.Md Abdul Gafur
carefully parse the data step by step. Means Log the data in each time and check the result. Most Probably it will be parsing mistakeDeadlyDroid
@MdAbdulGafur No error in logcat.kiran
@DeadlyDroid can you look at the json response, I couldn't find any mistakes.kiran
@kiran You are Correct there is no issue in parsing.Log the stringBuilder and check it if it has the correct value or no. You can use String str=EntityUtils.toString(entity). for converting it to stringDeadlyDroid

2 Answers

0
votes

Your future problem will be that you're not checking which kind of response you got. Is it rooftop or some other thing. I don't know if this matter for you, but you can get very far results sometimes.

I'm doing it like below. Iterating over the whole result (this gives a pro for debuggin if you'va got any results or not), checking the type of result (refer to gmaps docs) and for example adding it to a global list.

if (result!=null){
    List<Integer> rooftopsIds = new ArrayList<Integer>();
    JSONArray result = ((JSONArray) jsonObj.get("results"));
    int length = result.length();
    for (int i = 0; i < length; i++) {
        String type = result.getJSONObject(i).getJSONObject("geometry").getString("location_type");
        if (type.equalsIgnoreCase("ROOFTOP")) {
            //probably the most accurate response
            rooftopsIds.add(i); 
        }
        if (type.equalsIgnoreCase("RANGE_INTERPOLATED")) {
            //less accurate response
        }
        if (type.equalsIgnoreCase("GEOMETRIC_CENTER")) {
            //the worst result as for me :)
        }
    }
}

Then i can check if I got more than one result of each type. This matters because I've had situations where I got two rooftops for one address, the difference was that the other address was in nearby city, not the one user provided. So my advice is to check it.

To the gmaps url you shoould also add "&language=en-EN" (or your language)

Have you checked your JSON result Object, what does it contain? And you can paste the gmaps url into firefox with the address you want to geocode, you will get printed results.

It would be the best to use a breakpoint and debug on device after received result (you could easily view the whole JSON Object.

-1
votes

Kiran,

Going through the code,I felt that it was ok,The problem is where you have tested the application?

  • You have to send the lat,long to the emulator using DDMS prespective
  • Else,you have to debug the application through mobile phones( prefered)

I hope you understand the issue :)

Edit:

JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());

        lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

        lat = ((JSONArray) jsonObject.get("results")).getJSONObject(1)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

Try this.