ó = A³My APP is coded in UTF-8Here is the part of the" name="description" /> ó = A³My APP is coded in UTF-8Here is the part of the" />
70922

Getting the right accentuation from Google API Geocode - Android

Question:

I am using <a href="http://maps.google.com/maps/api/geocode" rel="nofollow">http://maps.google.com/maps/api/geocode</a> to get and address from some coordinates.

When I get the Json response on the APP, any character that has accentuation comes out with a "error" ---> ó = A³

My APP is coded in UTF-8

Here is the part of the code that get's the info from the API

JSONArray results = jsonObject.getJSONArray("results"); JSONObject r = results.getJSONObject(0); JSONArray addressComponentsArray = r.getJSONArray("address_components"); JSONObject addressComponents = addressComponentsArray.getJSONObject(0); numero = addressComponents.getString("short_name"); Log.i("Número", numero); JSONObject addressComponents1 = addressComponentsArray.getJSONObject(1); rua = addressComponents1.getString("long_name"); Log.i("Rua", rua);

And here is the whole class

class EncontrarEndereco extends AsyncTask<String, String, JSONObject> { ProgressDialog pDialog = new ProgressDialog(GPSActivity.this); @Override protected void onPreExecute(){ super.onPreExecute(); pDialog.setMessage("Aguarde, enquanto buscamos seu endereço"); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } double lat = -19.971864410192393; double lng = -43.97544760674483; HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true&language=pt&region=BR"); HttpClient client = new DefaultHttpClient(); HttpResponse response; StringBuilder stringBuilder = new StringBuilder(); protected JSONObject doInBackground (String... args){ 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; } protected void onPostExecute(final JSONObject jsonObject) { // Dismiss a caixa de dialogo depois de buscar todos os items String numero; String rua; String bairro; String cidade; String estado; String pais; String endereco_compelto; pDialog.dismiss(); Log.i("JSON string =>", jsonObject.toString()); try { String status = jsonObject.getString("status"); Log.i("status", status); if(status.equalsIgnoreCase("OK")){ JSONArray results = jsonObject.getJSONArray("results"); JSONObject r = results.getJSONObject(0); JSONArray addressComponentsArray = r.getJSONArray("address_components"); JSONObject addressComponents = addressComponentsArray.getJSONObject(0); numero = addressComponents.getString("short_name"); Log.i("Número", numero); JSONObject addressComponents1 = addressComponentsArray.getJSONObject(1); rua = addressComponents1.getString("long_name"); Log.i("Rua", rua); JSONObject addressComponents2 = addressComponentsArray.getJSONObject(2); bairro = addressComponents2.getString("long_name"); Log.i("Bairro ", bairro); JSONObject addressComponents3 = addressComponentsArray.getJSONObject(3); cidade = addressComponents3.getString("long_name"); Log.i("Cidade ", cidade); JSONObject addressComponents5 = addressComponentsArray.getJSONObject(5); estado = addressComponents5.getString("short_name"); Log.i("Estado ", estado); JSONObject addressComponents6 = addressComponentsArray.getJSONObject(6); pais = addressComponents6.getString("long_name"); Log.i("Pais ", pais); endereco_compelto = rua + ", " + numero + " - " + bairro + ", " + cidade + " - " + estado + ", " + pais; endereco.setText(endereco_compelto); } }catch (JSONException e) { Log.e("testing","Failed to load JSON"); e.printStackTrace(); } } }

Answer1:

Here what solved my problem, the bit handle the Inputstream

char[] buffer = new char[2048]; Reader reader = new InputStreamReader(entity.getContent(), "UTF-8"); StringBuilder stringBuilder = new StringBuilder(); while (true) { int n = reader.read(buffer); if (n < 0) { break; } stringBuilder.append(buffer, 0, n); }

Here it is inside the whole code.

import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; /** * Created by Usuário on 05/02/2015. */ public class GPSActivity extends Activity implements LocationListener { private TextView latituteField; private TextView longitudeField; private TextView endereco; private LocationManager locationManager; private String provider; /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.gps); latituteField = (TextView) findViewById(R.id.TextView02); longitudeField = (TextView) findViewById(R.id.TextView04); endereco = (TextView) findViewById(R.id.Endereco); //Get the Location Manager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); //Define the criteria how to select location provider -> use // default Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria,false); Location location = locationManager.getLastKnownLocation(provider); // Initialize the location fields if (location != null){ System.out.println("Provider " + provider + " has been selected"); onLocationChanged(location); }else{ latituteField.setText("Locação não disponível"); longitudeField.setText("Locação não disponível"); } } /** * Request updates at startup */ @Override protected void onResume(){ super.onResume(); locationManager.requestLocationUpdates(provider, 400, 1, this); } /** * Remove the LocationListener updates when Activity is paused */ @Override protected void onPause(){ super.onPause(); locationManager.removeUpdates(this); } @Override public void onLocationChanged(Location location){ double lat = (location.getLatitude()); double lng = (location.getLongitude()); latituteField.setText(String.valueOf(lat)); longitudeField.setText(String.valueOf(lng)); // Encontrando Endereço new EncontrarEndereco().execute(); } @Override public void onStatusChanged(String provider, int status, Bundle extras){ //TODO Auto-generated method tub } @Override public void onProviderEnabled(String provider) { Toast.makeText(this, "Enabled new provider " + provider, Toast.LENGTH_SHORT).show(); } @Override public void onProviderDisabled(String provider) { Toast.makeText(this, "Disabled provider " + provider, Toast.LENGTH_SHORT).show(); } class EncontrarEndereco extends AsyncTask<String, String, JSONObject> { ProgressDialog pDialog = new ProgressDialog(GPSActivity.this); @Override protected void onPreExecute(){ super.onPreExecute(); pDialog.setMessage("Aguarde, enquanto buscamos seu endereço"); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } double lat = -19.971864410192393; double lng = -43.97544760674483; HttpGet httpGet = new HttpGet("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true&language=pt&region=BR&output=xml&oe=utf8"); HttpClient client = new DefaultHttpClient(); HttpResponse response; StringBuilder stringBuilder = new StringBuilder(); protected JSONObject doInBackground (String... args){ try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); char[] buffer = new char[2048]; Reader reader = new InputStreamReader(entity.getContent(), "UTF-8"); while (true) { int n = reader.read(buffer); if (n < 0) { break; } stringBuilder.append(buffer, 0, n); } int b; while ((b = reader.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; } protected void onPostExecute(final JSONObject jsonObject) { // Dismiss a caixa de dialogo depois de buscar todos os items String numero; String rua; String bairro; String cidade; String estado; String pais; String endereco_compelto; pDialog.dismiss(); Log.i("JSON string =>", jsonObject.toString()); try { String status = jsonObject.getString("status"); Log.i("status", status); if(status.equalsIgnoreCase("OK")){ JSONArray results = jsonObject.getJSONArray("results"); JSONObject r = results.getJSONObject(0); JSONArray addressComponentsArray = r.getJSONArray("address_components"); JSONObject addressComponents = addressComponentsArray.getJSONObject(0); numero = addressComponents.getString("short_name"); Log.i("Número", numero); JSONObject addressComponents1 = addressComponentsArray.getJSONObject(1); rua = addressComponents1.getString("long_name"); Log.i("Rua", rua); JSONObject addressComponents2 = addressComponentsArray.getJSONObject(2); bairro = addressComponents2.getString("long_name"); Log.i("Bairro ", bairro); JSONObject addressComponents3 = addressComponentsArray.getJSONObject(3); cidade = addressComponents3.getString("long_name"); Log.i("Cidade ", cidade); JSONObject addressComponents5 = addressComponentsArray.getJSONObject(5); estado = addressComponents5.getString("short_name"); Log.i("Estado ", estado); JSONObject addressComponents6 = addressComponentsArray.getJSONObject(6); pais = addressComponents6.getString("long_name"); Log.i("Pais ", pais); endereco_compelto = rua + ", " + numero + " - " + bairro + ", " + cidade + " - " + estado + ", " + pais; endereco.setText(endereco_compelto); } }catch (JSONException e) { Log.e("testing","Failed to load JSON"); e.printStackTrace(); } } } }

Recommend

