Boa tarde,
Estou desenvolvendo uma aplicação para Android onde preciso buscar em um banco MySQL as posições de Latitude e Longitude e exibir um Overlay na tela. O Debug do Eclipse não me mostra o valor que está sendo trazido na consulta no momento em que atribuo seu valor para uma variável, mas testei em um projeto onde fazia somente isso e o resultado está correto. Segue o código em que faço a chamada da query e atribuo para uma variável:
package org.ci.geo.route;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import android.graphics.Point;
import org.ci.geo.route.Conexao;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
public class HutsItemizedOverlay extends ItemizedOverlay<OverlayItem> {
Conexao conn = new Conexao();
public HutsItemizedOverlay(Drawable defaultMarker) {
super(defaultMarker);
// change the direction of the shadow so the bottom of the marker is the part "touching"
boundCenterBottom(defaultMarker);
//static data, so we call this right away
populate();
}
@Override
public GeoPoint getCenter() {
Integer averageLat = 0;
Integer averageLon = 0;
for (GeoPoint point : hutPoints) {
averageLat += point.getLatitudeE6();
averageLon += point.getLongitudeE6();
}
averageLat /= hutPoints.length;
averageLon /= hutPoints.length;
return new GeoPoint(averageLat, averageLon);
}
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, false);
}
/* public GeoPoint hutPoints[] = new GeoPoint[] {
new GeoPoint(-25434516,-49316518),
new GeoPoint(-25447305,-49307184),
};*/
public GeoPoint hutPoints[] = new GeoPoint[] {
new GeoPoint(((int) (conn.queryLatitude()*1E6)),((int) (conn.queryLongitude()*1E6))),//aqui é onde atribuo o valor trazido da query para a criação do GeoPoint
};
@Override
protected OverlayItem createItem(int i) {
OverlayItem item = new OverlayItem(hutPoints[i], "NomeLocal", "PromocaoDetalhe");
return item;
}
@Override
public int size() {
return hutPoints.length;
}
public boolean onTap(GeoPoint geoPoint, MapView mapView) {
OverlayItem item = this.createItem(1);
Point point = mapView.getProjection().toPixels(geoPoint, null);
RectF rectF = new RectF(point.x-5,point.y-5,point.x+5,point.y+5);
boolean pontoClicado = rectF.contains(point.x,point.y);
if(pontoClicado){
Toast.makeText(mapView.getContext(), "Você clicou aqui: "+ item.getTitle() + "Acesse " + item.getSnippet(), Toast.LENGTH_LONG).show();
return true;
}
return super.onTap(geoPoint, mapView);
}
}
A classe da conexão é esta:
package org.ci.geo.route;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Conexao {
private Connection conectar() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
return DriverManager.getConnection(
"jdbc:mysql://localhost/mapa", "root", "admin");
} catch (SQLException ex) {
System.err.println("SQLState: " + ex.getSQLState());
System.err.println("VendorError: " + ex.getErrorCode());
System.err.println("SQLException: ");
ex.printStackTrace();
throw new RuntimeException(ex);
} catch (Exception e) {
System.err.println("Problemas ao tentar conectar com o banco de dados: ");
e.printStackTrace();
throw new RuntimeException(e);
}
}
public double queryLatitude() {
Connection conn = conectar();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement("SELECT latitude FROM localizacao LIMIT 1;");
rs = stmt.executeQuery();
if (!rs.next()) //Não há latitude a retornar
return -1;
return rs.getDouble("latitude");
} catch (Exception erro) {
throw new RuntimeException(erro);
} finally {
//Fecha o statement, o resultset e a conexão
if (rs != null) try { rs.close(); } catch (Exception e) {}
if (stmt != null) try { stmt.close(); } catch (Exception e) {}
try { conn.close(); } catch (Exception e) {}
}
}
public double queryLongitude() {
Connection conn = conectar();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement("SELECT longitude FROM localizacao LIMIT 1;");
rs = stmt.executeQuery();
if (!rs.next()) //Não há latitude a retornar
return -1;
return rs.getDouble("longitude");
} catch (Exception erro) {
throw new RuntimeException(erro);
} finally {
//Fecha o statement, o resultset e a conexão
if (rs != null) try { rs.close(); } catch (Exception e) {}
if (stmt != null) try { stmt.close(); } catch (Exception e) {}
try { conn.close(); } catch (Exception e) {}
}
}
}
E a classe principal é esta:
package org.ci.geo.route;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class MapRouteActivity extends MapActivity implements LocationListener{
LinearLayout linearLayout;
MapView mapView;
private Road mRoad;
private MapController controller;
private MeuOverlay overlay;
private LocationManager locationManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
Button botOk = (Button)findViewById(R.id.buttonOk);
Button botInicio = (Button)findViewById(R.id.buttonInicio);
// O LocationManager vai registrar e desregistrar
// a classe para ouvir eventos do GPS
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
controller = mapView.getController();
controller.setZoom(12);
// Cria a imagem que vai representar o Overlay da Posição do GPS
Bitmap marcador = BitmapFactory.decodeResource(getResources(), R.drawable.gps);
// Cria o Overlay da Posicao do GPS e adiciona ao mapView
overlay = new MeuOverlay(marcador);
mapView.getOverlays().add(overlay);
// Determinando um ponto inicial
int latitude = (int)(-25.423121 * 1E6);
int longitude = (int)(-49.273396 * 1E6);
GeoPoint geopoint = new GeoPoint(latitude, longitude);
controller.setCenter(geopoint);
overlay.setGeopoint(geopoint);
botOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new Thread() {
EditText edOrigem = (EditText)findViewById(R.id.editTextOrigem);
EditText edDestino = (EditText)findViewById(R.id.editTextDestino);
public String origem = URLEncoder.encode(edOrigem.getText().toString());
public String destino= URLEncoder.encode(edDestino.getText().toString());
@Override
public void run() {
String url = RoadProvider
.getUrl(origem,destino);
InputStream is = getConnection(url);
mRoad = RoadProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}}.start();
}
});
botInicio.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Drawable marker = getResources().getDrawable(R.drawable.ponto);
HutsItemizedOverlay huts = new HutsItemizedOverlay(marker);
List<Overlay> overlays = mapView.getOverlays();
overlays.add(huts);
mapView.setBuiltInZoomControls(true);
final MapController mapControl = mapView.getController();
mapControl.setCenter(huts.getCenter());
mapControl.zoomToSpan(huts.getLatSpanE6(), huts.getLonSpanE6());
}
});
}
Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
TextView textView = (TextView) findViewById(R.id.description);
textView.setText(mRoad.mName + " " + mRoad.mDescription);
MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
};
};
private InputStream getConnection(String url) {
InputStream is = null;
try {
URLConnection conn = new URL(url).openConnection();
is = conn.getInputStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
@Override
protected void onResume() {
super.onResume();
// Registrando a Activity para receber notificações
// de mudança na posição GPS
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
@Override
protected void onPause() {
super.onPause();
// Desregistrando a Activity para receber
// notificações de mudança na posição GPS
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
// Método chamado quando a posição GPS muda
int latitude = (int)(location.getLatitude() * 1E6);
int longitude = (int)(location.getLongitude() * 1E6);
GeoPoint geopoint = new GeoPoint(latitude, longitude);
overlay.setGeopoint(geopoint);
controller.animateTo(geopoint);
}
public void onProviderDisabled(String provider) {
// Método chamado quando o GPS é desabilitado
}
public void onProviderEnabled(String provider) {
// Método chamado quando o GPS é habilitado
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
// Método chamado quando o status do GPS muda.
// Pode ser: OUT_OF_SERVICE,
// TEMPORARILY_UNAVAILABLE e AVAILABLE
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
}
Alguém pode me ajudar?