I have a main activity which parses the JSON data from my mysql (table tracking:Lattitude and longitude) Now I want to pass this data in to my MapActivity and display on google maps. Any help is highly appreciated. Thanks!
this my JSONactivity
public class JSONActivity extends Activity{
private JSONObject jObject;
private String xResult ="";
//Seusuaikan url dengan nama domain
private String url = "http://10.0.2.2/labiltrack/daftartracking.php";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.daftartrack);
TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
//url += "?lattitude=" + UserData.getEmail();
xResult = getRequest(url);
try {
parse(txtResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(TextView txtResult) throws Exception {
// TODO Auto-generated method stub
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("joel");
String sret="";
//int j = 0;
for (int i = 0; i < menuitemArray.length(); i++) {
sret +=menuitemArray.getJSONObject(i).
getString("lattitude").toString()+" : ";
System.out.println(menuitemArray.getJSONObject(i)
.getString("lattitude").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"longitude").toString());
sret +=menuitemArray.getJSONObject(i).getString(
"lattitude").toString()+"\n";
//j=i;
}txtResult.setText(sret);
}
/**
* Method untuk Mengirimkan data keserver
* event by button login diklik
*
* #param view
*/
private String getRequest(String url) {
// TODO Auto-generated method stub
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"jo "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
/**
* Method untuk Menenrima data dari server
* #param response
* #return
*/
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
}
and this my mapActivity
public class mapactivity extends MapActivity {
private MapView mapView;
MapController mc;
GeoPoint p;
//private MyLocationOverlay me = null;
class MapOverlays extends com.google.android.maps.Overlay
{
#Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//translate the geopoint to screen pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//tambah marker
Bitmap bmp = BitmapFactory.decodeResource(getResources (), R.drawable.pin_red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
//mapView.setSatellite(true);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
mc.animateTo(p);
//geocoding
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
} }
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview1);
//utk mnampilkan zoom
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mapView.displayZoomControls(true);
//menampilkan default peta banda aceh
mc = mapView.getController();
String coordinates[] = {"5.550381", "95.318699"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(14);
mapView.invalidate();
//tambah marker
MapOverlays mapOverlay = new MapOverlays();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
public void btnSatelitClick(View v){
mapView.setSatellite(true);
mapView.setStreetView(false);
}
public void btnjalanClick (View v){
mapView.setSatellite(false);
mapView.setStreetView(true);
}
protected boolean isRouteDisplayed()
{
//auto generate method
return false;
}
}
my jsonactivity is get data from mysql (field "latitude" and "longitude") into listview, but now I want to display that data (latitude and longitude) on google map, How Could I do this ?
please help me, thanks in advance !
You need to get bundle from another class : this class will be for your mapActivity
Bundle b = getIntent().getExtras(); // Getting the Bundle object that pass from another activity
int SelectedPropertylat = b.getInt("SelectedLat");
int SelectedPropertylong = b.getInt("SelectedLong");
String lattitude = Integer.toString(SelectedPropertylat);
String longertude = Integer.toString(SelectedPropertylong);
Log.d(lattitude,longertude);
And taking datafrom mysql into your apps use this :
try{
JSONArray earthquakes = json.getJSONArray("PropertyDetails");
for(int i=0;i<earthquakes.length();i++){
JSONObject e = earthquakes.getJSONObject(i);
lat = e.getString("P_Lat");
lonng = e.getString("P_Long");
then convert lat and long into an string like :
lonnng = Integer.parseInt(lonng.toString());
latt =Integer.parseInt(lat.toString());
then pass the data into your mapview like this :
Intent moreDetailsIntent = new Intent(PropertiesDetails.this,mapActivity .class);
Bundle dataBundle = new Bundle();
dataBundle.putInt("SelectedLong",lonnng);
dataBundle.putInt("SelectedLat", latt);
moreDetailsIntent.putExtras(dataBundle);
startActivity(moreDetailsIntent);
Related
I am making a simple weather app and i have a problem with reading variables by aSyncTask. I am very beginner in programming for andorid, so I am asking for understanding. So, i want to put variables "latitude" and "longitude" choosen from place picker into asyncTask.execute("Latitude", "Longitude") and refresh a screen to show weather for new location. Now it dosent work, but i noticed, that when i put coordinates in code not by variables (for ex. asyncTask.execute("52.2296756", "38,3435546") then weather for this location appears after using Place Picker. I have also added outprint to check this varibles, and they looks okay.
public class MainActivity extends AppCompatActivity {
TextView cityField, detailsField, currentTemperatureField,
humidity_field, pressure_field, weatherIcon, updatedField;
ImageView mPlacePicker;
Typeface weatherFont;
int PLACE_PICKER_REQUEST = 1;
String latitude;
String longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
mPlacePicker = (ImageView) findViewById(R.id.place_picker);
mPlacePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PlacePicker.IntentBuilder builder = new
PlacePicker.IntentBuilder();
Intent intent;
try {
intent = builder.build(MainActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent
data) {
if (requestCode == PLACE_PICKER_REQUEST) {
if (resultCode == RESULT_OK) {
Place place = PlacePicker.getPlace(this, data);
String address = String.format("Place %s", place.getAddress());
Toast.makeText(this, address, Toast.LENGTH_LONG).show();
LatLng latLng = place.getLatLng();
latitude = String.valueOf(latLng.latitude);
longitude = String.valueOf(latLng.longitude);
//System.out.println(latitude);
//System.out.println(longitude);
}
}
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
weatherIcon = (TextView) findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
mPlacePicker = (ImageView) findViewById(place_picker);
Function.placeIdTask asyncTask = new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
System.out.println('"' + latitude + '"');
System.out.println('"' + longitude + '"');
asyncTask.execute('"' + latitude + '"', '"' + longitude + '"'); // asyncTask.execute("Latitude", "Longitude")
}
}
And this is second class with doInBackground
public class Function {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";
private static final String OPEN_WEATHER_MAP_API = "3b30fbc239f6a1ed664220635330aa46";
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
public placeIdTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON(params[0], params[1]);
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
String iconText = setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
}
}
public static JSONObject getWeatherJSON(String lat, String lon){
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
}
}
Remove the extra "". You don't need those e.g.
asyncTask.execute(latitude,longitude);
you can use a constructor for your class AsyncTask
something like this :
class placeIdTask extends AsynckTask<Void,Void,Void>{
Double latitude;
Double longitude;
public placeIdTask(Double latitude, Double longitude){
this.latitude = latitude;
this.longitude=longitude;
}
...//implement doInbackground using latitude and longitude
}
or
just you change the type of generic CLass like this
class placeIdTask extends AsynckTask<Double,Void,Void>{
#Override
protected Void doInBackground(Double... arg0) {
Double latitude = arg0[0];
Double longitude = arg0[1];
... }
... }
and I suggest u to use Double instead of String
hope that help you
//Add async task
private class SampleAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// this might take a while ...
// Do your task over here
// Use parameterlike this
latitude=params[0];
longitude=params[1];
return "Success";
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
//Call asyc task
new SampleAsyncTask().execute(String.valueOf(latitude),String.valueOf(longitude));
Hope this help you. Happy coding
EDIT: Found the solution to my problem.
The json string output returned the wrong url for my local images.
i am barely new to android and struggle with asyncTask.
What i want is to get the corresponding image to a marker on a map.
every entry on this map has its own image which has to be loaded from server via json.
the image load works fine but i dont get the right workflow to get the image i need for one entry.
by now i have one solution to load an async task in a for-loop, but this cant be the right way because the app refuses to go on after 43 tasks and stops with
"ECONNECTION TIMEOUT"
so how can get the asynctask out of the loop?
hope anyone can help? thank you!
here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
public class MapImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
String url, userId, contentId, title;
LatLng location;
BufferedReader reader = null;
public MapImageLoadTask(String url, String userId, String contentId, String title, LatLng location) {
this.url = url;
this.userId = userId;
this.contentId = contentId;
this.title = title;
this.location = location;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(title).position(location).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
hashMap.put(m, contentId);
}
}
}
Your problem maybe AsyncTask limitations. In android.os.AsyncTask.java you will see core size and blockingqueue size(128), should use counter for asynctask and debug it(Problem is, lots of async tasks or other).
AsyncTask.java
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
...}
Change Your Code Use Buffer(RequestData) And Use Only One Async Task. Update Market instance every publishProgress in onProgressUpdate
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
List<RequestData> datas = new ArrayList<RequestData>();
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
RequestData data = new RequestData();
data.url = "http://192.168.63.35:1234/rest_app_users/getImage/";
data.userId = userId;
data.contentId = contentId;
data.contentTitle = contentTitle;
data.latlng = latlng;
datas.add(data);
//new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
new MapImageLoadTask(datas).execute();
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
static class RequestData{
public String url;
public String userId;
public String contentId;
public String contentTitle;
public LatLng latLng;
public Bitmap bmp;
}
public class MapImageLoadTask extends AsyncTask<Void, RequestData, Void> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
BufferedReader reader = null;
List<RequestData> dataSet;
public MapImageLoadTask(List<RequestData> dataSet) {
this.dataSet = dataSet;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
for(RequestData item : dataSet){
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//
item.bmp = bmp;
publishProgress(item);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPublishProgress(RequestData item){
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(item.title).position(item.location).icon(BitmapDescriptorFactory.fromBitmap(item.bmp)));
hashMap.put(m, contentId);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
I am a newbie in android and here is my code, the problem is this code is not able to draw the path on the map.
This my main activity
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import org.w3c.dom.Document;
import java.util.ArrayList;
public class servicing extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
protected GoogleMap mMap;
String lang = "english";
String test = "test";
protected LocationManager locationManager;
Route route = new Route();
LatLng latLng1 = new LatLng(26.903291,75.792482);
LatLng latLng2 = new LatLng(26.907708,75.806044);
ArrayList<LatLng> points = new ArrayList<>(2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_servicing);
//GMapV2Direction md = new GMapV2Direction();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
/*Document doc = md.getDocument(latLng1, latLng2,
GMapV2Direction.MODE_DRIVING);
ArrayList<LatLng> directionPoint = md.getDirection(doc);
PolylineOptions rectLine = new PolylineOptions().width(3).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
Polyline polylin = mMap.addPolyline(rectLine);*/
points.add(latLng1);
points.add(latLng2);
route.drawRoute(mMap, this, points, true, lang, false);
Toast.makeText(getApplicationContext(),driverdata.extrastmt,Toast.LENGTH_LONG).show();
//route.drawRoute(mMap,this,latLng1,latLng2,lang);
}
#Override
public void onMapReady(GoogleMap googleMap){
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom((latLng1),15);
mMap.animateCamera(cameraUpdate);
//route.drawRoute(mMap, this, points, true, lang, false);
}
#Override
public void onProviderEnabled(String provider) {
(Toast.makeText(getApplication(), "Reconnecting", Toast.LENGTH_LONG)).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplication(),"Connection Failed! Check Network!",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude", "status");
}
#Override
public void onLocationChanged(Location location) {
Log.d("Latitude", "status");
}
}
And this my route class
public class Route {
GoogleMap mMap;
Context context;
String lang;
static String LANGUAGE_SPANISH = "es";
static String LANGUAGE_ENGLISH = "en";
static String LANGUAGE_FRENCH = "fr";
static String LANGUAGE_GERMAN = "de";
static String LANGUAGE_CHINESE_SIMPLIFIED = "zh-CN";
static String LANGUAGE_CHINESE_TRADITIONAL = "zh-TW";
static String TRANSPORT_DRIVING = "driving";
static String TRANSPORT_WALKING = "walking";
static String TRANSPORT_BIKE = "bicycling";
static String TRANSPORT_TRANSIT = "transit";
public boolean drawRoute(GoogleMap map, Context c, ArrayList<LatLng> points, boolean withIndications, String language, boolean optimize)
{
mMap = map;
context = c;
lang = language;
if(points.size() == 2)
{
String url = makeURL(points.get(0).latitude,points.get(0).longitude,points.get(1).latitude,points.get(1).longitude,"driving");
new connectAsyncTask(url,withIndications).execute();
return true;
}
else if(points.size() > 2)
{
String url = makeURL(points,"driving",optimize);
new connectAsyncTask(url,withIndications).execute();
return true;
}
return false;
}
private String makeURL (ArrayList<LatLng> points, String mode, boolean optimize){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append( points.get(0).latitude);
urlString.append(',');
urlString.append(points.get(0).longitude);
urlString.append("&destination=");
urlString.append(points.get(points.size()-1).latitude);
urlString.append(',');
urlString.append(points.get(points.size()-1).longitude);
urlString.append("&waypoints=");
if(optimize)
urlString.append("optimize:true|");
urlString.append( points.get(1).latitude);
urlString.append(',');
urlString.append(points.get(1).longitude);
for(int i=2;i<points.size()-1;i++)
{
urlString.append('|');
urlString.append( points.get(i).latitude);
urlString.append(',');
urlString.append(points.get(i).longitude);
}
urlString.append("&sensor=true&mode="+mode);
return urlString.toString();
}
private String makeURL (double sourcelat, double sourcelog, double destlat, double destlog,String mode){
StringBuilder urlString = new StringBuilder();
if(mode == null)
mode = "driving";
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString
.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString
.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode="+mode+"&alternatives=true&language="+lang);
return urlString.toString();
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng( (((double) lat / 1E5)),
(((double) lng / 1E5) ));
poly.add(p);
}
return poly;
}
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
boolean steps;
connectAsyncTask(String urlPass, boolean withSteps){
url = urlPass;
steps = withSteps;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
driverdata.extrastmt = result;
drawPath(result, steps);
//makeT(result);
}else{
driverdata.extrastmt="null";
}
}
}
private void drawPath(String result, boolean withSteps) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
Polyline line = mMap.addPolyline(new PolylineOptions()
.add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(4)
.color(Color.BLUE).geodesic(true));
}
if(withSteps)
{
JSONArray arrayLegs = routes.getJSONArray("legs");
JSONObject legs = arrayLegs.getJSONObject(0);
JSONArray stepsArray = legs.getJSONArray("steps");
//put initial point
for(int i=0;i<stepsArray.length();i++)
{
Step step = new Step(stepsArray.getJSONObject(i));
mMap.addMarker(new MarkerOptions()
.position(step.location)
.title(step.distance)
.snippet(step.instructions)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
}
}
catch (JSONException e) {
}
}
/**
* Class that represent every step of the directions. It store distance, location and instructions
*/
private class Step
{
public String distance;
public LatLng location;
public String instructions;
Step(JSONObject stepJSON)
{
JSONObject startLocation;
try {
distance = stepJSON.getJSONObject("distance").getString("text");
startLocation = stepJSON.getJSONObject("start_location");
location = new LatLng(startLocation.getDouble("lat"),startLocation.getDouble("lng"));
try {
instructions = URLDecoder.decode(Html.fromHtml(stepJSON.getString("html_instructions")).toString(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and finally JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
URL urlnew = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urlnew.openConnection();
is = new BufferedInputStream(urlConnection.getInputStream());
} catch (UnsupportedEncodingException 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");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.d("JSON_RUTA", json);
return json;
}
}
Please I need assistance, and moreover it fetches the data but on the map activity i.e, servicing activity the toast delivers nothing, once you press back and then again on button to start servicing activity, the toast delivers previous results, but no route can be seen on map.
I found solution, basically, I was calling route.drawroute(), before adding the points to the list, so it was returning null.
NEW VERSION 1.1
Hi guys. I tried to follow your recommendations and now i'm trying to redo the code.
I added this part of the code to work on the Main Thread the GoogleMaps markers.
The problem is, when i call the Ubic() function, i get this error:
http://i.imgur.com/QD7JZjRh.jpg
http://i.imgur.com/xvzJ9ckh.jpg
This is the code that i added an the error is caused by String Latlon[][] = com.Ubic();
public class BuscarContrincantes extends FragmentActivity implements
LocationListener {
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
double latitud;
double longitud;
String nombre;
Datos com = new Datos();
String latlon[][] = com.Ubic(); //HERE IS THE PROBLEM!
for (int i = 0; i < latlon.length - 1; i++) {
latitud = Double.parseDouble(latlon[i][0]);
longitud = Double.parseDouble(latlon[i][3]);
nombre = (latlon[i][2]);
LatLng posicion = new LatLng(latitud, longitud);
googlemapa.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icono_canchas))
.position(posicion).title(nombre));
}
}
VERSION 1.0
I'm having a problem with a project that i'm doing for my college.
Actually, i'm trying to set a Marker on a Map (With Google Maps) that his information is on a MySQL Database.
The code is:
BuscarContrincantes.java
public class BuscarContrincantes extends FragmentActivity implements
LocationListener {
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
new RetreiveFeedTask().execute();
}
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
double lat;
double lon;
String nombre;
Datos com = new Datos(); // File Datos.java
String latlon[][] = com.Ubic();
for (int i = 0; i < latlon.length - 1; i++) {
lat = Double.parseDouble(latlon[i][0]);
lon = Double.parseDouble(latlon[i][4]);
nombre = (latlon[i][2]);
LatLng pos3 = new LatLng(lat, lon);
googlemapa.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icono_canchas))
.position(pos3).title(nombre));
}
return null;
}
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}}
Datos.java
public class Datos {
public String[][] Ubic() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://MY.IP/FOLDER/QUERY.php");
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
JSONObject object = new JSONObject(jsonResult);
JSONArray arr = object.getJSONArray("products");
String[] lat = new String[arr.length()+1];
String[] lon = new String[arr.length()+1];
String[] nombre = new String[arr.length() + 1];
String[][] latlon = new String[arr.length() + 1][5];
for (int i = 0; i < arr.length(); i++) {
lat[i] = arr.getJSONObject(i).getString("latitude");
lon[i] = arr.getJSONObject(i).getString("longitude");
name[i] = arr.getJSONObject(i).getString("name");
latlon[i][0] = lat[i];
latlon[i][6] = lon[i];
latlon[i][2] = name[i];
}
return latlon;
} catch (JSONException e) {
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
private static String parse(String string) {
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
}
return answer;
}}
This code is trying to get Latitude, Longitude and Name of an object that is on a MySQL Database and must put this object on the Map, but i'm getting the AsynkTask #1 Error and i don't know why this is happening.
¿Can you help me, please? I'm getting really mad with this code and i don't know why this isn't working.
P.S: Sorry for my bad English. I'm from Chile :P
You can not access the GoogleMap instance at doInBackground method. The GoogleMap can only be read and modified from the main thread. Just the HTTP request shall be on background task.
You need to modify doInBackground to return the list of coordinates and implement the GoogleMap update at onPostExecute method (at main thread).
Here is the code based on Version 1.1:
GoogleMap googlemapa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.buscarcontrincante);
SupportMapFragment maps = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googlemapa = maps.getMap();
googlemapa.setMyLocationEnabled(true);
googlemapa.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googlemapa.getUiSettings().setCompassEnabled(true);
googlemapa.getUiSettings().setZoomControlsEnabled(true);
googlemapa.getUiSettings().setAllGesturesEnabled(true);
new RetreiveFeedTask().execute();
}
class RetreiveFeedTask extends AsyncTask<Void, Void, String[][]> {
#Override
protected String[][] doInBackground(Void... args) {
// Execute the HTTP request on background task
Datos com = new Datos(); // File Datos.java
return com.Ubic();
}
#Override
protected void onPostExecute(String[][] latlon) {
double latitud;
double longitud;
String nombre;
// Update the UI
for (int i = 0; i < latlon.length - 1; i++) {
latitud = Double.parseDouble(latlon[i][0]);
longitud = Double.parseDouble(latlon[i][3]);
nombre = (latlon[i][2]);
LatLng posicion = new LatLng(latitud, longitud);
googlemapa.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.icono_canchas)).position(posicion).title(nombre));
}
}
}
do you have any idea why my coordinates keeps changing to xxx.000000 when im storing it to my database. before, it is working properly but when i keep testing it, it's not saving my coordinates properly.
For example i want to store 120.993235 and 14.612364, and then when it's on the database in converts to 120.000000 and 14.000000. Can you help me guys. these are my codes.
**
public class LocationGetter extends MapActivity implements LocationListener { // <1>
private static final String TAG = "LocationActivity";
LocationManager locationManager; // <2>
Geocoder geocoder; // <3>
TextView locationText;
MapView map;
MapController mapController; // <4>
// ** This declarations was for passing of data to web service
// Progress Dialog
private ProgressDialog pDialog;
// JSONParser Object creation
JSONParser jsonParser = new JSONParser();
// url to pass location to web
// private static String url_create_product =
// "http://student-thesis.netii.net/location_adding.php";
private static String url_create_product = "http://10.0.2.2/TheCalling/location_adding.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
//Latitude and Longitude
public static double ILatitude;
public static double ILongitude;
// ** End
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
locationText = (TextView) this.findViewById(R.id.lblLocationInfo);
map = (MapView) this.findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
mapController = map.getController(); // <4>
mapController.setZoom(19);
locationManager = (LocationManager) this
.getSystemService(LOCATION_SERVICE); // <2>
geocoder = new Geocoder(this); // <3>
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER); // <5>
if (location != null) {
Log.d(TAG, location.toString());
this.onLocationChanged(location); // <6>
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
60000, 5, this); // <7>
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this); // <8>
}
#Override
public void onLocationChanged(Location location) { // <9>
Log.d(TAG, "onLocationChanged with location " + location.toString());
String text = String.format(
"Lat:\t %f\nLong:\t %f\nAlt:\t %f\nBearing:\t %f \n",
location.getLatitude(), location.getLongitude(),
location.getAltitude(), location.getBearing());
this.locationText.setText(text);
try {
List<Address> addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 10); // <10>
for (Address address : addresses) {
this.locationText.append(" " + address.getAddressLine(0));
}
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
int GLatitude = (int) (location.getLatitude() * 1000000);
int GLongitude = (int)(location.getLongitude() * 1000000);
GeoPoint point = new GeoPoint(GLatitude, GLongitude);
mapController.animateTo(point); // <11>
List<Overlay> mapOverlays = map.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.reddot);
AddItemizedOverlay itemizedOverlay = new AddItemizedOverlay(
drawable, this);
OverlayItem overlayitem = new OverlayItem(point, "Hello",
"Sample Overlay item");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
ILatitude = (double)latitude;
ILongitude = (double)longitude;
new phpconnect().execute();
} catch (IOException e) {
Log.e("LocateMe", "Could not get Geocoder data", e);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class phpconnect extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
String strLatitude = Double.toString(ILatitude);
String strLongitude = Double.toString(ILongitude);
// Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("latitude", strLatitude));
params.add(new BasicNameValuePair("longitude", strLongitude));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
**
Here you set all values after . to zero.
int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());
And this:
ILatitude = (double)latitude;
ILongitude = (double)longitude;
won't return the zeroed values.
You can try instead:
ILatitude = location.getLatitude();
ILongitude = location.getLongitude();