How can I get the nearest Place (Village Or Street name) - android

In my application, when the user insert data i want to capture the user's exact place. I've tried so many methods. But none of them shown the exact place. (I meant that they display the country and admin area details only. I used getLocality and getFeatureName. If no Locality or Featurename found at that latitude and longitude then it will return a null value). My code is
Geocoder coder=new Geocoder(MainActivity.mContext,Locale.getDefault());
try
{
List<Address> listaddress=coder.getFromLocation(lat, lon, 1);
Address obj=listaddress.get(0);
String add=obj.getAddressLine(0);
add = add+"\n"+obj.getLatitude();
add = add+","+obj.getLongitude();
add = add + "," + obj.getCountryName();
add = add + "," + obj.getAdminArea();
add = add + "\n" + obj.getPostalCode();//null
add = add + "," + obj.getSubAdminArea();
add = add +","+obj.getFeatureName();//null
add = add+ "," +obj.getPremises();//null
add = add + "\n" + obj.getLocality();//null
add = add + "," + obj.getSubThoroughfare();//null
add = add+ "," +obj.getSubLocality();//null
add = add+"\n"+obj.getThoroughfare();
Log.v("IGA", "Address" + add);
//Toast.makeText(this, "Address=>" + add,Toast.LENGTH_SHORT).show();
t.setText(" "+add);
}
So I don't know how to solve it. But I have an idea. I need to find the nearest place to my exact latitude and longitude value, so that i can use that place. But I don't know how to find the nearest place (Nearest place means Village or Street not any others).
Also, In Android phones one application "Places" is there. It shows the correct area about where exactly I'm. Is there any possibilities to use the application "Places" to find my exact or nearest area. (I need the closest village or street, not subAdminArea (state). If yes, please explain.
Can anyone help me please

Using google reverse geocoding api you could get your actual street address by giving latitude and lantitude values.
Get Lat & Lan through GPS Receiver in Android
Then call google reverse geocoding api top fecth the actual street address:
MapManager in = new MapManager(
"http://maps.google.com/maps/geo?output=xml&oe=utf-8&ll="
+ lattitude + "%2C"
+ lantitude + "&key=get-key-from-google-map-api");
content = in.URLRequest();
System.out.println("Addrss:"+in.parseMapData(content));
Class MapManager{
String url ="";
MapManager(String url){
this.url = url;
}
public String parseMapData(String data) {
String addr = "";
try {
InputStream in = new ByteArrayInputStream(data.getBytes());
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document doc = builder.parse(in, null);
NodeList address = doc.getElementsByTagName("address");
addr = address.item(0).getTextContent();
} catch (Throwable t) {
Log.v("Exception", "Exception: " + t.toString());
}
return addr;
}
public String URLRequest() {
httpclient = new DefaultHttpClient();
try {
httpget = new HttpGet(url);
httpresponse = httpclient.execute(httpget);
httpentity = httpresponse.getEntity();
response = EntityUtils.toString(httpentity);
response = response.trim();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IsServerConn = false;
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
IsServerConn = false;
}
return response;
}
}

