Adding Marker to map api v2 in AsyncTask - java

EDIT!
Not sure what I was thinking, but you can't update the UI in a background thread. oops.
How would I pass the marker add to the UI?
EDIT!
I'm trying to add markers to my map with api v2. If I add the markers in the onCreate it will work fine. If I add markers in my EndpointsTask directly below where I get the address information and convert it to lat long values it will not add the marker points.
Here is the code to add the marker:
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title("Hello world"));
Works fine when I put in actual double values in the onCreate. Does not work at all even with double values in the endpointstask (see below). In case you are wondering I sent the lati longi values to the console and it prints the lat long ok.
public class FinderActivity extends Activity implements LocationListener {
GoogleMap mMap;
Location myLocation;
EditText length;
String lengthString;
LocationManager locationmanager;
//Spinner s;
List<Address> address;
Geocoder coder = new Geocoder(this);
private static final String TAG_ID = "id";
private static final String TAG_FIRSTNAME = "nameFirst";
private static final String TAG_LASTNAME = "nameLast";
private static final String TAG_EMAIL = "emailAddress";
private static final String TAG_ADDRESS = "streetAddress";
private static final String TAG_STATE = "state";
private static final String TAG_PHONE = "phone";
JSONArray contacts = null;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap!= null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomBy(17));
}
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
Location location = locationmanager.getLastKnownLocation(provider);
locationmanager.requestLocationUpdates(provider, 20, 0, (LocationListener) this);
mMap.moveCamera(CameraUpdateFactory.newLatLng((new LatLng(location.getLatitude(), location.getLongitude()))));
//WORKS HERE
//mMap.addMarker(new MarkerOptions()
//.position(new LatLng(38.923546, -83.582954))
//.title("Hello world"));
new EndpointsTask().execute(getApplicationContext());
}
public class EndpointsTask extends AsyncTask<Context, Integer, Long> {
public Long doInBackground(Context... contexts) {
Contactinfoendpoint.Builder endpointBuilder = new Contactinfoendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Contactinfoendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
if (address == null) {
return null;
}
Address location1 = address.get(0);
double lati = location1.getLatitude();
double longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
// DOESNT WORK HERE
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title("Hello world"));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}

There are several ways but the postExecute method can solve your problem look this: how to pass the result of asynctask onpostexecute method into the parent activity android
protected void onPostExecute(Long result) {
// you can call a method of your activity
// example you can generate a list of all
// your markers and passed as param of method
// to your activity.
}

Related

get result of AsyncTask in other Method

I am trying to get the response of a servlet as text, to parse this text and extract the coordinates for showing markers on google maps. My problem is that I don't know how to call the result from onPostExecute method in the onMapReady method. Like I'm calling in my code, the input String is obviously empty.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap map;
private static final String LOG_TAG = "ExampleApp";
TextView tvIsConnected;
TextView tvResult;
TextView textView2;
private static final String SERVICE_URL = "http://192.168.178.42:8080/TutorialApp/User/GetAll";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
tvResult = (TextView) findViewById(R.id.tvResult);
textView2 = (TextView) findViewById(R.id.textView2);
// 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);
if (checkNetworkConnection())
// perform HTTP GET request
new HTTPAsyncTask().execute("http://192.168.178.42:8080/TutorialApp/User/GetAll");
}
public boolean checkNetworkConnection() {
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
boolean isConnected = false;
if (networkInfo != null && (isConnected = networkInfo.isConnected())) {
// show "Connected" & type of network "WIFI or MOBILE"
tvIsConnected.setText("Connected " + networkInfo.getTypeName());
// change background color to red
tvIsConnected.setBackgroundColor(0xFF7CCC26);
} else {
// show "Not Connected"
tvIsConnected.setText("Not Connected");
// change background color to green
tvIsConnected.setBackgroundColor(0xFFFF0000);
}
return isConnected;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line + "\n";
inputStream.close();
return result;
}
private String HttpGet(String myUrl) throws IOException {
InputStream inputStream = null;
String result = "";
URL url = new URL(myUrl);
// create HttpURLConnection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// make GET request to the given URL
conn.connect();
// receive response as inputStream
inputStream = conn.getInputStream();
// convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
return result;
}
private class HTTPAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return HttpGet(urls[0]);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
//onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
tvResult.setText(result);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
String input = tvResult.getText().toString();
String[] lines = input.split( "\n" );
List<Pair<Double, Double>> list = new ArrayList<>();
String ss="i";
for( int i =1; i < lines.length-1; i++ ) {
int firstcomma = lines[i].indexOf(",");
int secondcomma = lines[i].indexOf(",", firstcomma + 1);
int thirdcomma = lines[i].indexOf(",", secondcomma + 1);
Double lat = Double.parseDouble(lines[i].substring(secondcomma + 1, thirdcomma));
Double longitude = Double.parseDouble(lines[i].substring(thirdcomma + 1, lines.length));
list.add(new Pair(lat,longitude));
}
for(int j=1; j<list.size();j++) {
map = googleMap;
// Add a marker in Sydney and move the camera
//LatLng sydney = new LatLng(-34, 151);
LatLng sydney = new LatLng(list.get(j).first, list.get(j).second);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
}
The reason you can't call the result of onPostExecute() in onMapReady() is because they are both running in the background. The only thing that you can really do here is either call getMapAsync() from your onPostExecute(), which will ensure that your onPostExecute() has completed; or, move the functionality of the onMapReady() into the onPostExecute(). You basically have 2 asyncTasks running, so you either need to chain them (which is kind of hacky) or move the logic from onMapReady() to onPostExecute().

