I am trying to get the latitude, longitude, current address, current speed and send to the server for every 5 min. I can get the lat, long, address. But I can not get the current speed from location.getSpeed().
Herewith I have attached my entire code. Please review and give me your valuable suggestions to resolve my problem
public class MainActivity extends FragmentActivity implements LocationListener {
private GoogleMap googleMap;
private LocationManager locationManager;
private String provider;
Location location;
UserSessionManager session;
private Handler customHandler = new Handler();
String currentdatetime_tosend, latitude_tosend, logitude_tosend,
address_tosend, speed_tosend, username_tosend, startTime_tosend;
Boolean isInternetAvail = false;
ConnectionCheck conChk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle(GlobalConstants.loginDriverName);
System.out.println("GlobalConstants.loginDriverName==> "+GlobalConstants.loginDriverName);
session = new UserSessionManager(getApplicationContext());
try {
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
conChk = new ConnectionCheck(getApplicationContext());
GetLocaion();
} catch (Exception e) {
e.printStackTrace();
}
}
private void AddMarker(double latitude, double longitude, String driverName) {
googleMap.clear();
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title(driverName);
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.driver_car));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(latitude, longitude)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Double lat = (Double) (location.getLatitude());
Double lng = (Double) (location.getLongitude());
speed_tosend = Float.toString(location.getSpeed());
Toast.makeText(getApplicationContext(),
"Speed==> " + speed_tosend.toString() + "",
Toast.LENGTH_SHORT).show();
latitude_tosend = lat.toString();
logitude_tosend = lng.toString();
getAddress();
AddMarker(lat, lng, GlobalConstants.loginDriverName);
if (conChk.isConnectingToInternet())
new SendDetailsInBackground().execute();
} else
Toast.makeText(getApplicationContext(),
"Getting Location.. Please Wait..", Toast.LENGTH_SHORT)
.show();
}
private void BackgroundProcess() {
customHandler.postDelayed(updateTimerThread, 0);
}
private Runnable updateTimerThread = new Runnable() {
public void run() {
GetLocaion();
customHandler.postDelayed(this, 30000);
}
};
private void StartTheProcess() {
BackgroundProcess();
}
private void StopGetingLocation() {
customHandler.removeCallbacks(updateTimerThread);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
private void GetLocaion() {
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
Toast.makeText(getApplicationContext(), "Location Activated",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"No location found..!!", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getApplicationContext(), "GPS IS Ennabled..!!",
Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.startGettingLocation) {
startTime_tosend = getDateTime();
StartTheProcess();
return true;
}
if (id == R.id.stopGetingLocation) {
StopGetingLocation();
return true;
}
if (id == R.id.logout) {
exit();
}
return super.onOptionsItemSelected(item);
}
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
class SendDetailsInBackground extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("currentdatetime",
startTime_tosend));
params.add(new BasicNameValuePair("driver_mobile",
GlobalConstants.loginDriverNumber));
params.add(new BasicNameValuePair("username",
GlobalConstants.loginDriverName));
params.add(new BasicNameValuePair("lattitude", latitude_tosend));
params.add(new BasicNameValuePair("longtitude", logitude_tosend));
params.add(new BasicNameValuePair("currentaddress", address_tosend));
params.add(new BasicNameValuePair("currentspeed", speed_tosend));
String json = sendToServer(GlobalConstants.url_pass_tripdetail,
params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String file_url) {
}
}
public String sendToServer(String url, List<NameValuePair> params) {
String TAG = "";
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
String response = EntityUtils.toString(httpEntity);
System.out.println("Response==> " + response);
TAG = response;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return TAG;
}
private void getAddress() {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(
Double.parseDouble(latitude_tosend),
Double.parseDouble(logitude_tosend), 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i) + ",");
Toast.makeText(getApplicationContext(), "Address Found..!!!",
Toast.LENGTH_LONG).show();
address_tosend = sb.toString();
} else {
Toast.makeText(getApplicationContext(), "Address is empty!",
Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "No Address returned!",
Toast.LENGTH_SHORT).show();
}
}
public void exit() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Logout")
.setMessage("Are you sure you want to Logout?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
session.logoutUser();
StopGetingLocation();
finish();
}
}).setNegativeButton("No", null).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Related
I have a MapsActivity in my app which starts by clicking on a button in MainActivity and when activity started I will get markers coordinates by JSON and show them in MapsActivity, but this will happen only in first time and once I press back and go to MainActivity and press the button again MapsActivity starts but markers won't be displayed in that . I tried to finish or destroy activity but that didn't help.
any help will be much appreciated
this is my MapsActivity code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
check_activity = 1;
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
ma_fin = this;
MainActivity.maps_adv = 1;
if (flag == 1) {
map_update();
maps_adv = 0;
}
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
checkLocationPermission();
setUpMapIfNeeded();
map_update();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
mGoogleApiClient.disconnect();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0,
0)).title("Marker"));
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
MarkerOptions options = new MarkerOptions()
.position(latLng)
.title("Your Location");
mMap.addMarker(options);
float zoomLevel = 13.0f; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
}
#Override
public void onConnected(Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
/*
* Google Play services can resolve some errors it detects.
* If the error has a resolution, try sending an Intent to
* start a Google Play services activity that can resolve
* error.
*/
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(
this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
/*
* Thrown if Google Play services canceled the original
* PendingIntent
*/
} catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
} else {
/*
* If no resolution is available, display a dialog to the
* user with the error.
*/
Log.i(TAG, "Location services connection failed with code " +
connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 1;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION)) {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
requestPermissions(new String[]{
android.Manifest.permission.ACCESS_COARSE_LOCATION
},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
try {
final ArrayList myList;
if (checker==0) {
myList = (ArrayList<Object>) getIntent().getSerializableExtra("maps");
}
else
{
checker = 0;
myList = maps;
}
mMap = googleMap;
mMap.clear();
for (int i = 0; i < myList.size(); i++) {
LatLng sydney = new LatLng(((Double) (((ArrayList) myList.get(i))).get(2)).doubleValue(), ((Double) (((ArrayList) myList.get(i))).get(3)).doubleValue());
mMap.addMarker(new MarkerOptions().position(sydney).title((String) (((ArrayList) myList.get(i))).get(1)).icon(BitmapDescriptorFactory.fromResource(R.drawable.location_icon)));
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
String position = "0";
String title = marker.getTitle();
for (int i = 0; i < myList.size(); i++) {
if (title.equals(((ArrayList) myList.get(i)).get(1).toString())) {
position = ((ArrayList) myList.get(i)).get(0).toString();
titlename = ((ArrayList) myList.get(i)).get(1).toString();
address = ((ArrayList) myList.get(i)).get(4).toString();
}
}
foo = Integer.valueOf(position);
a = ((ArrayList) myList.get(foo)).get(0).toString();
backgroundTask = new BackgroundTask(textView);
backgroundTask.execute();
map_check = 1;
MainActivity.maps_adv = 0;
return true;
}
});
} catch (RuntimeException e) {
e.printStackTrace();
}
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
jsonobj = new JSONObject();
jsonobj.put("hotel_id_post", foo);
Log.i("EEE", a);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));
nameValuePairs.add(new BasicNameValuePair("func", "2"));
nameValuePairs.add(new BasicNameValuePair("adv", MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" + features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date", MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", "1"));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServerhotel = str.getStringFromInputStream(inputStream);
Log.e("responseqqqqqqq", "response -----" + responseServerhotel);
HotelList.jsonroom = new JSONObject(responseServerhotel);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
if (responseServerhotel.equals("{\"types\":null}"))
{
MainActivity.nothing = "no room to show";
Intent intent = new Intent(MapsActivity.this,Nothing.class);
startActivity(intent);
}
else
{
Intent intent = new Intent(MapsActivity.this, RoomList.class);
startActivity(intent);
}
}
}
private class BackgroundTask1 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask1(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(MainActivity.url);
try {
//mMap.clear();
jsonadv = new JSONObject();
jsonadv_cont = new JSONObject();
jsonobj = new JSONObject();
jsonads = new JSONObject();
MainActivity.features = "";
features_count = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("func", "11"));
nameValuePairs.add(new BasicNameValuePair("adv",
MainActivity.features.toString()));
nameValuePairs.add(new BasicNameValuePair("adv_cont", ("" +
features_count).toString()));
nameValuePairs.add(new BasicNameValuePair("date",
MainActivity.current_date));
nameValuePairs.add(new BasicNameValuePair("during", num));
Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());
// Use UrlEncodedFormEntity to send in proper format which we need
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
InputStream inputStream = response.getEntity().getContent();
InputStreamToStringExample str = new InputStreamToStringExample();
responseServer = str.getStringFromInputStream(inputStream);
Log.e("response", "response -----" + responseServer);
jsonmap = new JSONObject(responseServer);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
backgroundTask2 = new BackgroundTask2(textView);
backgroundTask2.execute();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (backgroundTask != null) {
backgroundTask.cancel(true);
}
if (backgroundTask1 != null) {
backgroundTask1.cancel(true);
}
if (backgroundTask2 != null) {
backgroundTask2.cancel(true);
}
finish();
}
private class BackgroundTask2 extends AsyncTask<Void, Void, String> {
private final WeakReference<TextView> messageViewReference;
private BackgroundTask2(TextView textView) {
this.messageViewReference = new WeakReference<>(textView);
}
#Override
protected String doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MainActivity.url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray mapsarr = jsonmap.getJSONArray("maps");
for (int i = 0; i < mapsarr.length(); i++) {
ArrayList<Object> mapping = new ArrayList<>();
JSONObject c = mapsarr.getJSONObject(i);
String id = c.getString("hotel_id");
String name = c.getString("hotel_name");
Double x = c.getDouble("hotel_x");
Double y = c.getDouble("hotel_y");
String address = c.getString("hotel_address");
mapping.add(0, id);
mapping.add(1, name);
mapping.add(2, x);
mapping.add(3, y);
mapping.add(4, address);
maps.add(i, mapping);
}
Log.i("MAPTEST", mapsarr.toString());
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
final TextView textView = messageViewReference.get();
if (textView != null) {
textView.setText(s);
}
onMapReady(mMap);
checker = 1;
}
}
public static class InputStreamToStringExample {
public static void main(String[] args) throws IOException {
// intilize an InputStream
InputStream is =
new ByteArrayInputStream("file content..blah blah".getBytes());
String result = getStringFromInputStream(is);
System.out.println(result);
System.out.println("Done");
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
}
public void map_update() {
maps.clear();
backgroundTask1 = new BackgroundTask1(textView);
backgroundTask1.execute();
}
public static void refresh()
{
flag = 0;
MapsActivity ma = new MapsActivity();
ma.map_update();
}
public class MapsActivity extends Activity {
private static LatLng goodLatLng = new LatLng(37, -120);
private GoogleMap googleMap;
private EditText et_address, et_finalAddress;
LatLng addressPos, finalAddressPos;
Marker addressMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
et_address = (EditText) findViewById(R.id.addressEditText);
et_finalAddress = (EditText) findViewById(R.id.finalAddressEditText);
// Initial Map
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(false);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Hello"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showAddressMarker(View view) {
String newAddress = et_address.getText().toString();
if (newAddress != null) {
new PlaceAMarker().execute(newAddress);
googleMap.animateCamera(CameraUpdateFactory.zoomIn());
}
}
public void getDirections(View view) {
String startingAddress = et_address.getText().toString();
String finalAddress = et_finalAddress.getText().toString();
if ((startingAddress.equals("")) || finalAddress.equals("")) {
Toast.makeText(this, "Enter a starting and Ending address", Toast.LENGTH_SHORT).show();
} else {
new GetDirections().execute(startingAddress, finalAddress);
}
}
class PlaceAMarker extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String startAddress = params[0];
startAddress = startAddress.replaceAll(" ", "%20");
getLatLng(startAddress, false);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
addressMarker = googleMap.addMarker(new MarkerOptions()
.position(addressPos).title("Address"));
}
}
class GetDirections extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... params) {
String startAddress = params[0];
startAddress = startAddress.replaceAll(" ", "%20");
getLatLng(startAddress, false);
String endingAddress = params[1];
endingAddress = endingAddress.replaceAll(" ", "%20");
getLatLng(endingAddress, true);
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String geoUriString = "http://maps.google.com/maps?addr=" +
addressPos.latitude + "," +
addressPos.longitude + "&daddr=" +
finalAddressPos.latitude + "," +
finalAddressPos.longitude;
Intent mapCall = new Intent(Intent.ACTION_VIEW, Uri.parse(geoUriString));
startActivity(mapCall);
}
}
protected void getLatLng(String address, boolean setDestination) {
String uri = "http://maps.google.com/maps/api/geocode/json?address="
+ address + "&sensor=false";
HttpGet httpGet = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int byteData;
while ((byteData = stream.read()) != -1) {
stringBuilder.append((char) byteData);
}
} catch (IOException e) {
e.printStackTrace();
}
double lat = 0.0, lng = 0.0;
JSONObject jsonObject;
try {
jsonObject = new JSONObject(stringBuilder.toString());
lng = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lng");
lat = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
.getJSONObject("geometry").getJSONObject("location")
.getDouble("lat");
} catch (JSONException e) {
e.printStackTrace();
}
if (setDestination) {
finalAddressPos = new LatLng(lat, lng);
} else {
addressPos = new LatLng(lat, lng);
}
}
}
This is what i have now which is let user inputting both address and i want to show the weather of the destination of the user input. I am new to java language , hope you guys can help me to solve my problem as stated. Thanks
In my app I want to show the multiple marker using latitude and longitude from JSON but when I run the application it only shows one marker, other markers are not shown. Please help - here is my code:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progressDialog; // class variable
private void showProgressDialog(String title, String message)
{
progressDialog = new ProgressDialog(getActivity());
progressDialog.setTitle(title); // set title
progressDialog.setMessage(message); // set message
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
showProgressDialog("Loading...", "Please wait for few seconds");
// dialog = new ProgressDialog(getActivity().this);
// dialog.setMessage("Loading, please wait");
// dialog.setTitle("Connecting server");
// dialog.show();
// dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
// Date a = new Date();
// a.setTime(System.currentTimeMillis()-(60*60*1000));
// Log.e("onehourback",""+a);*/
//------------------>>
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject jsono = new JSONObject(data);
JSONArray jarray = jsono.getJSONArray("SingleIMEs");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
// Log.e("object",""+object);
/*try {
array.add(jarray.getJSONObject(i));
Log.e("array",""+array);
} catch (JSONException e)
{
e.printStackTrace();
}*/
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
}
}
//}
return true;
//------------------>>
} catch (ParseException e1) {
e1.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
if(progressDialog != null && progressDialog.isShowing())
{
progressDialog.dismiss();
}
/* adapter.notifyDataSetChanged();
if(result == false)
Toast.makeText(getActivity().getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
*/
}
}
private void setUpMapIfNeeded(View inflatedView) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(latt,lng)).title("eee"));
Log.e("lat",""+latt);
Log.e("lon",""+lng);
mMap.setMyLocationEnabled(true);
if (mMap != null) {
//setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
mMap.addMarker(new MarkerOptions().position(new LatLng(arg0.getLatitude(), arg0.getLongitude())).title("WePOP"));
// mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).position( new LatLng(Double.parseDouble(datas.get("Lat")), Double.parseDouble(datas.get("Long")))));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
}
});
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
It looks like you're overwriting your latt and lng variables multiple times in this code:
for(int j=0; j < 1;j++)
{
latvalue=object.getString("Latitude");
longvalue=object.getString("Longitude");
latt=Double.parseDouble(latvalue);
lng=Double.parseDouble(longvalue);
Log.e("lat",""+latt);
Log.e("lon",""+lng);
}
I would suggest you create a List that holds some sort of object containing latt and lng information (something like List positions).
Then modify your code in setUpMapIfNeeded to cycle through all your LatLngs. Something like this:
for(LatLng latlng: positions) {
mMap.addMarker(new MarkerOptions().position(new LatLng(latlng.getLat(),latlng.getLng())).title("eee"));
Log.e("Added marker at lat: " + latlng.getLat() + ", lng: " + latlng.getLng());
}
Notice: It's been quite some time since i've used android and google maps, so the code i've written here probably isn't perfect - but the idea should be good :-)
In my application I want to track the vehicles,am getting multiple latitude and longitude from JSON I plotted the latlong in the google map,when the latlong changes in JSON the marker has to move.but here it moves by creating an new marker the previous marker is still exist.how can I remove the marker in the previous location
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
// setUpMap();
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
mMap.clear();
if (marker != null) {
marker.remove();
}
for (int i = 0; i < arraylist1.size(); i++) {
final LatLng position = new LatLng(Double
.parseDouble(arraylist1.get(i).get("Latitude")),
Double.parseDouble(arraylist1.get(i).get(
"Longitude")));
String ime1 = arraylist1.get(i).get("IME");
final MarkerOptions options = new MarkerOptions()
.position(position);
//mMap.addMarker(options);
//mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
marker=mMap.addMarker(new MarkerOptions().position(position).icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
//options.title(ime1);
builder.include(position);
}
LatLng latLng = new LatLng(arg0.getLatitude(), arg0
.getLongitude());
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// mMap.setOnMapClickListener(null);
mMap.setOnMarkerClickListener(null);
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
});
}
}
}
/* protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}
new DownloadJSON().execute();
} */
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
String result="";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
try {
arraylist1 = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
String result = "";
json = jParser.getJSONFromUrl(SERVICE_URL);
try {
//arraylist1.clear();
jsonarray = json.getJSONArray("SingleIMEs");
Log.d("Haaaaaaaaaaaa", "" + json);
for (int i = 0; i < jsonarray.length(); i++) {
Log.d("H11111111111111111111111111",
"" + jsonarray.length());
map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
// pubname = json.getString("PubName");
latitude = json.getDouble("Latitude");
longitude = json.getDouble("Longitude");
ime = json.getString("IME");
// map.put("PubName", json.getString("PubName"));
//map.put("PubID", json.getString("PubID"));
map.put("Latitude", json.getString("Latitude"));
Log.e("CHECKLAT",""+json.getString("Latitude") );
map.put("Longitude", json.getString("Longitude"));
Log.e("CHECKLONG",""+json.getString("Longitude") );
map.put("IME", json.getString("IME"));
arraylist1.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
result="Error";
e.printStackTrace();
}
}catch(Exception e){
result="Error";
}
return null;
}
protected void onPostExecute(Void args) {
// mProgressDialog.dismiss();
}
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
/* Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
Log.d("onLocationUpdated!!!","");
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);*/
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
if (marker != null) {
marker.remove();
}
Do you actually have a function to remove the marker here? If not, you have to remove the marker from the map and set it to null in order to remove it.
marker.setMap(null);
Source: marker API documentation
Im trying to make my service send the phone's coordinates to my server every 5 secs,
and I have no idea why isnt it working.
(Though it does work on a non-service activity. (when an OnClick method is called - A button is clicked.
that is why the fact that its not working within the service is weird.)
This is my code:
public class LocationService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// I Dont Know what this method does.
Execute();
return null;
}
String lat="", lon="";
public void Execute()
{
new PostAsyncTask().execute();
}
public void ReNewCoordinates(){
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,Bundle extras) {}};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
ReNewCoordinates();
//new PostAsyncTask().execute();
}
public void postData(String la, String lo) {
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.myserver.com/insert.php");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("user","100nir100"));
nameValuePair.add(new BasicNameValuePair("lat", lat));
nameValuePair.add(new BasicNameValuePair("lon", lon));
nameValuePair.add(new BasicNameValuePair("address", GetAddress(lat, lon)));
UrlEncodedFormEntity form;
form = new UrlEncodedFormEntity(nameValuePair);
form.setContentEncoding(HTTP.UTF_8);
try {
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
try
{
HttpResponse response = httpClient.execute(httpPost);
int status=response.getStatusLine().getStatusCode();//200=success 300=redirection 400=client error 500 = server error
if(status==200)
{
HttpEntity e=response.getEntity();
String data=EntityUtils.toString(e);
Integer x= Integer.valueOf(data.trim());//very important to use trim
if(x==1)
{
Toast.makeText(this, "Sucssess", Toast.LENGTH_SHORT).show();
}
else if(x!=1)
{
Toast.makeText(this, "Unsucssessful", Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "Unsucssessful", Toast.LENGTH_SHORT).show();
}
}
catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
catch (Exception e) {
// TODO: handle exception
}
}
public String GetAddress(String lat, String lon)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
class PostAsyncTask extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... params) {
postData(lat, lon);
return true;
}
protected void onPreExecute() {
// show progress dialog
}
protected void onPostExecute(Long result) {
// hide progress dialog
}
}
public int onStartCommand(Intent intent, int flags, int startId) {
//new PostAsyncTask().execute();
new Thread(new Runnable(){
public void run() {
while(true){
new PostAsyncTask().execute();
try{
Thread.sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return Service.START_STICKY;
}
public void OnStart()
{
Execute();
}
public void OnDestroy()
{
super.onDestroy();
//Thread.stop();
}
}
So how can I make the service do it every 5 secs?
Thanks for your help!