private class MatchingNearByLocationTask extends
AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
jsonStr = getLocationInfo(latitude, longitude).toString(); // put longitude and latitude value from which u want find nearer palce
if (jsonStr != null) {
Log.i("location--??", jsonStr);
JSONObject jsonObj;
try {
jsonObj = new JSONObject(jsonStr);
JSONObject responseJsonObject = jsonObj
.getJSONObject("response");
JSONArray venues = responseJsonObject
.getJSONArray(("venues"));
for (int index = 0; index < venues.length(); index++) {
locationObject = new NearByLocationObject();
String id = "", name = "", longitude = "", latitude = "";
JSONObject venuesJsonObj = venues.getJSONObject(index);
id = venuesJsonObj.getString("id");
name = venuesJsonObj.getString("name");
JSONObject latLngJsonObj = venuesJsonObj
.getJSONObject("location");
longitude = latLngJsonObj.getString("lng");
latitude = latLngJsonObj.getString("lat");
locationObject.setId(id);
locationObject.setNameOfLocation(name);
locationObject.setLocationOfLatitude(latitude);
locationObject.setLocationOfLongitude(longitude);
nearByLocationArrayList.add(locationObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
adapter = new NearByLocationArrayAdapter(getContext(),
R.layout.nearby_location_item, nearByLocationArrayList);
nearByLocationListView.setAdapter(adapter);
}
#Override
protected void onCancelled() {
super.onCancelled();
progressDialog.dismiss();
}
}
private JSONObject getLocationInfo(double lat, double lng) {
HttpGet httpGet = new HttpGet(
"https://api.foursquare.com/v2/venues/search?ll="
+ lat
+ ","
+ lng
+ "&radius=100&oauth_token=TNFKWLITLCJYWPSLAXQNHCSDPHZ4IS5PWVDD45OI224JGFFM&v=20140407&intent=checkin");
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) {
} catch (IOException e) {
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
public class NearByLocationObject {
String id = "", nameOfLocation, locationOfLatitude, LocationOfLongitude;
public NearByLocationObject() {
super();
// TODO Auto-generated constructor stub
}
public NearByLocationObject(String id, String nameOfLocation,
String locationOfLatitude, String locationOfLongitude) {
super();
this.id = id;
this.nameOfLocation = nameOfLocation;
this.locationOfLatitude = locationOfLatitude;
LocationOfLongitude = locationOfLongitude;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNameOfLocation() {
return nameOfLocation;
}
public void setNameOfLocation(String nameOfLocation) {
this.nameOfLocation = nameOfLocation;
}
public String getLocationOfLatitude() {
return locationOfLatitude;
}
public void setLocationOfLatitude(String locationOfLatitude) {
this.locationOfLatitude = locationOfLatitude;
}
public String getLocationOfLongitude() {
return LocationOfLongitude;
}
public void setLocationOfLongitude(String locationOfLongitude) {
LocationOfLongitude = locationOfLongitude;
}
}

Related

Showing ProgressBar on parsing and downloading json result

In my App I am hitting a service which can have no result to n number of results(basically some barcodes). As of now I am using default circular progressbar when json is parsed and result is being saved in local DB(using sqlite). But if the json has large number of data it sometimes takes 30-45 min to parse and simultaneously saving that data in DB, which makes the interface unresponsive for that period of time and that makes user think the app has broken/hanged. For this problem I want to show a progressbar with the percentage stating how much data is parsed and saved so that user get to know the App is still working and not dead. I took help from this link but couldn't find how to achieve. Here's my Asynctask,
class BackGroundTasks extends AsyncTask<String, String, Void> {
private String operation, itemRef;
private ArrayList<Model_BarcodeDetail> changedBarcodeList, barcodeList;
private ArrayList<String> changeRefList;
String page;
public BackGroundTasks(String operation, String itemRef, String page) {
this.operation = operation;
this.itemRef = itemRef;
this.page = page;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (dialog == null) {
dialog = ProgressDialog.show(mActivity, null,
"Please wait ...", true);
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if (!connection.HaveNetworkConnection()) {
dialog.dismiss();
connection.showToast(screenSize, "No Internet Connection.");
return null;
}
if (operation.equalsIgnoreCase("DownloadChangeItemRef")) {
changeRefList = DownloadChangeItemRef(params[1]);
if (changeRefList != null && !changeRefList.isEmpty()) {
RefList1.addAll(changeRefList);
}
}
if ((changeRefList != null && changeRefList.size() >0)) {
setUpdatedBarcodes(changedBarcodeList);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#SuppressLint("SimpleDateFormat")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
ArrayList<String> DownloadChangeItemRef(String api_token) {
ArrayList<String> changedRefList = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(thoth_url + "/" + todaysDate
+ "?&return=json");
String url = thoth_url + "/" + todaysDate + "?&return=json";
String result = "";
try {
changedRefList = new ArrayList<String>();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(postRequest, responseHandler);
JSONObject jsonObj = new JSONObject(result);
JSONArray jsonarray = jsonObj.getJSONArray("changes");
if (jsonarray.length() == 0) {
return null;
}
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
changedRefList.add(obj.getString("ref"));
}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
// when there is no thoth url
Log.i("inclient: ", e.getMessage());
return null;
} catch (Exception e) {
// when there are no itemref
return null;
}
return changedRefList;
}
private boolean setUpdatedBarcodes(
final ArrayList<Model_BarcodeDetail> changedBarcodeList2) {
try {
BarcodeDatabase barcodeDatabase = new BarcodeDatabase(mActivity);
barcodeDatabase.open();
for (Model_BarcodeDetail model : changedBarcodeList2) {
barcodeDatabase.updateEntry(model, userId);
}
n++;
barcodeDatabase.close();
if (RefList1.equals(RefList)) {
if (dialog != null) {
dialog.dismiss();
}
connection.showToast(screenSize, "Barcodes updated successfully");
}
} catch (Exception e) {
Log.i("Exception caught in: ", "setDownloadedBarcodes method");
e.printStackTrace();
return false;
}
return true;
}

My UI is blocked using AsyncTask with distancematrix and google Maps

I'm using google maps to show some markers. The markers are download from a database and, at the same time, I get the distancematrix from google api, between the current position of the user and the marker that I get from the database.
My problem is that I was doing this with .get, bloking my ui (I've read that .get blocked the ui:
dataFromAsyncTask = testAsyncTask.get();
Now, I'm trying to do the same without blocking the ui, but I'm not be able to get at the same time, or in a good way, the distance for this markers.
I appreciate some help, please.
This is my code with my old and wrong .get:
for (City city : listCity.getData()) {
geoPoint = city.getLocation();
nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
startRetrievenDistanceAndDuration();
try {
dataFromAsyncTask = testAsyncTask.get();
} catch (InterruptedException i) {
} catch (ExecutionException e) {
}
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameCity)
.snippet(dataFromAsyncTask)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
startRetrievenDistanceAndDuration method:
private void startRetrievenDistanceAndDuration() {
final String url;
testAsyncTask = new DistanceBetweenLocations(new FragmentCallback() {
#Override
public void onTaskDone(String result) {
}
});
url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";
testAsyncTask.execute(new String[]{url});
}
public interface FragmentCallback {
public void onTaskDone(String result);
AsyncTask class:
#Override
protected String doInBackground(String... params) {
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url=new URL(params[0]);
}catch (MalformedURLException m){
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
}catch (IOException e){}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
result.append(line);
}
}catch (IOException e){
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
return distance + ", " + duration;
}
#Override
protected void onPostExecute(String result) {
mFragmentCallback.onTaskDone(result);
}
}
I'm trying to do this, but I only show the last marker of my list:
Call in the loop the method:
startRetrievenDistanceAndDuration();
And in onTaskDone try to put the marker, but only get the last marker of my list
#Override
public void onTaskDone(String result) {
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(result)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
UPDATED AFTER CHANGES: (still don't work)
I can parse the data in Asynctask and send it in onPostExecute, but I only get one value, and not the 9 values that I have....
MAIN ACTIVITY:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(HashMap<String, String> result) {
super.onPostExecute(result);
String name = result.get("beachName");
String distance = result.get("distance");
String duration = result.get("duration");
String latitue = result.get("latitude");
String longitude = result.get("longitude");
Double mlatituDouble = Double.parseDouble(latitue);
Double mlongitudeDouble = Double.parseDouble(longitude);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
Toast.makeText(getActivity(), "mMap NO null", Toast.LENGTH_SHORT).show();
mMap.addMarker(new MarkerOptions().position(new LatLng(mlatituDouble, mlongitudeDouble))
.title(name)
.snippet(distance + " " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
ASYNCTASK CLASS:.
public class DistanceBetweenLocations extends AsyncTask<String, String, HashMap<String, String>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
HashMap<String, String> map;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected HashMap<String, String> doInBackground(String... params) {
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
map = new HashMap<String, String>();
map.put("beachName", nameBeach);
map.put("distance", distance);
map.put("duration", duration);
map.put("latitude", latitude);
map.put("longitude", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return map;
}
}
I'll use your last code (the "UPDATED AFTER CHANGES"), ok?
If I get it right, your DistanceBetweenLocations result will be a list of beaches geolocation data. So, on every iteration of the for loop in doInBackground, you are replacing the value of "map" variable, this is your problem.
To solve your problem, you can have a List of HashMap or a List of a Pojo like this:
public class BeachPojo {
private String beachName;
private String distance;
private String duration;
private String latitude;
private String longitude;
public String getBeachName() {
return beachName;
}
public void setBeachName(String beachName) {
this.beachName = beachName;
}
public String getDistance() {
return distance;
}
public void setDistance(String distance) {
this.distance = distance;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
Using the Pojo, your AsyncTask will be like this:
public class DistanceBetweenLocations extends AsyncTask<String, String, List<BeachPojo>> {
Double currentLatitude;
Double currentlongitude;
public BeachMap beachMap;
public BackendlessCollection<Beach> dataBeach;
public GoogleMap mMap;
String latitude;
String longitude;
public DistanceBetweenLocations(Double currentLatitude, Double currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected List<BeachPojo> doInBackground(String... params) {
List<BeachPojo> list = new ArrayList<BeachPojo>();
BeachPojo pojo;
dataBeach = beachMap.listBeach;
for (Beach city : dataBeach.getData()) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint == null) {
} else {
latitude = String.valueOf(geoPoint.getLatitude());
longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
URL url = null;
StringBuilder result = null;
String duration = "";
String distance = "";
try {
url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxxx");
} catch (MalformedURLException m) {
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
}
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
} finally {
urlConnection.disconnect();
}
try {
JSONObject jsonObject = new JSONObject(result.toString());
JSONArray jsonArray = jsonObject.getJSONArray("rows");
JSONObject object_rows = jsonArray.getJSONObject(0);
JSONArray jsonArrayElements = object_rows.getJSONArray("elements");
JSONObject object_elements = jsonArrayElements.getJSONObject(0);
JSONObject object_duration = object_elements.getJSONObject("duration");
JSONObject object_distance = object_elements.getJSONObject("distance");
duration = object_duration.getString("text");
distance = object_distance.getString("text");
pojo = new BeachPojo();
pojo.setBeachName(nameBeach);
pojo.setDistance(distance);
pojo.setDuration(duration);
pojo.setLatitude(latitude);
pojo.setLongitude(longitude);
list.add(pojo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return list;
}
}
Now you have a List to iterate. I have adjusted the code a little bit to this goal:
DistanceBetweenLocations task = new DistanceBetweenLocations(mlatituDouble, mlongitudeDouble){
#Override
protected void onPostExecute(List<BeachPojo> result) {
super.onPostExecute(result);
if (mMap == null) {
mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapView))
.getMap();
}
Double beachLatitude;
Double beachLongitude;
for (BeachPojo pojo : result) {
beachLatitude = Double.parseDouble(pojo.getLatitude());
beachLongitude = Double.parseDouble(pojo.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(beachLatitude, beachLongitude))
.title(pojo.getBeachName())
.snippet(pojo.getDistance() + " " + pojo.getDuration())
.icon(BitmapDescriptorFactory.defaultMarker()));
}
}
};
task.execute();
I hope you understand the idea of returning a List from your AsyncTask and loop throught the result on onPostExecute method.
Note: this is an implementation without knowing the real code, then you should adjust to your reality.
I'm not exactly sure what you're trying to do but I think you've made this more complicated then it has to be.
From what I understand you have a list of City objects and you use them to construct some URLs from which you retrieve a JSON object that is use to construct MarkerOptions objects.
You can do that using a AsyncTask like this:
public class Task extends AsyncTask<City, Void, Markers> {
String currentLatitude;
String currentlongitude;
public Task(String currentLatitude, String currentlongitude){
this.currentLatitude = currentLatitude;
this.currentlongitude = currentlongitude;
}
#Override
protected String doInBackground(City... cities) {
final Markers mMap = ...;
for (City city : cities) {
GeoPoint geoPoint = city.getLocation();
String nameBeach = city.getName();
if (geoPoint != null) {
String latitude = String.valueOf(geoPoint.getLatitude());
String longitude = String.valueOf(geoPoint.getLongitude());
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + currentLatitude + "," + currentlongitude + "&destinations=" + latitude + "," + longitude + "&key=xxx";);
urlConnection = (HttpURLConnection) url.openConnection();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
JSONObject jsonObject = new JSONObject(result.toString()).getJSONArray("rows").getJSONObject(0).getJSONArray("elements").getJSONObject(0);
String duration = jsonObject.getJSONObject("duration").getString("text");
String distance = jsonObject.getJSONObject("distance").getString("text");
mMap.addMarker(new MarkerOptions().position(new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()))
.title(nameBeach)
.snippet(distance + ", " + duration)
.icon(BitmapDescriptorFactory.defaultMarker()));
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
}catch (Exception e){
e.printStackTrace();
}
}
if (urlConnection != null) {
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
return mMap;
}
}
And here is how you can use this task.
public class Login extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
Task task = new Task(currentLatitude, currentlongitude){
#Override
protected void onPostExecute(Markers markers) {
super.onPostExecute(markers);
//This runs on the UI thread and "markers" is the "mMap" object that was create on the background thread.
}
};
List<City> cities = ....
task.execute(cities.toArray(new City[cities.size()]));
}
}
The idea is that you need to execute all the long running operation in the AsyncTask's doInBackground(...) method. Also, you don't need to create other objects to deal with the AsyncTask response, you can override the task's onPostExecute(...) inside the class you've created the task in.

Nothing happens in the try

In this activity, i get places nearby and add them to a listview. I wanted also to add the place's phone number in an arrayList like the other datas, so i had to use place details request. So, i get all the place_id for all the places from the arrayList and launch the query to get the details (phone number). The problem is in class "readFromGooglePlaceDetailsAPI", it goes in the "try" and goes out with nothing happening, i don't know why!!! I only can see "IN TRY !!!" and then "----" from the println.
Is my sequence not right?
Where is the problem and what is the solution ?
public class ListActivity extends Activity implements OnItemClickListener {
public ArrayList<GetterSetter> myArrayList;
ArrayList<GetterSetter> detailsArrayList;
ListView myList;
ProgressDialog dialog;
TextView nodata;
CustomAdapter adapter;
GetterSetter addValues;
GetterSetter addDetails;
private LocationManager locMan;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_activity);
if (!isNetworkAvailable()) {
Toast.makeText(getApplicationContext(), "Enable internet connection and RE-LAUNCH!!",
Toast.LENGTH_LONG).show();
return;
}
myList = (ListView) findViewById(R.id.placesList);
placeSearch();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
public void placeSearch() {
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
dialog = ProgressDialog.show(this, "", "Please wait", true);
//build places query string
String placesSearchStr;
placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types="+ ServicesListActivity.types+
"&key=My_KEY";
//execute query
new readFromGooglePlaceAPI().execute(placesSearchStr);
myList.setOnItemClickListener(this);
}
public void detailsSearch() {
String detailsSearchStr;
//build places query string
for(int i=0; i < myArrayList.size(); i++){
detailsSearchStr = "https://maps.googleapis.com/maps/api/place/details/json?" +
"placeid=" + myArrayList.get(i).getPlace_id() +
"&key=My_KEY";
Log.d("PlaceID:", myArrayList.get(i).getPlace_id());
//execute query
new readFromGooglePlaceDetailsAPI().execute(detailsSearchStr);
}
}
public class readFromGooglePlaceDetailsAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
detailsArrayList = new ArrayList<GetterSetter>();
String phoneNumber =" -NA-";
try {
System.out.println("IN TRY !!!");
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("result");
System.out.println("Before FOR !!!");
for (int i = 0; i < results.length(); i++) {
System.out.println("IN FOR LOOP !!!");
addDetails = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
if(!arrayItems.isNull("formatted_phone_number")){
phoneNumber = arrayItems.getString("formatted_phone_number");
Log.d("Phone Number ", phoneNumber);
}
addDetails.setPhoneNumber(phoneNumber);
System.out.println("ADDED !!!");
detailsArrayList.add(addDetails);
Log.d("Before", detailsArrayList.toString());
}
} catch (Exception e) {
}
System.out
.println("------------------------------------------------------------------");
Log.d("After:", detailsArrayList.toString());
// nodata = (TextView) findViewById(R.id.nodata);
//nodata.setVisibility(View.GONE);
// adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, detailsArrayList);
// myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
// dialog.dismiss();
}
}
public class readFromGooglePlaceAPI extends AsyncTask<String, Void, String> {
#Override protected String doInBackground(String... param) {
return readJSON(param[0]);
}
protected void onPostExecute(String str) {
myArrayList = new ArrayList<GetterSetter>();
String rating=" -NA-";
try {
JSONObject root = new JSONObject(str);
JSONArray results = root.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
addValues = new GetterSetter();
JSONObject arrayItems = results.getJSONObject(i);
JSONObject geometry = arrayItems.getJSONObject("geometry");
JSONObject location = geometry.getJSONObject("location");
//place ID for place details later
String placeID = arrayItems.getString("place_id").toString();
if(!arrayItems.isNull("rating")){
rating = arrayItems.getString("rating");
}
addValues.setPlace_id(placeID);
addValues.setLat(location.getString("lat"));
addValues.setLon(location.getString("lng"));
addValues.setName(arrayItems.getString("name").toString());
addValues.setRating(rating);
addValues.setVicinity(arrayItems.getString("vicinity").toString());
myArrayList.add(addValues);
//Log.d("Before", myArrayList.toString());
}
} catch (Exception e) {
}
// System.out
// .println("############################################################################");
// Log.d("After:", myArrayList.toString());
nodata = (TextView) findViewById(R.id.nodata);
nodata.setVisibility(View.GONE);
adapter = new CustomAdapter(ListActivity.this, R.layout.list_row, myArrayList);
myList.setAdapter(adapter);
//adapter.notifyDataSetChanged();
dialog.dismiss();
detailsSearch();
}
}
public String readJSON(String URL) {
StringBuilder sb = new StringBuilder();
HttpGet httpGet = new HttpGet(URL);
HttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} else {
Log.e("JSON", "Couldn't find JSON file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
#Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent details = new Intent(ListActivity.this, Details.class);
details.putExtra("name", myArrayList.get(arg2).getName());
details.putExtra("rating", myArrayList.get(arg2).getRating());
details.putExtra("vicinity", myArrayList.get(arg2).getVicinity());
details.putExtra("lat", myArrayList.get(arg2).getLat());
details.putExtra("lon", myArrayList.get(arg2).getLon());
details.putExtra("formatted_phone_number", detailsArrayList.get(arg2).getPhoneNumber());
startActivity(details);
}
}
try{
JSONObject jsonObject = new JSONObject(str);
if (jsonObject.has("results")) {
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
//your logic here
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Note that the getJSONArray() function throws an Exception if the mapping fails. For example I can't find a JSON Array which is called results.
The most important thing you have to do at first is:
change:
catch (Exception e) {
}
to
catch (Exception e) {
Log.e(YOUR_TAG, "Exception ..." , e);
}
Your try throws an Exception which you don't even Log. That might be the reason why you are confused.

How to eliminate the empty strings inside the object in android json parsing

Hi friends i like to parse the json from url and also like to elimate the null values field and only show the object which has value if anyone known syntax for that means please guide me thanks in advance.
JSON Structure
{
"daftar_rs": [
{
"Name": "exe1",
"URL": "http://samir-mangroliya.blogspot.in/p/android-json-parsing-tutorial.html"
},
{
"Name": "exe2",
"URL": "https://code.google.com/p/json-io/"
},
{
"Name": "exe3",
"URL": ""
},
{
"Name": "exe4",
"URL": "http://stackoverflow.com/questions/10964203/android-removing-jsonobject"
},
{
"Name": "exe5",
"URL": ""
},
{
"Name": "exe6",
"URL": ""
}
],
"success": 1
}
MainActivity
public class MainActivity extends Activity {
ListView lv;
List<String> titleCollection = new ArrayList<String>();
List<String> urlCollection = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
// we will using AsyncTask during parsing
new AsyncTaskParseJson().execute();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String linkUrl = urlCollection.get(arg2);
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
});
}
public void loadContents()
{
ArrayAdapter<String> adapter =new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,titleCollection);
lv.setAdapter(adapter);
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
final String TAG = "AsyncTaskParseJson.java";
// set your json string url here
String yourJsonStringUrl = "http://192.168.1.167/vinandrophp/vinex.php";
// contacts JSONArray
JSONArray dataJsonArr = null;
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... arg0) {
try {
// instantiate our json parser
JsonParser jParser = new JsonParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);
// loop through all users
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String strFromDoInBg) {
loadContents();
}
}
}
JsonParser.java
public class JsonParser {
final String TAG = "JsonParser.java";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONObject getJSONFromUrl(String url) {
// make HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e(TAG, "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
Just check it inside your code.
String linkUrl = urlCollection.get(arg2);
if (linkUrl== null || linkUrl.equals("")){
// null
}
else{
// not null so put to extras and start intent
Intent webViewIntent = new Intent(MainActivity.this, WebViewActivity.class);
webViewIntent.putExtra("url", linkUrl);
startActivity(webViewIntent);
}
try below code
for (int i = 0; i < dataJsonArr.length(); i++)
{
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String Name = c.getString("Name");
String Url = c.getString("URL")
if(!TextUtils.isEmpty(Name) && !TextUtil.isEmpty(Url))
{
titleCollection.add(Name);
urlCollection.add(Url));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection + ", URL: " + urlCollection);
}
try below code:-
if(c.getString("URL").equals("") || c.isNULL("URL"))
{
// do nothing
}
else
{
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
Change for loop as
for (int i = 0; i < dataJsonArr.length(); i++) {
JSONObject c = dataJsonArr.getJSONObject(i);
// Storing each json item in variable
String name = c.getString("Name");
String url = c.getString("URL");
if(name != null && !(name.equals(""))
&& url != null && !(url.equals(""){
titleCollection.add(c.getString("Name"));
urlCollection.add(c.getString("URL"));
}
// show the values in our logcat
Log.e(TAG, "Name: " + titleCollection
+ ", URL: " + urlCollection);
}
Try replace keys and values with regular expression if the key is empty in the JsonParser class.
json=json.replaceAll("\\n",""); //you should do not have any new lines after commas
json=json.replaceAll(",\\W*\"\\w+\":\\W?(\"\"|null)","");

android - Best way to get the Current Address

I am getting the Latitude and Longitude from the Location Manager.
After getting these points, I am trying to get the Address using Geocoder method with these geopoints but I got the IOException called service not available.
I was try to fix this issue but I am unable to do it. Then I was changed the Implementation, after few hours I found one solution but I don't Know Is this best way.
Please advice what's the best way to get the current address?
public class MainActivity extends Activity implements LocationListener {
// providers
public LocationManager locationManager;
String strNetworkProvider;
public TextView tvAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the Location Manager
String locati
locati getSystemService(location_context);
strNetworkProvider = LocationManager.NETWORK_PROVIDER;
locationManager.requestLocationUpdates(strNetworkProvider, 0, 0,
MainActivity.this);
tvAddress = (TextView) findViewById(R.id.address);
}
// Get the current Location
#Override
public void onLocationChanged(Location location) {
if (location != null) {
locationManager.removeUpdates(MainActivity.this);
double latitude = location.getLatitude();
double l
Double[] geopoints = { latitude, longitude };
Log.i("Latitude and Logitude", latitude + ", " + longitude);
// async task for initial WS call
new getAddressFromGeopoints().execute(geopoints);
}
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
// Async task for getting the address
public class getAddressFromGeopoints extends
AsyncTask<Double, Void, List<Address>> {
#Override
protected List<Address> doInBackground(Double... geoPoints) {
List<Address> addresses;
addresses = getFromLocation(geoPoints[0], geoPoints[1], 1);
return addresses;
}
protected void onPostExecute(final List<Address> addresses) {
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0);
tvAddress.setText(address);
Log.i("Address", address);
}
}
}
// This method is responsible for get the address from the
// Geopoints(Latitude and Longitude)
public static List<Address> getFromLocation(double lat, double lng,
int maxResult) {
String address = String
.format(Locale.ENGLISH,
"http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language;="
+ Locale.getDefault().getCountry(), lat, lng);
HttpGet httpGet = new HttpGet(address);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
List<Address> retList = null;
try {
resp
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject js JSONObject();
js JSONObject(stringBuilder.toString());
retList = new ArrayList<Address>();
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String indiStr = result.getString("formatted_address");
Address addr = new Address(Locale.ITALY);
addr.setAddressLine(0, indiStr);
retList.add(addr);
}
}
} catch (ClientProtocolException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
} catch (IOException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
} catch (JSONException e) {
Log.e(MainActivity.class.getName(),
"Error parsing Google geocode webservice response.", e);
}
return retList;
}
}
Sharing the code which I generally use
How to use the code :- first calculate the lat and lng and the call String address[] = getCountry();
address[0] // country
address[1] // postal code
address[2] // Locality
address[3] // AddressLine
Constants
private static final int COUNTRY = 0;
private static final int POSTALCODE = 1;
private static final int CITY = 2;
private static final int ADDRESS = 3;
Methods
public String[] getCountry() {
if (lat != 0.0 && lng != 0.0) {
Geocoder geocoder = new Geocoder(activity, Locale.getDefault());
String[] country = new String[4];
try {
List<Address> addresses = geocoder.getFromLocation(lat,
lng, 1);
if (addresses.size() > 0) {
Address obj = addresses.get(0);
// String add = obj.getAddressLine(0);
country[0] = obj.getCountryName() == null ? "xx" : obj
.getCountryName();
country[1] = obj.getPostalCode() == null ? "xx" : obj
.getPostalCode();
country[2] = obj.getLocality() == null ? "xx" : obj
.getLocality();
country[3] = obj.getAddressLine(0) == null ? "xx" : obj
.getAddressLine(0);
} else {
country = getFromLocation();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
// Toast.makeText(activity, e.getMessage(),
// Toast.LENGTH_SHORT).show();
return getFromLocation();
}
return country;
} else {
return new String[] { "xx", "xx", "xx", "xx" };
}
}
public String[] getFromLocation() {
String[] countries = new String[4];
String address = String
.format(Locale.ENGLISH,
"http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=true&language="
+ Locale.getDefault().getCountry(), lat,
lng);
// Log.v("url", address);
StringBuilder stringBuilder = new StringBuilder();
try {
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
InputStream stream = conn.getInputStream();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
// Log.v("json", stringBuilder.toString());
if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) {
JSONArray results = jsonObject.getJSONArray("results");
int count = 0;
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
countries[ADDRESS] = result
.getString("formatted_address");
JSONArray array = result
.getJSONArray("address_components");
for (int j = 0; j < array.length(); j++) {
JSONObject oo = array.getJSONObject(j);
JSONArray type = oo.getJSONArray("types");
for (int k = 0; k < type.length(); k++) {
String tt = type.getString(k);
if (tt.equals("country")) {
countries[COUNTRY] = oo
.getString("long_name");
count++;
}
if (tt.equals("postal_code")) {
countries[POSTALCODE] = oo
.getString("long_name");
count++;
}
if (tt.equals("locality")) {
countries[CITY] = oo.getString("long_name");
count++;
}
if (count == 3) {
return countries;
}
}
}
String indiStr = result.getString("address_components");
Address addr = new Address(Locale.getDefault());
addr.setAddressLine(0, indiStr);
}
}
} catch (ClientProtocolException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
return new String[] { "xx", "xx", "xx", "xx" };
} catch (IOException e) {
Log.e(MainActivity.class.getName(),
"Error calling Google geocode webservice.", e);
return new String[] { "xx", "xx", "xx", "xx" };
} catch (JSONException e) {
Log.e(MainActivity.class.getName(),
"Error parsing Google geocode webservice response.", e);
return new String[] { "xx", "xx", "xx", "xx" };
}
return countries;
}
}
If the code can not find the address it will return xx.

Categories

Resources