Android Geocoder getFromLocationName fails with valid address - java

I'm trying to get latitude and longitude of specific addresses using
addressList = geoCoder.getFromLocationName(locationName, 1);
For most addresses this works just fine, but there are some valid addresses, like "Lentoasemantie 1, Vantaa", which returns empty array. The strange thing is that the valid addresses used to work 4 days ago, but not anymore while most of the addresses continue to work.
So, this looks like Google backend problem and I'm wondering should I report this to Google (where / how?) or switch away from using Geocoder, because it's inherently unreliable?

Geocoder Android API is not as efficient as the Google Maps Geocoding API so I suggest you to use this one instead of Geocoder.
You can find below the function to get location from address through Volley queue (For Lentoasemantie 1, Vantaa, it works) :
public void getLocationFromAddress(String address) {
String url = "https://maps.googleapis.com/maps/api/geocode/json?address="
+ Uri.encode(address) + "&sensor=true&key=API_KEY";
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest stateReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONObject location;
try {
// Get JSON Array called "results" and then get the 0th
// complete object as JSON
location = response.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
// Get the value of the attribute whose name is
// "formatted_string"
if (location.getDouble("lat") != 0 && location.getDouble("lng") != 0) {
LatLng latLng = new LatLng(location.getDouble("lat"), location.getDouble("lng"));
//Do what you want
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
});
// add it to the queue
queue.add(stateReq);
}

Related

Google API returning the server location, not user location