  • setMaxForRoute does not work in ThreadSafeClientConnManager
  • calling rest web service?
  • org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
  • How to determine how long a song is using winmm.dll?
  • Android: How to make my retrieved (from mysql) JSON parsed data added to ListView refresh it self ev
  • Merge duplicates list of dictionaries item value
  • Mocked HttpRequest loses the QueryString
  • Faster implementation for reduceByKey on Seq of pairs possible?
  • C# Rijndael decryption returns extra question mark character
  • Creating a database programatically in nlog to enable using DatabaseTarget
  • Openejb rest integration tests with exception mappers
  • Android json parse not working
  • How to create a waiting page in Django
  • EclEmma, Java8 and Lambda - no coverage on lambda expression
  • C# Getting window's title by handle in Hebrew return question marks
  • Timezone display value with GMT offset from a given timezone?
  • ElasticSearch and Apache HttpAsyncClient
  • java use Regular Expressions to generate a string [duplicate]
  • Why is JSON.NET adding all these backslashes
  • angularjs ng-bind-html html input part missing
  • how to avoid the dependencies hell with unit test in angular 2+
  • WSO2 ESB 4.0.3 - Error installing Data Services feature from 4.0.* repositories
  • Zend Framework 2, Module Redirect
  • How to make http call with file in groovy to upload a file and build arguments
  • Why does PHP appear to evaluate this condition incorrectly?
  • Contact form problem - I do receive messages, but no contents (blank page)
  • Python: sending key press events over SSH
  • Error in making a socket connection
  • How to Save JSON data to SQL server database in C#?
  • What is the difference between a “service account” and an “installed application”?
  • Problem with Django using Apache2 (mod_wsgi), Occassionally is “unable to import from module” for no
  • Python pandas melting data to multiple columns and coulmn names in another column
  • Sending cookie value via httpget but not getting the desired response
  • what makes a request a new request in asp.net C#
  • Spring Cloud Microservice Architecture Confusion
  • Transactional Create with Validation in ServiceStack Redis Client
  • Handling un-mapped Rest path
  • Seeking advice on Jetty HttpClient Hang
  • PHP - How to update data to MySQL when click a radio button
  • To Get the radio button value in ruby on rails