I try to send a Toast Message from a Thread to the UIThread when clicking a button.
However, every time I click the button the Toast does not appear.
I am using a Handler to do this.
This is the full code, in case I made a major mistake somewhere:
package google.map.activity;
//imports
public class GoogleMapActivity extends MapActivity {
int lat = 0;
int lng = 0;
Location location;
MapController mc;
GeoPoint p;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.googlemapactivity);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(false);
mapView.setSatellite(false);
mapController = mapView.getController();
mapController.setZoom(19);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5,
0, new GeoUpdateHandler());
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 5, 0, new GeoUpdateHandler());
// //////---Switch to
// Start/////////////////////////////////////////////////////////////////////////////
Button switchToMain = (Button) findViewById(R.id.switchtomain);
switchToMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
// ////--Call a
// Cab/////////////////////////////////////////////////////////////////////////////////////
Button getCab = (Button) findViewById(R.id.GetCab); // create the Button
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
getCab.setOnClickListener(new View.OnClickListener() {
String bestProvider = locationManager.getBestProvider(criteria,
true);
Location locationTest = locationManager
.getLastKnownLocation(bestProvider); // get
// last
// known
// location fix from
// locationManager
public void getAddress() {
String msg = null;
Looper.prepare();
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager
.getLastKnownLocation(bestProvider);
Geocoder geocoder = new Geocoder(getBaseContext(), Locale
.getDefault());// create
// new
// GeoCoder
String result = null; // initialize result
try { // try to get Address list from location of bestProvider
List<Address> list = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1);
if (list != null && list.size() > 0) {
Address address = list.get(0);
// sending back first address line and locality
result = address.getAddressLine(0) + ", "
+ address.getLocality();// set result
// to
// Streetname+Nr.
// and City
}
} catch (IOException e) {
msg = String.format("IOException!!");
} finally {
if (result != null) {
msg = String.format(result);
// Looper.loop();
} else
msg = String.format("Keine Position");
}
Message myMessage = new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", msg);
myMessage.obj = resBundle;
handler.sendMessage(myMessage);
}
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// Looper.myLooper();
// Looper.prepare();
getAddress(); // get the Address
Location locationTest = locationManager
.getLastKnownLocation(bestProvider);
if (locationTest == null) {
bestProvider = LocationManager.NETWORK_PROVIDER;
}
Location location2 = locationManager
.getLastKnownLocation(bestProvider);
int lat = (int) (location2.getLatitude() * 1E6); // get
// position
// for GeoPoint
int lng = (int) (location2.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng); // create
// GeoPoint
// for
// mapController
mapController.animateTo(point);
}
}).start();
// toast.show();
}
});
}
public Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Toast.makeText(getApplicationContext(), msg.toString(),
Toast.LENGTH_LONG);
}
};
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Thank you in advance!
Edit: Solved it by using this:
Handler toastHandler = new Handler();
Runnable toastRunnable = new Runnable() {public void run() {Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();}};
In the UIThread and this:
toastHandler.post(toastRunnable);
in the background thread.
Try this:
runOnUiThread(new Runnable()
{
public void run()
{
// Here you can make a Toast
}
});
Your toast needs to be done in the UI thread. Here's how to do that:
Note: ClassName.this is needed because this by itself will refer to your anonymous Runnable class.
runOnUiThread(new Runnable() {
#Override
public void run()
{
Toast.makeText(ClassName.this, R.string.something, Toast.LENGTH_LONG).show();
}
});
Related
I have a StringBuilder variable from which I want to get the final value and pass it to the another activity. And I want to display the final string value in edit text view.
I have tried to get the value using toString() method but I am unable to see the value in text view its blank.
String value=str.toString();
intent.putExtra("value",value);
startActivity(intent);
By this I have got the value and sending to 2nd activity.
Intent intent = this.getIntent();
String data = intent.getStringExtra("keyName");
edtxt_from.setText(data);
Using this I am getting the value in 2nd activity.
Whats going wrong??
Please help...
I am not getting the updated address in edit text view..
ChooseFromMapActivity
public class ChooseFromMapActivity extends AppCompatActivity implements
LocationListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private LocationRequest mLocationRequest;
GoogleMap mGoogleMap;
private GoogleApiClient mGoogleApiClient;
boolean mUpdatesRequested = false;
private LatLng center;
private LinearLayout markerLayout;
private Geocoder geocoder;
private List<Address> addresses;
private TextView Address;
double latitude;
double longitude;
private GPSTracker gps;
private LatLng curentpoint;
private LinearLayout useLocation;
Intent intent;
double x, y;
StringBuilder str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_from_map);
Address = (TextView) findViewById(R.id.textShowAddress);
markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) { // Google Play Services are
// not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else { // Google Play Services are available
// Getting reference to the SupportMapFragment
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);
// Use high accuracy
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
// Note that location updates are off until the user turns them on
mUpdatesRequested = false;
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
mGoogleApiClient.connect();
}
useLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent = new Intent(ChooseFromMapActivity.this,GoSend.class);
String value=str.toString();
intent.putExtra("value",value);
}
});
}
private void stupMap() {
try {
mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
mGoogleMap.getUiSettings().setCompassEnabled(true);
mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
gps = new GPSTracker(this);
gps.canGetLocation();
latitude = gps.getLatitude();
longitude = gps.getLongitude();
curentpoint = new LatLng(latitude, longitude);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(curentpoint).zoom(19f).tilt(70).build();
mGoogleMap.setMyLocationEnabled(true);
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Clears all the existing markers
mGoogleMap.clear();
mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition arg0) {
// TODO Auto-generated method stub
center = mGoogleMap.getCameraPosition().target;
mGoogleMap.clear();
markerLayout.setVisibility(View.VISIBLE);
try {
new GetLocationAsync(center.latitude, center.longitude)
.execute();
} catch (Exception e) {
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
stupMap();
}
private class GetLocationAsync extends AsyncTask<String, Void, String> {
// boolean duplicateResponse;
public GetLocationAsync(double latitude, double longitude) {
// TODO Auto-generated constructor stub
x = latitude;
y = longitude;
}
#Override
protected String doInBackground(String... params) {
try {
geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
addresses = geocoder.getFromLocation(x, y, 1);
str = new StringBuilder();
if (Geocoder.isPresent()) {
if ((addresses != null) && (addresses.size() > 0)) {
Address returnAddress = addresses.get(0);
String localityString = returnAddress.getLocality();
String city = returnAddress.getCountryName();
String region_code = returnAddress.getCountryCode();
String zipcode = returnAddress.getPostalCode();
str.append(localityString + "");
str.append(city + "" + region_code + "");
str.append(zipcode + "");
}
} else {
}
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
try {
Address.setText(addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
}
GoSend
public class GoSend extends AppCompatActivity {
LatLng latLng;
private GoogleMap mMap;
MarkerOptions markerOptions;
LinearLayout ll;
Toolbar toolbar;
EditText editTextLocation;
EditText edtxt_from;
EditText edtxt_to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gosendlayout);
Location l=new Location();
setUI();
if (Build.VERSION.SDK_INT >= 21) {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
//Bundle bundle = getIntent().getParcelableExtra("bundle");
// double fromPosition = bundle.getParcelable("from_position");
// edtxt_from.setText(fromPosition);
/* Bundle extras = getIntent().getExtras();
if (extras != null) {
double latitude = extras.getDouble("latitude");
double longitude = extras.getDouble("Longitude");
edtxt_from.setText(String.valueOf(latitude));*/
Intent intent = this.getIntent();
String data = intent.getStringExtra("value");
edtxt_from.setText(data);
// Bundle bundle = intent.getExtras();
// Serializable value =bundle.getSerializable("value");
// edtxt_from.setText(String.valueOf(longitude));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void setUI() {
ll = (LinearLayout) findViewById(R.id.LinearLayoutGoSend);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("GO-SEND");
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.setMyLocationEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
edtxt_from=(EditText)findViewById(R.id.editText_from);
edtxt_to=(EditText)findViewById(R.id.editText_to);
edtxt_from.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
edtxt_to.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),PickLocationActivity.class);
startActivity(i);
}
});
}
}
Change
String data = intent.getStringExtra("keyName");
to
String data = intent.getStringExtra("value");
You were using the wrong key.
simply do :
Replace keyName by value
i using call function to javascript to android . i using my android code below how to stop android mthread.i used for MyBackgroudMethod mThread but i want to stop this thread in sendCheckOutBackgroundKill();how to possible.please help me!!!
public class EmployeeManager extends CordovaActivity implements
LocationListener{
JavaScriptInterface jsInterface;
LocationManager locationManager;
boolean isGPSEnabled = false;
boolean network_enabled = false;
String provider;
String lati = "";
String latlong = "";
String accuracy = "";
Location currentLocation;
LocationManager mLocationManager;
String devieID = "";
boolean backgroundtask = false;
String iSGps = "";
String mTime="";
String mEmployeeId="";
String mAttendanceId="";
MyBackgroudMethod mThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_employee_manager_main);
super.loadUrl("file:///android_asset/www/index.html");
//mThread = new MyBackgroudMethod();
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
/**/
jsInterface = new JavaScriptInterface(EmployeeManager.this);
appView.addJavascriptInterface(jsInterface, "JSInterface");
appView.getSettings().setJavaScriptEnabled(true);
appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
devieID = getUniquePsuedoID();
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if (provider != null && !provider.equals("")) {
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
if (isGPSEnabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
} else if (network_enabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
}
// locationManager.requestLocationUpdates(provider, 1000, 0, this);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(getBaseContext(), "Location can't be retrieved",
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getBaseContext(), "No Provider Found",Toast.LENGTH_SHORT).show();
}
}
public static String getUniquePsuedoID()
{
String m_szDevIDShort = "35" + (Build.BOARD.length() % 10) + (Build.BRAND.length() % 10) + (Build.CPU_ABI.length() % 10) + (Build.DEVICE.length() % 10) + (Build.MANUFACTURER.length() % 10) + (Build.MODEL.length() % 10) + (Build.PRODUCT.length() % 10);
String serial = null;
try
{
serial = android.os.Build.class.getField("SERIAL").get(null).toString();
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
catch (Exception e)
{
serial = "serial"; // some value
}
return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
}
public class JavaScriptInterface {
public Activity mContext;
public JavaScriptInterface(Activity c) {
this.mContext = c;
}
#JavascriptInterface
public void sendToAndroid(boolean deviceID) {
Log.v("log", "Sent TO android");
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passLatLong(\"" + lati + "\",\"" + latlong + "\",\"" + accuracy + "\");");
appView.setEnabled(false);
}
});
}
#JavascriptInterface
public void sendToDeviceId() {
runOnUiThread(new Runnable() {
public void run() {
appView.loadUrl("javascript:passDevieId(\"" + devieID + "\");");
}
});
}
#JavascriptInterface
public void sendCheckInBackground(String time, String employeeId, String attendanceId) {
mTime= time;
mEmployeeId = employeeId;
mAttendanceId = attendanceId;
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check In Background Native", 3000).show();
mThread = new MyBackgroudMethod();
mThread.setDaemon(true);
mThread.start();
}
});
}
public void sendCheckOutBackgroundKill() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(EmployeeManager.this, "Check Out Background Native Kill", 3000).show();
mThread.interrupt();
}
});
}
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private class MyBackgroudMethod extends Thread {
#Override
public void run() {
while (true) {
checkInternetConnection();
try {
Thread.sleep(Integer.parseInt(mTime)*60*1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
private void checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new JSONTask().execute(mTime,mEmployeeId,mAttendanceId);
} else {
Log.v(TAG, "Internet Connection Not Present");
}
}
#Override
public void onLocationChanged(Location location) {
if(location.getAccuracy() < 400) {
lati = Double.toString(location.getLatitude());
latlong = Double.toString(location.getLongitude());
accuracy = Double.toString(location.getAccuracy());
}
}
#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
}
public class JSONTask extends AsyncTask<String, Void, String> {
public void onPreExecute() {
// progress.show();
}
protected String doInBackground(String... arg) {
// This value will be returned to your
// onPostExecute(result) method
String time1 = arg[0];
String employeeId2 = arg[1];
String attendenceId2 = arg[2];
String img_url = DBAdpter.onFieldCheckIn(employeeId2, attendenceId2, lati, latlong, accuracy);
return img_url;
}
protected void onPostExecute(String result) {
Toast.makeText(EmployeeManager.this, "JSON TASK", 4000).show();
}
}
}
The loop isn't exiting after the interruption. Put a "break;" inside the catch-clause. That's all.
Map showing starting point.
why call marker from database not show.
I'm don't understand.
Or write code the show from database error?
this code Map.java
public class Map extends FragmentActivity implements LocationListener {
SQLiteDatabase SQL;
GoogleMap map;
myDBClass DB;
Cursor cursor;
ArrayList<LatLng> MarkerPoint = new ArrayList<LatLng>();
double latitude = 0;
double longtitude = 0;
GMapV2Direction md = new GMapV2Direction();
Document document;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show_map);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
//map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Destination Marker from Database SQLite
if (MarkerPoint.size() > 1) {
String Name = getIntent().getStringExtra("Name");
DB = new myDBClass(this);
SQL = DB.getWritableDatabase();
cursor = SQL.rawQuery("SELECT *" + " FROM "
+ myDBClass.TABLE_NAME + " WHERE " + myDBClass.NAME
+ " ='" + Name + "'", null);
cursor.moveToFirst();
/**String name = cursor.getString(cursor.getColumnIndex(myDBClass.NAME));
double lat_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
double lng_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
map.addMarker(new MarkerOptions()
.position(new LatLng(lat_db, lng_db)) .title(name));**/
latitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
longtitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
cursor.moveToNext();
//MarkerPoint.clear();
//map.clear();
LatLng strpoint = new LatLng(latitude, longtitude);
drawMarker(strpoint);
}
}
DrawRouteTask drawroute = new DrawRouteTask();
drawroute.execute();
}
private class DrawRouteTask extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response = "";
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(Map.this);
Dialog.setMessage("Loading");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
// Get All Route values
if (MarkerPoint.size() >= 2) {
LatLng Start = MarkerPoint.get(0);
LatLng End = MarkerPoint.get(1);
document = md.getDocument(Start, End,GMapV2Direction.MODE_DRIVING);
response = "Success";
}
return response;
}
#Override
protected void onPostExecute(String result) {
try {
if (response.equalsIgnoreCase("Success")) {
ArrayList<LatLng> directionPoint = md.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
}
} catch (Exception e) {
// TODO:ERROR TRACE ROUTE
}
Dialog.dismiss();
}
}
private void drawMarker(LatLng point) {
MarkerPoint.add(point);
MarkerOptions options = new MarkerOptions();
options.position(point);
if (MarkerPoint.size() == 1) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
} else if (MarkerPoint.size() == 2) {
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
map.addMarker(options);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (MarkerPoint.size() < 2) {
latitude = location.getLatitude();
longtitude = location.getLongitude();
LatLng point = new LatLng(latitude, longtitude);
map.moveCamera(CameraUpdateFactory.newLatLng(point));
map.animateCamera(CameraUpdateFactory.zoomTo(6));
drawMarker(point);
}
}
#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
}
http://i.stack.imgur.com/SXq5P.jpg
Map showing starting point.
why call marker from database not show.
I'm don't understand.
Or write code the show from database error?
I'm working on an app that uses the network location, but i've recived some users feedback that says that they never pass this block of code, i'm assuming that the problem is that location changed is never called, but it only happens in a few diveces, and i cant force the failure in mine.
Is there any chance to solve it or control it? showing a toast saying that is unable to find location, will work for me...
I know that if the user reboot his phone, the location will work, but that it's not a solution for the users
I left the code right here...
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
Location net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
final LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
// SOME STUFF
myTask task = new myTask();
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
} else {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
I've tried with the next idea, i think it could work, at least to get a location and not keep the user waiting.
final LocationManager lm = (LocationManager) thisOfActivity
.getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// SOME STUFF
LocationListener locationListenerNetwork = null;
// Constructor
class MyThread implements Runnable {
LocationListener locationListenerNetwork;
public MyThread(LocationListener lln) {
locationListenerNetwork = lln;
}
public void run() {
}
}
final Handler myHandler = new Handler();
//Here's a runnable/handler combo
final Runnable MyRunnable = new MyThread(locationListenerNetwork)
{
#Override
public void run() {
if (locationListenerNetwork != null)
lm.removeUpdates(locationListenerNetwork);
Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location != null)
{
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
else
{
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_LONG).show();
}
}
};
locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Log.e("LATLON", lat + "," + lon);
lm.removeUpdates(this);
myHandler.removeCallbacks(MyRunnable);
ListView tweetList = (ListView) thisOfActivity
.findViewById(R.id.tweets);
jsonUpdateAsyncTask task = new jsonUpdateAsyncTask(
thisOfActivity, Double.toString(lat),
Double.toString(lon), tweetList);
if (progress.isShowing())
progress.dismiss();
task.execute();
thisOfActivity.registerForContextMenu(tweetList);
}
public void onProviderDisabled(String provider) {
thisOfActivity
.startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
if (progress.isShowing())
progress.dismiss();
MainActivity.accionEnCuro = false;
Toast.makeText(
thisOfActivity.getApplicationContext(),
thisOfActivity.getString(R.string.location),
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
switch( status ) {
case LocationProvider.AVAILABLE:
Log.e("LocProv", "AVAILABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocProv", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.e("LocProv", "TEMPORARILY_UNAVAILABLE");
break;
}
}
};
if (network_enabled) {
myHandler.postDelayed(MyRunnable, 10 * 1000);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0,locationListenerNetwork);
} else {
// MORE STUFF
opinions?
I am developing an android application that contains 3 activities and one of them is map. I am using google maps
what I want:
When the user opens the activity (map) it shows the user her location not the coordinate.
The user should also be able to posit(pining) any place by using a pin and my app must store the coordinates for this pin in a variable so i can use it later.
public class LActivity extends MapActivity
{
/** Called when the activity is first created. */
MapView mapView;
GeoPoint geo;
MapController mapController;
LocationManager locationManager;
CustomPinpoint itemizedoverlay;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
// create a map view
//LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main);
mapView.setBuiltInZoomControls(true);
// Either satellite or 2d
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
this is CustomPinpoint class
public class CustomPinpoint extends ItemizedOverlay<OverlayItem> {
static int maxNum = 3;
OverlayItem overlays[] = new OverlayItem[maxNum];
int index = 0;
boolean full = false;
CustomPinpoint itemizedoverlay;
public CustomPinpoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i) {
return overlays[i];
}
#Override
public int size() {
if (full) {
return overlays.length;
} else {
return index;
}
}
public void addOverlay(OverlayItem overlay) {
if (index < maxNum) {
overlays[index] = overlay;
} else {
index = 0;
full = true;
overlays[index] = overlay;
}
index++;
populate();
}
}
I have implemented the same thing you want. I am providing you the sample code. In this I have also implemented the ProgressDialog when fetching the location.
This is the starting point for getting the location. I named this AndroidLocationActivity. This is the 1st activity which starts when your app starts.
String provider;
public double latitude, longitude = 0;
CurrentPositionTask getCurrentLocation;
Location currentLocation;
LocationListener locationListener;
LocationManager locationManager;
private long time=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
setCriteria();
currentLocation = AndroidLocationActivity.this.locationManager.getLastKnownLocation(provider);
if (currentLocation == null) {
currentLocation = new Location(provider);
}
time = currentLocation.getTime();
if (latitude == 0 && longitude == 0) {
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
Toast.makeText(AndroidLocationActivity.this, String.valueOf(time), Toast.LENGTH_LONG).show();
Here set the time if time is not more than 1minute than i am not updating the location.
if (time >= 100000) {
latitude = 0;
longitude = 0;
}
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("Null");
e.printStackTrace();
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
runAsyncTask();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
locationManager.removeUpdates(locationListener);
}
public void setCriteria() {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
provider = locationManager.getBestProvider(criteria, true);
Toast.makeText(getApplicationContext(), "Provider - " + provider, Toast.LENGTH_SHORT).show();
if (provider == null) {
provider = LocationManager.GPS_PROVIDER;
}
}
public void runAsyncTask() {
// TODO Auto-generated method stub
if (getCurrentLocation == null) {
getCurrentLocation = new CurrentPositionTask();
}
if (getCurrentLocation != null) {
getCurrentLocation.execute("Searching for Location");
}
}
public boolean checkConnection()
{
//ARE WE CONNECTED TO THE NET
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (AndroidLocationActivity.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable()&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
} else {
return false;
}
}
private class CurrentPositionTask extends AsyncTask<String, Void, Void>
{
private ProgressDialog Dialog = new ProgressDialog(AndroidLocationActivity.this);
private boolean flag = true;
public CurrentPositionTask() {
locationListener = new MyLocationListener();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
try {
if (checkConnection()) {
Dialog.setTitle("Loading");
Dialog.setMessage("Searching for Location");
Dialog.show();
locationManager.requestLocationUpdates(provider, 0, 0, locationListener);
}
else {
Toast.makeText(getApplicationContext(), "Internet is Not Available", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
while (flag) {
if (latitude !=0 && longitude != 0) {
flag=false;
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
Toast.makeText(AndroidLocationActivity.this, "Location Floats:- " + latitude + "," + longitude, Toast.LENGTH_LONG).show();
super.onPostExecute(result);
if (Dialog != null && Dialog.isShowing()) {
Dialog.dismiss();
time=0;
Intent homeIntent = new Intent(AndroidLocationActivity.this.getApplicationContext(), HomeMenuActivity.class);
set the lat & lng here and start new activity
homeIntent.putExtra("lat", latitude);
homeIntent.putExtra("lng", longitude);
startActivity(homeIntent);
}
locationManager.removeUpdates(locationListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
This is the function in which i am displaying the Map. This is the HomeMenuActivity
public static Context context;
onCreate(..) {
context = getApplicationContext(); // it will be used in Itemized Overlay
latitude = getIntent().getDoubleExtra("lat", 0);//get the lat & lng
longitude = getIntent().getDoubleExtra("lng", 0);
}
public void showMap() {
// TODO Auto-generated method stub
try {
geoPoint = new GeoPoint((int)(latitude * 1E6),(int)(longitude * 1E6));
mapview = (MapView)findViewById(R.id.mapview);
mapControll= mapview.getController();
mapview.setBuiltInZoomControls(true);
mapview.setStreetView(true);
mapview.setTraffic(true);
mapControll.setZoom(16);
mapControll.animateTo(geoPoint);
userPic = this.getResources().getDrawable(your pic....);
userPicOverlay = new MyItemizedOverlay(userPic);
OverlayItem overlayItem = new OverlayItem(geoPoint, "", null);
userPicOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(userPicOverlay);
//Added symbols will be displayed when map is redrawn so force redraw now
mapview.postInvalidate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
ItemizedOverlay Class
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> myOverlays ;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
myOverlays = new ArrayList<OverlayItem>();
populate();
}
public void addOverlay(OverlayItem overlay){
myOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return myOverlays.get(i);
}
// Removes overlay item i
public void removeItem(int i){
myOverlays.remove(i);
populate();
}
// Returns present number of items in list
#Override
public int size() {
return myOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
myOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
try {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
String title = myOverlays.get(index).getTitle();
Toast.makeText(HomeMenuActivity.context, title, Toast.LENGTH_LONG).show();
return super.onTap(index);
}
}
Hope this will help.....
Remove your method onCreate and add this code:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
initMap(); // This is the method which initialize the map
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new CustomPinpoint(drawable);
createMarker();
}
#Override
public void onResume()
{
super.onResume();
try
{
initMyLocation();
}catch(Exception e){}
}
/**
* Inits the map.
*/
protected void initMap()
{
mapView = (MyMapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapView.setStreetView(false);
mapController = mapView.getController();
mapOverlay = new MapOverlay();
List<Overlay> overlays = mapView.getOverlays();
overlays.add(mapOverlay);
mapController.setZoom(14);
mapView.invalidate();
}
/**
* Initialises the MyLocationOverlay and adds it to the overlays of the map.
*/
public void initMyLocation() {
try
{
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location l = LocationService.getLastKnownLocation(lm);
int lat = (int)(l.getLatitude()*1E6);
int lng = (int)(l.getLongitude()*1E6);
mapController.setCenter(new GeoPoint(lat , lng));
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(myLocOverlay);
mapController.setCenter(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
findMe();
}
/**
* This method will animate to my current position
*/
public void findMe()
{
try
{
mapController.animateTo(myLocOverlay.getMyLocation());
}catch(NullPointerException e){}
}
Then to store the Overlays for future use you can either use SharedPreferences or SQLite. There are loads of tutorials for each of them.