Hello so I though I was getting user location through this code but im actually getting the server's location, any idea how can I change it so I get the user location?
public void geolocate() {
try {
GeolocationPayloadBuilder payloadBuilder = new GeolocationPayload.GeolocationPayloadBuilder();
GeolocationPayload payload = payloadBuilder.createGeolocationPayload();
//GeoApiContext context = new GeoApiContext.Builder().apiKey("my api key").build();
// I guess the payload needs to be build in a different way but no clue how it should be :/
GeolocationApiRequest req = (GeolocationApiRequest) GeolocationApi.geolocate(context, payload);
GeolocationResult res = req.await();
String location = res.location.toString();
String[] latLngArray = location.split(",");
com.google.maps.model.LatLng latLng = new com.google.maps.model.LatLng(Double.parseDouble(latLngArray[0]),
Double.parseDouble(latLngArray[1]));
GeocodingApiRequest geoReq = GeocodingApi.reverseGeocode(context, latLng);
GeocodingResult[] geoRes = geoReq.await();
// Setting the user location for view
System.out.println(geoRes[0].formattedAddress);
origen.setValue(geoRes[0].formattedAddress);
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
}
this is the dependency where im getting the objects from:
<dependency>
<groupId>com.google.maps</groupId>
<artifactId>google-maps-services</artifactId>
<version>0.9.3</version>
</dependency>
hope somebody can help me with this, thanks in advance
EDIT:
I have been searching and found out how to build the payload with help of https://developers.google.com/maps/documentation/geolocation/intro#cell_tower_object
But I have a couple of question which is how will I get my users mac address to create the wifiAccessPoint and also where do I find info of cell towers in my city (Cali, Colombia)? Just an update will keep searching any help is appreciated..
#POST
#Path("/geolocate")
public String geolocate() {
try {
CellTower newCellTower = new CellTower.CellTowerBuilder().CellId(42).LocationAreaCode(415)
.MobileCountryCode(310).MobileNetworkCode(410).Age(0).createCellTower();
WifiAccessPoint newWifiAccessPoint = new WifiAccessPoint.WifiAccessPointBuilder()
.MacAddress("00:25:9c:cf:1c:ac").createWifiAccessPoint();
WifiAccessPoint newWifiAccessPoint2 = new WifiAccessPoint.WifiAccessPointBuilder()
.MacAddress("00:25:9c:cf:1c:ad").createWifiAccessPoint();
GeolocationPayloadBuilder payloadBuilder = new GeolocationPayload.GeolocationPayloadBuilder()
.HomeMobileCountryCode(310).HomeMobileNetworkCode(410).RadioType("gsm").Carrier("Vodafone")
.ConsiderIp(false).AddCellTower(newCellTower).AddWifiAccessPoint(newWifiAccessPoint)
.AddWifiAccessPoint(newWifiAccessPoint2);
GeolocationPayload payload = payloadBuilder.createGeolocationPayload();
GeoApiContext context = new GeoApiContext.Builder().apiKey("my api key")
.build();
GeolocationApiRequest req = (GeolocationApiRequest) GeolocationApi.geolocate(context, payload);
GeolocationResult res = req.await();
String location = res.location.toString();
String[] latLngArray = location.split(",");
com.google.maps.model.LatLng latLng = new com.google.maps.model.LatLng(Double.parseDouble(latLngArray[0]),
Double.parseDouble(latLngArray[1]));
GeocodingApiRequest geoReq = GeocodingApi.reverseGeocode(context, latLng);
GeocodingResult[] geoRes = geoReq.await();
// Setting the user location for view
return geoRes[0].formattedAddress;
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
return "XD";
}
The Geolocation API of Google Maps Platform is not intended for getting user location, what I can suggest is that you use the HTML5 Geolocation instead, there's also a sample of that in the Google Maps Platform documentation. But please note that this is not supported by Google as this is using HTML5 Geolocation and not Google APIs, if you wish to get the address of the user location as well, you may Geocode the coordinates that will be returned by the HTML5 Geolocation. You may see the sample below (without the Geocoding function). Here's a working sample - https://jsfiddle.net/w2sad5pn/
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}

org.json.JSONException: Index 0 out of range [0..0) How to resolve it?

I am facing this issue from past few days after adding google maps api in project. I have done everything , I have enabled the free trial billing and have also done many changes regarding code but nothing i got , after that i added google place api but result is the search bar suddenly disappear.
In this code it is showing error:
private void drawRoute(final LatLng yourLocation, String address) {
mService.getGeoCode(address).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try{
JSONObject jsonObject=new JSONObject(response.body().toString());
String lat= ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lat").toString();
String lng= ((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
.getJSONObject("geometry")
.getJSONObject("location")
.get("lng").toString();
LatLng orderLocation=new LatLng(Double.parseDouble(lat),Double.parseDouble(lng));
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.locationmarker);
bitmap=Common.scaleBitmap(bitmap,70,70);
MarkerOptions marker=new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.title("Order of "+Common.currentRequest.getPhone())
.position(orderLocation);
mMap.addMarker(marker);
//draw route
mService.getDirections(yourLocation.latitude+","+yourLocation.longitude,
orderLocation.latitude+","+orderLocation.longitude)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
new ParserTask().execute(response.body().toString());
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
}
I guess the error occurs at this place:
((JSONArray)jsonObject.get("results"))
.getJSONObject(0)
You have to consider the case that the results property contains just an empty array. To do so you might assign the results array to a variable, test for its length and if it's 0 do something else like returning immediately (doing nothing) or showing a message to the user.
JSONArray results = (JSONArray)jsonObject.get("results");
if (results.length() == 0) {
// handle this case, for example
return;
}
// There is at least one result
String lat= results
.getJSONObject(0)
.getJSONObject("geometry")
...

Replace element of ArrayList if object of same value already present in it

I'm using socket.io for my chat app. I have an ArrayList which contains last message, username, time. Whenever a new message arrives in JSON format then it should check if JSON contained username is present in ArrayList or not. If present, then updates the ArrayList otherwise add in ArrayList.
Here is my code:-
private Emitter.Listener handle1 = new Emitter.Listener() {
#Override
public void call(final Object... args) {
ChatLists.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject)args[0];
try {
String sendername = data.getString("sender");
String lastMessage = data.getString("message");
String profileImage = data.getString("Profile");
String token = data.getString("fb_token");
chat_list chat_list = new chat_list(sendername,
profileImage, lastMessage, "0", "", "dummy", token);
if (chat_lists.size()==0){
chat_lists.add(chat_list);
}else {
for (int i=0;i<chat_lists.size();i++){
if (chat_lists.get(i).getContactname().equals(sendername)){
chat_lists.set(i,chat_list);
}else {
chat_lists.add(chat_list)
}
}
}
contactlistAdapter = new ContactlistAdapter(chat_lists);
recyclerView.setAdapter(contactlistAdapter);
contactlistAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
};
Well, you can use contains() & set() methods of ArrayList in a logical way to solve your problem like below:-
if(chat_lists.contains(username))
chat_lists.set(indexOf(username), new_username);
else chat_lists.add(new_username);
Try it:
if(chat_lists.contains(chat_list)){
chat_lists.remove(chat_list);
chat_lists.add(chat_list);
} else {
chat_lists.add(chat_list);
}
Read about architecture patterns, for example, MVP.
You need to store your messages somethere (in Model) and update view relative to data.
Also read about RecyclerView, cause of ListView is a little bit deprecated
if (chat_lists.get(i).getContactname().equals(sendername)){
above statement has problem them. It's not getting under your if condition and following the chat_lists.add(chat_list) statement.
Instead equals use ignoreCasequals. If still wont it solve your problem please use debug mode or logs check chat_lists.get(i).getContactname()
and sendername same or not.

json array value from volley into hashmap string, string

i have a request to build slider image from jsonArray using volley, i don't know how to put value of jsonArray to hashmap<string, string> .. it keep saying null object
error message
Attempt to invoke virtual method 'java.lang.Object
java.util.HashMap.put(java.lang.Object, java.lang.Object)' on a null object reference
JSON array value
[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]
and then i wanna put that value like this into hashmap<string, string> inside onCreate()
HashMap<String,String> url_maps = new HashMap<>();
url_maps.put("Hannibal", "http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg");
url_maps.put("Big Bang Theory", "http://tvfiles.alphacoders.com/100/hdclearart-10.png");
url_maps.put("House of Cards", "http://cdn3.nflximg.net/images/3093/2043093.jpg");
url_maps.put("Game of Thrones", "http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg");
it gonna use for adding picture to my slider(slideshow) inside onCreate()
for(String name : url_maps.keySet()){
DefaultSliderView DefaultSliderView = new DefaultSliderView(getContext());
// initialize a SliderLayout
DefaultSliderView
.image(url_maps.get(name))
.setScaleType(BaseSliderView.ScaleType.Fit)
.setOnSliderClickListener(this);
//add your extra information
DefaultSliderView.bundle(new Bundle());
DefaultSliderView.getBundle()
.putString("extra",name);
mDemoSlider.addSlider(DefaultSliderView);
}
and i don't know how to put values from volley JsonArray, and this is my request but error saying null.
private void getSlider(){
String tag_string_req = "sliderList";
// Showing progress dialog before making http request
JsonArrayRequest mostReq = new JsonArrayRequest(AppConfig.URL_Slider, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < 5; i++) {
JSONObject jObj = response.getJSONObject(i);
url_maps.put(jObj.getString("cPID"), jObj.getString("image"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + "Error Data Occured!!" + error.getMessage());
Toast.makeText(getContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) ;
AppController.getInstance().addToRequestQueue(mostReq, tag_string_req);
}
the values request was accepted on volley, it show on Logcat .. but null on hashmap .. tell me if i got mistake in my code, sorry just newbie and still study
You are iterating thru just the keys... You need to iterate through the keys and values...
for (url_maps.Entry<String, String> url_map : url_maps.entrySet()) {
String key = url_map.getKey();
String value = url_map.getValue();
// ...
}
ANOTHER WAY TO ATTEMPT THIS IS...
to deserialize your Json into a java object...
ObjectMapper mapper = new ObjectMapper();
string StringJson = "[
{"cPID":"62001002280293829",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/rsch.jpg"},
{"cPID":"62001002020254584",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/penang.jpg"},
{"cPID":"62001002050264258",
"image":"http:\/\/ibigcreative.com\/dev\/assets\/images\/slider\/guardian.jpg"}
]";
// For the following line to work you will need to make a URLMaps Class to hold the objects
URLMaps urlMaps = mapper.readValue(StringJson , URLMaps.class);
The URLMaps Class might look like this.
public class URLMaps{
public string name = "";
public string image = "";
//constructor
public URLMaps(string a, string b) {
name = a;
image = b;
}
public string getName() {
return name;
}
public string getImage() {
return image;
}
}
Then to utilize the class you can go with:
urlMaps.getName(), or urlMaps.getValue() in your DefaultSliderView.image()
Also to note, since this is a class you can store an array of them or a list of them, so you can re-purpose your for loop...
For (URLMap urlmap : UrlMaps[]) // where URLMaps is your object that holds multiple instances of URLMaps.
Lastly, it has been a long time since I have coded in Java, so this code is untested, but should help you come to a solution.

How to extract a value from a facebook invite friends onComplete() response

I am implementing Facebook friends invite in my android app and I need to get to how many friends user sent app request so that I can award him some points.
What I have done so far is as below
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
sessiob, params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,FacebookException error) {
if (error != null) {
} else {
final String requestId = values.getString("request");
final String[] requestArr1 = values.getStringArray("to");
if (requestId != null) {
Log.e("RequestId1",requestId + "\n" + values.toString());
else {
Toast.makeText(Login.this,"Request cancelled", Toast.LENGTH_SHORT).show();
}
}
}
}).build();
And the Bundle value I am getting is Bundle[{to[0]=808411111111111,to[1]=151584774222222, request=879734911111111}]
While my above code final String requestId = values.getString("request"); working fine however values.getStringArray("to"); giving me Null.
I want to know value "to" inside the Bundle is a StringArray or not and if yes then what's wrong in my extraction process.
Check out this example you will find your all answers
Simple facebook

Categories