I'm working to implement MapView for the given gpx file to show way points and tracks,please any one guide me to implement it with sample code.
Thanks in advance.
It is working correctly
package com.lightcone.mapoverlaydemo;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class ShowTheMap extends MapActivity {
private static double lat;
private static double lon;
private int latE6;
private int lonE6;
private MapController mapControl;
private GeoPoint gp;
private MapView mapView;
private Button overlayButton, accessButton;
private Button routeButton;
private List<Overlay> mapOverlays;
private Drawable drawable1, drawable2;
private MyItemizedOverlay itemizedOverlay1, itemizedOverlay2;
private boolean foodIsDisplayed = false;
// Define an array containing the food overlay items
private OverlayItem[] foodItem = {
new OverlayItem(new GeoPoint(35952967, -83929158), "Food Title 1",
"Food snippet 1"),
new OverlayItem(new GeoPoint(35953000, -83928000), "Food Title 2",
"Food snippet 2"),
new OverlayItem(new GeoPoint(35955000, -83929158), "Food Title 3",
"Food snippet 3") };
// Define an array containing the access overlay items
private OverlayItem[] accessItem = {
new OverlayItem(new GeoPoint(35953700, -83926158),
"Access Title 1", "Access snippet 1"),
new OverlayItem(new GeoPoint(35954000, -83928200),
"Access Title 2", "Access snippet 2"),
new OverlayItem(new GeoPoint(35955000, -83927558),
"Access Title 3", "Access snippet 3"),
new OverlayItem(new GeoPoint(35954000, -83927158),
"Access Title 4", "Access snippet 4") };
String TAG = "GPStest";
// Set up the array of GeoPoints defining the route
int numberRoutePoints;
GeoPoint routePoints[]; // Dimension will be set in class RouteLoader below
int routeGrade[]; // Index for slope of route from point i to point i+1
RouteSegmentOverlay route; // This will hold the route segments
boolean routeIsDisplayed = false;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); // Suppress title bar for
// more space
setContentView(R.layout.showthemap);
// Add map controller with zoom controls
mapView = (MapView) findViewById(R.id.mv);
mapView.setSatellite(false);
mapView.setTraffic(false);
mapView.setBuiltInZoomControls(true); // Set android:clickable=true in
// main.xml
int maxZoom = mapView.getMaxZoomLevel();
int initZoom = maxZoom - 2;
mapControl = mapView.getController();
mapControl.setZoom(initZoom);
// Convert lat/long in degrees into integers in microdegrees
latE6 = (int) (35.955 * 1e6);
lonE6 = (int) (-83.9265 * 1e6);
gp = new GeoPoint(latE6, lonE6);
mapControl.animateTo(gp);
// // Button to control food overlay
// overlayButton = (Button)findViewById(R.id.doOverlay);
// overlayButton.setOnClickListener(new OnClickListener(){
// public void onClick(View v) {
// setOverlay1();
// }
// });
//
// // Button to control access overlay
// accessButton = (Button)findViewById(R.id.doAccess);
// accessButton.setOnClickListener(new OnClickListener(){
// public void onClick(View v) {
// setOverlay2();
// }
// });
// Button to control route overlay
routeButton = (Button) findViewById(R.id.doRoute);
routeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!routeIsDisplayed) {
routeIsDisplayed = true;
loadRouteData();
} else {
if (route != null)
route.setRouteView(false);
route = null; // To prevent multiple route instances if key
// toggled rapidly (see line 235)
routeIsDisplayed = false;
mapView.postInvalidate();
}
}
});
}
/*
* Methods to set map overlays. In this case we will place a small overlay
* image at a specified location. Place the marker image as a png file in
* res > drawable-* . For example, the reference to
* R.drawable.knifefork_small below is to an image file called
* knifefork_small.png in the project folder res > drawable-hdpi. Can only
* use lower case letters a-z, numbers 0-9, ., and _ in these image file
* names. In this example the single overlay item is specified by drawable
* and the location of the overlay item is specified by overlayitem.
*/
// Display food location overlay. If not already displayed, clicking button
// displays all
// food overlays. If already displayed successive clicks remove items one by
// one. This
// illustrates ability to change individual overlay items dynamically at
// runtime.
public void setOverlay1() {
int foodLength = foodItem.length;
// Create itemizedOverlay2 if it doesn't exist and display all three
// items
if (!foodIsDisplayed) {
mapOverlays = mapView.getOverlays();
drawable1 = this.getResources().getDrawable(
R.drawable.knifefork_small);
itemizedOverlay1 = new MyItemizedOverlay(drawable1);
// Display all three items at once
for (int i = 0; i < foodLength; i++) {
itemizedOverlay1.addOverlay(foodItem[i]);
}
mapOverlays.add(itemizedOverlay1);
foodIsDisplayed = !foodIsDisplayed;
// Remove each item successively with button clicks
} else {
itemizedOverlay1.removeItem(itemizedOverlay1.size() - 1);
if ((itemizedOverlay1.size() < 1))
foodIsDisplayed = false;
}
// Added symbols will be displayed when map is redrawn so force redraw
// now
mapView.postInvalidate();
}
// Display accessibility overlay. If not already displayed, successive
// button clicks display each of
// the three icons successively, then the next removes them all. This
// illustrates the ability to
// change individual overlay items dynamically at runtime.
public void setOverlay2() {
int accessLength = accessItem.length;
// Create itemizedOverlay2 if it doesn't exist
if (itemizedOverlay2 == null) {
mapOverlays = mapView.getOverlays();
drawable2 = this.getResources().getDrawable(
R.drawable.accessibility);
itemizedOverlay2 = new MyItemizedOverlay(drawable2);
}
// Add items with each click
if (itemizedOverlay2.size() < accessLength) {
itemizedOverlay2.addOverlay(accessItem[itemizedOverlay2.size()]);
mapOverlays.add(itemizedOverlay2);
// Remove all items with one click
} else {
for (int i = 0; i < accessLength; i++) {
itemizedOverlay2.removeItem(accessLength - 1 - i);
}
}
// Added symbols will be displayed when map is redrawn so force redraw
// now
mapView.postInvalidate();
}
// Method to insert latitude and longitude in degrees
public static void putLatLong(double latitude, double longitude) {
lat = latitude;
lon = longitude;
}
// This sets the s key on the phone to toggle between satellite and map view
// and the t key to toggle between traffic and no traffic view (traffic view
// relevant only in urban areas where it is reported).
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_S) {
mapView.setSatellite(!mapView.isSatellite());
return true;
} else if (keyCode == KeyEvent.KEYCODE_T) {
mapView.setTraffic(!mapView.isTraffic());
mapControl.animateTo(gp); // To ensure change displays immediately
}
return (super.onKeyDown(keyCode, e));
}
// Required method since class extends MapActivity
#Override
protected boolean isRouteDisplayed() {
return false; // Don't display a route
}
// Method to read route data from server as XML
public void loadRouteData() {
try {
String url = "http://eagle.phys.utk.edu/reubendb/UTRoute.php";
String data = "?lat1=35952967&lon1=-83929158&lat2=35956567&lon2=-83925450";
// RouteLoader RL = new RouteLoader();
// RL.execute(new URL(url+data));
new RouteLoader().execute(new URL(url + data));
} catch (MalformedURLException e) {
Log.i("NETWORK", "Failed to generate valid URL");
}
}
// Overlay a route. This method is only executed after loadRouteData()
// completes
// on background thread.
public void overlayRoute() {
if (route != null)
return; // To prevent multiple route instances if key toggled
// rapidly (see also line 116)
// Set up the overlay controller
route = new RouteSegmentOverlay(routePoints, routeGrade); // My class
// defining
// route
// overlay
mapOverlays = mapView.getOverlays();
mapOverlays.add(route);
// Added symbols will be displayed when map is redrawn so force redraw
// now
mapView.postInvalidate();
}
/*
* Class to implement single task on background thread without having to
* manage the threads directly. Launch with
* "new RouteLoader().execute(new URL(urlString)". Must be launched from the
* UI thread and may only be invoked once. Adapted from example in Ch. 10 of
* Android Wireless Application Development. Use this to do data load from
* network on separate thread from main user interface to prevent locking
* main UI if there is network delay.
*/
private class RouteLoader extends AsyncTask<URL, String, String> {
#Override
protected String doInBackground(URL... params) {
// This pattern takes more than one param but we'll just use the
// first
try {
URL text = params[0];
XmlPullParserFactory parserCreator;
parserCreator = XmlPullParserFactory.newInstance();
XmlPullParser parser = parserCreator.newPullParser();
// parser.setInput(text.openStream(), null);
parser.setInput(getResources()
.openRawResource(R.raw.fells_loop), null);
publishProgress("Parsing XML...");
int parserEvent = parser.getEventType();
int pointCounter = -1;
int wptCounter = -1;
int totalWaypoints = -1;
int lat = -1;
int lon = -1;
String wptDescription = "";
int grade = -1;
// Parse the XML returned on the network
while (parserEvent != XmlPullParser.END_DOCUMENT) {
switch (parserEvent) {
case XmlPullParser.START_TAG:
String tag = parser.getName();
if (tag.compareTo("number") == 0) {
numberRoutePoints = Integer.parseInt(parser
.getAttributeValue(null, "numpoints"));
totalWaypoints = Integer.parseInt(parser
.getAttributeValue(null, "numwpts"));
routePoints = new GeoPoint[numberRoutePoints];
routeGrade = new int[numberRoutePoints];
Log.i(TAG, " Total points = " + numberRoutePoints
+ " Total waypoints = " + totalWaypoints);
}
if (tag.compareTo("trkpt") == 0) {
pointCounter++;
lat = Integer.parseInt(parser.getAttributeValue(
null, "lat"));
lon = Integer.parseInt(parser.getAttributeValue(
null, "lon"));
grade = Integer.parseInt(parser.getAttributeValue(
null, "grade"));
routePoints[pointCounter] = new GeoPoint(lat, lon);
routeGrade[pointCounter] = grade;
Log.i(TAG, " trackpoint=" + pointCounter
+ " latitude=" + lat + " longitude=" + lon
+ " grade=" + grade);
} else if (tag.compareTo("wpt") == 0) {
wptCounter++;
lat = Integer.parseInt(parser.getAttributeValue(
null, "lat"));
lon = Integer.parseInt(parser.getAttributeValue(
null, "lon"));
wptDescription = parser.getAttributeValue(null,
"description");
Log.i(TAG, " waypoint=" + wptCounter
+ " latitude=" + lat + " longitude=" + lon
+ " " + wptDescription);
}
break;
}
parserEvent = parser.next();
}
} catch (Exception e) {
Log.i("RouteLoader", "Failed in parsing XML", e);
return "Finished with failure.";
}
return "Done...";
}
protected void onCancelled() {
Log.i("RouteLoader", "GetRoute task Cancelled");
}
// Now that route data are loaded, execute the method to overlay the
// route on the map
protected void onPostExecute(String result) {
Log.i(TAG, "Route data transfer complete");
overlayRoute();
}
protected void onPreExecute() {
Log.i(TAG, "Ready to load URL");
}
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
}
}
feel_loop.xml file content from raw folder
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<gpx
version="1.0"
creator="ExpertGPS 1.1.1 - http://www.topografix.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.topografix.com/GPX/1/0"
xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/1"
xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd http://www.topografix.com/GPX/Private/TopoGrafix/0/1 http://www.topografix.com/GPX/Private/TopoGrafix/0/1/topografix.xsd">
<number numpoints="23" numwpts="2"></number>
<wpt lat="35952967" lon="-83929158" description="Construction"></wpt>
<wpt lat="35955038" lon="-83929126" description="Heavy traffic"></wpt>
<trk>
<trkseg>
<trkpt lat="35952967" lon="-83929158" grade="1"></trkpt>
<trkpt lat="35954021" lon="-83930341" grade="1"></trkpt>
<trkpt lat="35954951" lon="-83929075" grade="1"></trkpt>
<trkpt lat="35955038" lon="-83929126" grade="4"></trkpt>
<trkpt lat="35955203" lon="-83928973" grade="1"></trkpt>
<trkpt lat="35955212" lon="-83928855" grade="1"></trkpt>
<trkpt lat="35955603" lon="-83928273" grade="2"></trkpt>
<trkpt lat="35955807" lon="-83928369" grade="1"></trkpt>
<trkpt lat="35955974" lon="-83927943" grade="1"></trkpt>
<trkpt lat="35956063" lon="-83927720" grade="1"></trkpt>
<trkpt lat="35956291" lon="-83927358" grade="1"></trkpt>
<trkpt lat="35956471" lon="-83927229" grade="1"></trkpt>
<trkpt lat="35956541" lon="-83927176" grade="2"></trkpt>
<trkpt lat="35956397" lon="-83927044" grade="3"></trkpt>
<trkpt lat="35956274" lon="-83926685" grade="1"></trkpt>
<trkpt lat="35956213" lon="-83926642" grade="1"></trkpt>
<trkpt lat="35956239" lon="-83926261" grade="1"></trkpt>
<trkpt lat="35956202" lon="-83925722" grade="1"></trkpt>
<trkpt lat="35956226" lon="-83925467" grade="1"></trkpt>
<trkpt lat="35956343" lon="-83925502" grade="1"></trkpt>
<trkpt lat="35956324" lon="-83925617" grade="1"></trkpt>
<trkpt lat="35956445" lon="-83925379" grade="1"></trkpt>
<trkpt lat="35956567" lon="-83925450" grade="1"></trkpt>
</trkseg>
</trk>
</gpx>
Building on Kandha's answer, for the actual GPX parsing you can easily use one of the existing libraries to do it. See this other StackOverflow question.
Related
i am trying to get the value from the hashmap (from ListViewRestaurants) So i can pass the latitude and longitude to the MapsActivity but for reason my hashmap always return null ... So can Anyone help me.
public class ListViewRestaurants extends Activity {
static ListView listView;
static ArrayList<HashMap<String, String>> arrList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listiew);
arrList = new ArrayList<HashMap<String, String>>();
String json_str = getJsonData();
try {
JSONArray jArray = new JSONArray(json_str);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = null;
json = jArray.getJSONObject(i);
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put("id", json.getString("id"));
map1.put("BusinessName", json.getString("BusinessName"));
map1.put("AddressLine1", json.getString("AddressLine1"));
map1.put("AddressLine2", json.getString("AddressLine2"));
map1.put("AddressLine3", json.getString("AddressLine3"));
map1.put("PostCode", json.getString("PostCode"));
map1.put("RatingValue", json.getString("RatingValue"));
map1.put("RatingDate", json.getString("RatingDate"));
map1.put("DistanceKM", json.getString("DistanceKM"));
map1.put("Latitude", json.getString("Latitude"));
map1.put("Longitude", json.getString("Longitude"));
int name = json.getInt("RatingValue");
if(name == 5){
map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==4){
//map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==3){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==2){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==1){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==0){
// map1.put("Image", String.valueOf(R.drawable.ic_launcher_web));
}
else if(name==-1){
map1.put("RatingValue", "Exempt");
}
// adding HashList to ArrayList
arrList.add(map1); // Intent intent = new Intent(this,MapsActivity.class); // intent.putExtra("map", map1);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (!arrList.isEmpty()) {
ListAdapter adapter = new SimpleAdapter(this, arrList,
R.layout.list_item, new String[]{"id", "BusinessName",
"AddressLine1", "AddressLine2", "AddressLine3", "PostCode",
"RatingValue", "RatingDate", "DistanceKM", "Image"},
new int[]{R.id.restaurantId, R.id.BusinessName,
R.id.adr1, R.id.adr2, R.id.adr3, R.id.postCode,
R.id.rating, R.id.ratingDate, R.id.distance, R.id.image});
listView.setAdapter(adapter);
}
}
private String getJsonData() {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
String str = "";
Intent intent = getIntent();
String latitude = intent.getStringExtra("Lat");
String longtitude = intent.getStringExtra("Lon");
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=s_loc&lat="+latitude+"&long="+longtitude);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
Here i am trying to retrieve details from the hashamp (latitude and longitude) from the ListViewRestuarants but i always get null values.
import android.content.Intent; import android.support.v4.app.FragmentActivity; import android.os.Bundle; import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions;
import java.util.HashMap;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
static String x;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//get the value from the array class
Intent intent = getIntent();
HashMap<String, String> hashMap = (HashMap<String, String>)intent.getSerializableExtra("map"); System.out.println(hashmap)
// Log.v("HashMapTest", hashMap.get("Longtitude"));
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title(x));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
} }
This is a main class which display tab view (for more information)
import android.app.TabActivity; import android.content.Intent; import android.os.Bundle; import android.widget.TabHost;
public class MainActivity extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create the TabHost that will contain the Tabs
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabHost.TabSpec tab1 = tabHost.newTabSpec("First Tab");
TabHost.TabSpec tab2 = tabHost.newTabSpec("Second Tab");
// Set the Tab name and Activity
// that will be opened when particular Tab will be selected
tab1.setIndicator("Restaurant");
tab1.setContent(new Intent(this, ListViewRestaurants.class));
tab2.setIndicator("Map");
tab2.setContent(new Intent(this, RestaurantMap.class));
/** Add the tabs to the TabHost to display. */
tabHost.addTab(tab1);
tabHost.addTab(tab2);
} }
The issue is you are setting a different key in the map but trying to fetch the value corresponding to a different key -
map1.put("Longitude", json.getString("Longitude")); //Setting "Longitude"
Log.v("HashMapTest", hashMap.get("Longtitude")); //Getting "Longtitude"
Apparently, there is no key "Longtitude" in your map.
Best practice is to have constants for keys and use it for insertion and retrieval and this will avoid such issues and will not waste your time debugging in also.
I am using a SMSReceiver class which receives an sms and then sends the sms as an extra to my main activity to use in the map application. In my onReceive method I toast the extra and I get the value perfectly fine, but when I try use the variable later down my code to reverse geoCode to get the coordinates from the address then suddenly the global variable is null again :(
The method is called showOnMapClicked on line 324 where the variable is null again.
The sms is being sent from the DDMS.
Somebody please help, I just cant figure it out!
OnReceive Class:
package com.example.maps;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
import android.content.Intent;
public class SMSReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//Adding bundle extras to be used by the main class
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "SMS from ";
//Adding the sms to the array to be stored
if (bundle != null)
{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
if (i == 0)
{
//Appending the information to the string to be displayed
str += msgs[i].getOriginatingAddress();
str += ": \n";
}
str += msgs[i].getMessageBody().toString();
}
Toast.makeText(context, str, Toast.LENGTH_LONG).show();
//Creating the new intent
Intent mainActivityIntent = new Intent(context, MainActivity.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
//Making the intent broadcast to the main class and putting the extra in to be displayed
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
//Setting the name of the string to "sms"
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
//Stops the sms from going directly into the inbox
this.abortBroadcast();
}
}
}
Main Activity Class:
package com.example.maps;
//Daniel Tromp - Assignment 2 - 12002076
//Imports for DAYS!
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.example.maps.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.InputFilter;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
//Implementing all the needed services
public class MainActivity extends Activity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {
// Initializing the needed globals
Location mLocation;
String addressSms;
String addressText;
public GoogleMap mMap;
private TextView mAddress;
private ProgressBar mActivityIndicator;
private LocationClient mLocationClient;
BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;
IntentFilter intentFilter;
// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 1000;
// Update frequency in seconds
public static final int UPDATE_INTERVAL_IN_SECONDS = 5;
// Update frequency in milliseconds
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND
* UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
// A fast frequency ceiling in milliseconds
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND
* FASTEST_INTERVAL_IN_SECONDS;
// Define an object that holds accuracy and frequency parameters
private LocationRequest mLocationRequest;
private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
#Override
//On receiving a message, the textview is set to the sms message
public void onReceive(Context context, Intent intent) {
addressSms = intent.getStringExtra("sms");
//Toasting the variable where it displays my sms message
Toast.makeText(getBaseContext(), addressSms, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
mAddress = (TextView) findViewById(R.id.address);
// As the app loads, the address bar will be displayed
mActivityIndicator = (ProgressBar) findViewById(R.id.address_progress);
// Setting the map type to be Hybrid
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
/*
* Create a new location client, using the enclosing class to handle
* callbacks.
*/
mLocationClient = new LocationClient(this, this, this);
//Creating the new intent
intentFilter = new IntentFilter();
intentFilter.addAction("SMS_RECEIVED_ACTION");
registerReceiver(intentReceiver, intentFilter);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
// The Map is verified. It is now safe to manipulate the map.
}
}
}
// When the application is started
#Override
protected void onStart() {
super.onStart();
// Connect the client.
mLocationClient.connect();
}
private class GetAddressTask extends AsyncTask<Location, Void, String> {
Context mContext;
public GetAddressTask(Context context) {
super();
mContext = context;
}
protected String doInBackground(Location... params) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
Location loc = params[0];
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
} catch (IOException e1) {
Log.e("LocationSampleActivity",
"IO Exception in getFromLocation()");
e1.printStackTrace();
return ("IO Exception trying to get address");
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(loc.getLatitude()) + " , "
+ Double.toString(loc.getLongitude())
+ " passed to address service";
Log.e("LocationSampleActivity", errorString);
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found";
}
}
protected void onPostExecute(String address) {
// Set activity indicator visibility to "gone"
mActivityIndicator.setVisibility(View.GONE);
// Display the results of the lookup.
mAddress.setText(address);
}
}
// When the connection is made to get live updates
public void onConnected(Bundle dataBundle) {
// Display the connection status
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
// Start periodic updates
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
// When the new coordinates are put into the DDMS, the map will change to
// that location and get the new address
public void onLocationChanged(Location location) {
// Report to the UI that the location was updated
LatLng latlng = new LatLng(location.getLatitude(),
location.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
mActivityIndicator.setVisibility(View.VISIBLE);
/*
* Reverse geocoding is long-running and synchronous. Run it on a
* background thread. Pass the current location to the background task.
* When the task finishes, onPostExecute() displays the address.
*/
(new GetAddressTask(this)).execute(location);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onDisconnected() {
}
// Click on button to get the read me file to know how to use the
// application
public void readMeClicked(View v) {
// Create a dialog to pop up and explain the application to the user
AlertDialog alertDialog = new AlertDialog.Builder(this).create(); // Read
// Update
alertDialog.setTitle("Read Me");
alertDialog
.setMessage("My app was created to be able to quickly send out an emergency SMS to a certain individual which will contain the emergency message as well as their current location. By using the DDMS, the coordinates can be input and then my app will go to that specific location and pull the most correct address of that location");
// Making the dialog show
alertDialog.show();
}
public void getFromLocationClicked(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Emergency SMS");
// Setting Dialog Message
alertDialog.setMessage("Enter Emergency Contact Number");
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
// Setting Positive "Continue" Button
alertDialog.setPositiveButton("Continue",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String testing = input.getText().toString();
getFromLocation(testing);
}
});
// Setting Negative "Cancel" Button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
};
public void getFromLocation(String strAddress) {
Geocoder coder = new Geocoder(this);
List<Address> address;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address != null) {
Address location = address.get(0);
double recLat = location.getLatitude();
double recLng = location.getLongitude();
LatLng p = new LatLng(recLat, recLng);
Toast.makeText(getBaseContext(), p + "", Toast.LENGTH_LONG)
.show();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(p, 16));
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
//Showing the value when the show button is clicked
public void showOnMapClicked(View v)
{
//When it toasts, the addressSms value is now null!??
Toast.makeText(getBaseContext(), addressSms, Toast.LENGTH_LONG).show();
//getFromLocation(addressSms);
}
public void showToast(String message)
{
String test = message;
Toast.makeText(getBaseContext(), test, Toast.LENGTH_LONG).show();
}
// Click the button to start to generate the emergency SMS
public void sendAddressClicked(final View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Emergency SMS");
// Setting Dialog Message
alertDialog.setMessage("Enter Emergency Contact Number");
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
input.setFilters(new InputFilter[] {
// Maximum 2 characters.
new InputFilter.LengthFilter(10),
// Digits only.
DigitsKeyListener.getInstance(), // Not strictly needed, IMHO.
});
// Setting Positive "Continue" Button
alertDialog.setPositiveButton("Continue",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Setting the SMS message and adding the current
// location which is gathered by the map.
String textMessage = input.getText().toString();
// Checking if the phone number is not blank
if (textMessage.isEmpty()) {
// If the phone number is not entered
Toast.makeText(getBaseContext(),
"Cannot be blank. Enter phone number.",
Toast.LENGTH_LONG).show();
sendAddressClicked(v);
}
else {
enterMessage(textMessage);
}
}
});
// Setting Negative "Cancel" Button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
};
// Method to send the emergency method and the current location
private void sendSMS(String phoneNumber, String message) {
// Sending the sms to the emulator number input
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
// Once the user has input the number, the message now will be asked for
public void enterMessage(final String number) {
// Creating the dialog to input the emergency message
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Emergency SMS");
// Setting Dialog Message
alertDialog.setMessage("Enter Emergency SMS");
final EditText input = new EditText(MainActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
input.setInputType(InputType.TYPE_CLASS_TEXT);
// Setting Positive "SEND SMS" Button
alertDialog.setPositiveButton("SEND SMS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
// Setting the SMS message and adding the current
// location which is gathered by the map.
String textMessage = input.getText().toString();
String SMS = textMessage + "\n\n"
+ "My Current Address Is: " + addressText;
String phoneNumber = number;
// Checking to see if the SMS is blank
if (textMessage.isEmpty()) {
Toast.makeText(getBaseContext(),
"Cannot be blank. Enter emergency SMS.",
Toast.LENGTH_LONG).show();
enterMessage(phoneNumber);
}
else {
// Sending the variables through to the sendSMS
// method to be sent
sendSMS(phoneNumber, SMS);
}
}
});
// Setting Negative "Cancel" Button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
};
}
Try overriding the onSaveInstanceState(Bundle bundle) method in your MainActivity and use logs to see if it is getting called before your data is getting wiped out. I suspect that you'll see it is getting called. If so, just save your 'globals' in the bundle and retrieve them by overriding the onRestoreInstanceState(Bundle bundle)
The DOC should help you with how to save and restore. Whenever the activity needs to be killed for memory or orientation change, onCreate will be called and the 'globals' can be lost that way.
This might help with more details.
I followed a tut regarding finding nearby places using places api and tried to integrate it in my app. The nearyplaceactivity is runninng but place results are not showing up. Dont know wat is wrong coz the code is almost same as what the tutorial mentioned. Below is my code. If anyone could help, i would be really grateful... The tut link is http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
NearbyPlacesActivity.java
package com.example.travelplanner;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class NearbyPlacesActivity extends Activity {
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Alert Dialog Manager
AlertDialogManager alert = new AlertDialogManager();
// Google Places
GooglePlaces googlePlaces;
// Places List
PlacesList nearPlaces;
// GPS Location
GPSTracker gps;
// Button
Button btnShowOnMap;
// Places Listview
ListView lv;
// ListItems data
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Strings
public static String KEY_REFERENCE = "reference"; // id of the place
public static String KEY_NAME = "name"; // name of the place
public static String KEY_VICINITY = "vicinity"; // Place area name
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby_places);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alert.showAlertDialog(NearbyPlacesActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// creating GPS Class object
gps = new GPSTracker(this);
// check if GPS location can get
if (gps.canGetLocation()) {
Log.d("Your Location", "latitude:" + gps.getLatitude() + ", longitude: " + gps.getLongitude());
} else {
// Can't get user's current location
alert.showAlertDialog(NearbyPlacesActivity.this, "GPS Status",
"Couldn't get location information. Please enable GPS",
false);
// stop executing code by return
return;
}
// Getting listview
lv = (ListView) findViewById(R.id.list);
// button show on map
btnShowOnMap = (Button) findViewById(R.id.btn_show_map);
// calling background Async task to load Google Places
// After getting places from Google all the data is shown in listview
new LoadPlaces().execute();
/** Button click event for shown on map */
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
/**
* ListItem click event
* On selecting a listitem SinglePlaceActivity is launched
* */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String reference = ((TextView) view.findViewById(R.id.reference)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
SinglePlaceActivity.class);
// Sending place refrence id to single place activity
// place refrence id used to get "Place full details"
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
}
});
}
/**
* Background Async Task to Load Google places
* */
class LoadPlaces extends AsyncTask<String, String, String> {
// Progress dialog
ProgressDialog pDialog;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NearbyPlacesActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
// Separeate your place types by PIPE symbol "|"
// If you want all types places make it as null
// Check list of types supported by google
//
String types = "cafe|restaurant"; // Listing places only cafes, restaurants
// Radius in meters - increase this value if you don't find any places
double radius = 1000; // 1000 meters
// get nearest places
nearPlaces = googlePlaces.search(gps.getLatitude(),
gps.getLongitude(), radius, types);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
// Get json response status
String status = nearPlaces.status;
// Check for all possible status
if(status.equals("OK")){
// Successfully got places details
if (nearPlaces.results != null) {
// loop through each place
for (Place p : nearPlaces.results) {
HashMap<String, String> map = new HashMap<String, String>();
// Place reference won't display in listview - it will be hidden
// Place reference is used to get "place full details"
map.put(KEY_REFERENCE, p.reference);
// Place name
map.put(KEY_NAME, p.name);
// adding HashMap to ArrayList
placesListItems.add(map);
}
// list adapter
ListAdapter adapter = new SimpleAdapter(NearbyPlacesActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
alert.showAlertDialog(NearbyPlacesActivity.this, "Near Places",
"Sorry no places found. Try to change the types of places",
false);
}
else if(status.equals("UNKNOWN_ERROR"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry unknown error occured.",
false);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry query limit to google places is reached",
false);
}
else if(status.equals("REQUEST_DENIED"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry error occured. Request is denied",
false);
}
else if(status.equals("INVALID_REQUEST"))
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry error occured. Invalid Request",
false);
}
else
{
alert.showAlertDialog(NearbyPlacesActivity.this, "Places Error",
"Sorry error occured.",
false);
}
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.nearby_places, menu);
return true;
}
}
My application reads a user selected file which contains addresses and then displays on mapview when done geocoding. To avoid hanging app the importing and geocoding is done in AsyncTask.
public class LoadOverlayAsync extends AsyncTask<Uri, Integer, StopsOverlay> {
Context context;
MapView mapView;
Drawable drawable;
public LoadOverlayAsync(Context con, MapView mv, Drawable dw)
{
context = con;
mapView = mv;
drawable = dw;
}
protected StopsOverlay doInBackground(Uri... uris)
{
StringBuilder text = new StringBuilder();
StopsOverlay stopsOverlay = new StopsOverlay(drawable, context);
Geocoder geo = new Geocoder(context, Locale.US);
try
{
File file = new File(new URI(uris[0].toString()));
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null)
{
StopOverlay stopOverlay = null;
String[] tempLine = line.split("~");
List<Address> results = geo.getFromLocationName(tempLine[4] + " " + tempLine[5] + " " + tempLine[7] + " " + tempLine[8], 10);
if (results.size() > 0)
{
Toast progressToast = Toast.makeText(context, "More than one yo", 1000);
progressToast.show();
}
else if (results.size() == 1)
{
Address addr = results.get(0);
GeoPoint mPoint = new GeoPoint((int)(addr.getLatitude() * 1E6), (int)(addr.getLongitude() * 1E6));
stopOverlay = new StopOverlay(mPoint, tempLine);
}
if (stopOverlay != null)
{
stopsOverlay.addOverlay(stopOverlay);
}
//List<Address> results = geo.getFromLocationName(locationName, maxResults)
}
} catch (URISyntaxException e) {
showErrorToast(e.toString());
//e.printStackTrace();
} catch (FileNotFoundException e) {
showErrorToast(e.toString());
//e.printStackTrace();
} catch (IOException e) {
showErrorToast(e.toString());
//e.printStackTrace();
}
return stopsOverlay;
}
protected void onProgressUpdate(Integer... progress)
{
Toast progressToast = Toast.makeText(context, "Loaded " + progress.toString(), 1000);
progressToast.show();
}
protected void onPostExecute(StopsOverlay so)
{
//mapView.getOverlays().add(so);
Toast progressToast = Toast.makeText(context, "Done geocoding", 1000);
progressToast.show();
}
protected void showErrorToast(String msg)
{
Toast Newtoast = Toast.makeText(context, msg, 10000);
Newtoast.show();
}
}
But if geocode fails, I want a dialog popup to let user edit the address. That would require calling on gui method while in doInBackground. What would be a good workaround this?
You'd have to handle it in your onPostExecute method. Perhaps design it so a null argument to onPostExecute indicates that it failed, so in that case pop up the dialog.
If you don't want to change the Result type of StopsOverlay, then what you can do is set some member fields in doInBackground, then check those in onPostExecute and show your error UI at that point.
Note that this is safe and recommended per the AsyncTask docs:
AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.
Set member fields in doInBackground(Params...), and refer to them in onProgressUpdate(Progress...) and onPostExecute(Result).
For example, you could declare a field:
private boolean mTooManyResults = false;
Then change it so that in doInBackground, you have code like:
if (results.size() > 0)
{
mTooManyResults = true;
}
Then in onPostExecute:
if (mTooManyResults)
{
// notify user about error
Toast progressToast = Toast.makeText(context, "More than one yo", 1000);
progressToast.show();
} else
{
// notify user about success
Toast progressToast = Toast.makeText(context, "Done geocoding", 1000);
progressToast.show();
}
My main class is principal extends activity
with this code call MiMapa class:
switch(v.getId()){
case R.id.presentLocation_button:
Log.i("Button","Button 3 pushed");
Intent m = new Intent(this, MiMapa.class);
startActivity(m);
break;
work perfect.
MiMapa class is :
public class MiMapa extends MapActivity implements LocationListener {
I have this method:
public void setOverlay1(){
int foodLength = foodItem.length;
// Create itemizedOverlay2 if it doesn't exist and display all three items
if(! foodIsDisplayed){
mapOverlays = mapView.getOverlays();
drawable1 = this.getResources().getDrawable(R.drawable.golf);
itemizedOverlay1 = new Ofertas(drawable1);
// Display all three items at once
for(int i=0; i<foodLength; i++){
itemizedOverlay1.addOverlay(foodItem[i]);
}
mapOverlays.add(itemizedOverlay1);
foodIsDisplayed = !foodIsDisplayed;
// Remove each item successively with button clicks
} else {
itemizedOverlay1.removeItem(itemizedOverlay1.size()-1);
if((itemizedOverlay1.size() < 1)) foodIsDisplayed = false;
}
// Added symbols will be displayed when map is redrawn so force redraw now
mapView.postInvalidate();
}
now the problem.
into Ofertas class ( public class Ofertas extends ItemizedOverlay {)
in the tap method My code is:
protected boolean onTap(int i){
GeoPoint gpoint = myOverlays.get(i).getPoint();
double lat = gpoint.getLatitudeE6()/1e6;
double lon = gpoint.getLongitudeE6()/1e6;
String toast = "Title: "+myOverlays.get(i).getTitle();
toast += "\nText: "+myOverlays.get(i).getSnippet();
toast += "\nSymbol coordinates: Lat = "+lat+" Lon = "+lon+" (microdegrees)";
Toast.makeText(principal.context, toast, Toast.LENGTH_LONG).show();
Intent intent = new Intent();
intent.setClass(principal.context,Popup.class);
principal.context.startActivity(intent);
intent.putExtra("message", "My popup number " + mCount);
mCount++;
//startActivity(intent);
return(true);
}
but don't work.
I had tried
intent.setClass(MiMapa.context,Popup.class);
or
intent.setClass(principal.this,Popup.class);
or
intent.setClass(MiMapa.this,Popup.class);
Nothing work.
please, help me.
thanks
Pass your Activity into your ItemizedOverlay (e.g., via the constructor) and use that for your startActivity() call.