Asyntask #1 Android error

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));
}
}
}

How to return a class to a onPostExecute?

Update, please see below.
How do I return my class LocationData and my ArrayList listOfObjects to the onPostExecute()? I want to use it in my UI and right now it is in the background in an AsyncTask. Also I want to add markers with:
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title(name));
so that I can add each new location to the map after each loop.
Do I place the above in the onPostExecute after returning the LocationData class?
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
// test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: "
+ nameLast1);
address = coder.getFromLocationName(streetAddress1, 5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude,
String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
// WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute() {
// mMap.addMarker(new MarkerOptions()
// .position(new LatLng(lati, longi))
// .title("Hello world"));
This may seem elementary but I've created this method:
public ArrayList getLocationData() {
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
return listOfObjects;
}
within my LocationData class. I then placed LocationData.getLocationData(); with the onPostExecute and I get the LocationData can't be resolved. The code together looks like this at the moment:
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
final String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude, String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public ArrayList<LocationData> getLocationData() {
ArrayList<LocationData> listOfObjects = new ArrayList<LocationData>();
listOfObjects.add(new LocationData(lati, longi, nameFirst1));
return listOfObjects;
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
//WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute(Long result ) {
//CANT BE RESOLVED
LocationData.getLocationData();
//mMap.addMarker(new MarkerOptions()
//.position(new LatLng(lati, longi))
// .title("Hello world"));
Here are my changes based upon #Sustain recommendations. I seem to not be getting any map markers now. Anyone see anything?
public class FinderActivity extends Activity implements LocationListener {
GoogleMap mMap;
Location myLocation;
EditText length;
String lengthString;
LocationManager locationmanager;
double lati;
double longi;
String nameFirst1;
//Spinner s;
List<Address> address;
Geocoder coder = new Geocoder(this);
private static final String TAG_ID = "id";
private static final String TAG_FIRSTNAME = "nameFirst";
private static final String TAG_LASTNAME = "nameLast";
private static final String TAG_EMAIL = "emailAddress";
private static final String TAG_ADDRESS = "streetAddress";
private static final String TAG_STATE = "state";
private static final String TAG_PHONE = "phone";
JSONArray contacts = null;
private static class LocationData {
private double lat;
private double longitude;
private String name;
public LocationData(double lat, double longitude, String name) {
this.lat = lat;
this.longitude = longitude;
this.name = name;
}
public void setLat(double lat) {
this.lat = lat;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLat() {
return lat;
}
public double getLongitude() {
return longitude;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap!= null) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.zoomBy(17));
}
LocationManager locationmanager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
Location location = locationmanager.getLastKnownLocation(provider);
locationmanager.requestLocationUpdates(provider, 20, 0, (LocationListener) this);
mMap.moveCamera(CameraUpdateFactory.newLatLng((new LatLng(location.getLatitude(), location.getLongitude()))));
new EndpointsTask().execute(getApplicationContext());
}
public class EndpointsTask extends AsyncTask<Context, LocationData, Long> {
private List<LocationData> locationList = new ArrayList<LocationData>();
public Long doInBackground(Context... contexts) {
Contactinfoendpoint.Builder endpointBuilder = new Contactinfoendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Contactinfoendpoint endpoint = CloudEndpointUtils.updateBuilder(
endpointBuilder).build();
try {
String apples = endpoint.listContactInfo().execute().toString();
JSONObject jObject = new JSONObject(apples);
JSONArray jsonArr = jObject.getJSONArray("items");
for(int i =0 ; i<jsonArr.length() ;i++ ){
JSONObject jsonObj1 = jsonArr.getJSONObject(i);
// Storing each json item in variable
String id = jsonObj1.getString(TAG_ID);
String nameFirst1 = jsonObj1.getString(TAG_FIRSTNAME);
String nameLast1 = jsonObj1.getString(TAG_LASTNAME);
String emailAddress1 = jsonObj1.getString(TAG_EMAIL);
String streetAddress1 = jsonObj1.getString(TAG_ADDRESS);
String phone1 = jsonObj1.getString(TAG_PHONE);
//test to see if made it to string
Log.d("YOUR_TAG", "First Name: " + nameFirst1 + " Last Name: " + nameLast1);
address = coder.getFromLocationName(streetAddress1,5);
Address location1 = address.get(0);
// SET LAT LNG VALUES FOR MARKER POINT
lati = location1.getLatitude();
longi = location1.getLongitude();
Log.d("Location", "Location:" + lati + " " + longi);
LocationData data = new LocationData(lati, longi, nameFirst1);
locationList.add(data);
publishProgress(data);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (long) 0;
}
protected void onProgressUpdate(LocationData data) {
// Add Marker on Map using data. This is called by
// publishProgress(LocationData) on the UI Thread.
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lati, longi))
.title(nameFirst1));
Log.d("bananas", lati + longi + nameFirst1);
}
//WHAT DO I PUT HERE TO RETURN LocationData Class here
// ADD MARKER TO MAP UI
protected void onPostExecute() {
}
}
The class LocationData is defined inside an unreachable scope. Instead, define it in it's own .java file like so:
class LocationData {
// final Fields
// Constructor
// Getters
}
or as a private static class of your outermost class if you don't use it anywhere else.
Then for your subclass of AsyncTask you could have something like:
private class AsyncJsonTask extends AsyncTask<Param, LocationData, Void>
{
private List<LocationData> locationList = new ArrayList<LocationData>();
// ...
protected void doInBackground(Param) {
// ...
for (int i = 0; i < jsonArr.length(); i++) {
// Do your stuff with JSon Objects
// ...
// Instanciate a new LocationData and pass it as progress:
LocationData data = new LocationData(latitude, longitude, name);
locationList.add(data);
publishProgress(data);
}
}
protected void onProgressUpdate(LocationData data) {
// Add Marker on Map using data. This is called by
// publishProgress(LocationData) on the UI Thread.
mMap.addMarker(/* marker */);
}
protected void onPostExecute() {
// Assign outer class member field the value of the builded list
// for future reference.
mLocationList = locationList;
}
}
This way, you can publish each marker individually on the map before fetching the next one.
As a side note, you should investigate the meaning of static methods and fields; your call to LocationData.getLocationData() would not be valid.
onPostExecute runs in the UI thread. So any changes in the UX can be done here, in your case, adding markers to the map.
onPostExecute takes in the Result parameter returned from doInBackground().
You can learn more about AsyncTask from http://developer.android.com/reference/android/os/AsyncTask.html
It got a nice example as well.

Location passed from android to web always gets 999.9999

i can pass successfully my location to my web service using php and android java. but the thing is i always have 999.99999 and -999.99999 in both my longitude and latitude. Can you point to me in what part am i having mistakes.
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
private static String ILatitude;
private static String 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() * 1000000);
int longitude = (int) (location.getLongitude() * 1000000);
GeoPoint point = new GeoPoint(latitude, longitude);
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 = Integer.toString(latitude);
ILongitude = Integer.toString(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 = ILatitude;
String strLongitude = ILongitude;
// Building parameters
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("latitude", strLatitude));
params1.add(new BasicNameValuePair("longitude", strLongitude));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params1);
// 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;
}
}
}
**
Thank you in advance guys.
well i guess i don't need to post my php codes here, but if you want to check just notify me. :)
I'm guessing your numbers are exceeding the bounds of int. Try using BigInteger or perhaps the long primitive type.

GPS coordinates not properly stored in database from android to php [CLOSE]

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();

Categories