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: