How to call an activity from a class extending ItemizedOverlay - android

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.

Related

In Android is it possible to create an array of strings and LatLngs?

I am trying to create maximum 6 line array of place names and LatLngs and then use an intent to send it to a map class where the user can select name. The name needs to still be tied to the LatLng so the map can centre and zoom to it.
I have added edited code below. I have a mix of putExtra and putParcelable as I'm trying anything to get a working prototype. Hopefully it makes some sense.
The Sending Class Geocode is this:
private void geocodeLocation(String gPlace) {
Geocoder gGeocoder = new Geocoder(this, Locale.getDefault());
try{
List<Address> results = null;
if(Geocoder.isPresent()){
results = gGeocoder.getFromLocationName(gPlace, numberOptions);
} else {
return;
}
Iterator<Address> locations = results.iterator();
String country;
int opCount = 0;
while(locations.hasNext()){
Address location = locations.next();
raw += location+"\n";
strAddressOutput[opCount] = location.getAddressLine(0) + ", " + location.getAddressLine(1) + country + "\n";
strLatOutput[opCount] = location.getLatitude();
strLongOutput[opCount] = location.getLongitude();
gLatLng = new LatLng(location.getLatitude(),location.getLongitude());
strLatLng[opCount] = gLatLng;
opCount ++;
}
for(int i = 0; i<opCount; i++){
}
} catch (IOException e){
}
The Sending Class Intent is this:
public void onConnected(Bundle bundle) {
if (!android.location.Geocoder.isPresent()) {
return;
}
if (gAddressRequested) {
geocodeLocation(gPlace);
Intent tdMap = new Intent(this, com.dm4_map_test.todos3maps.MainMap.class);
tdMap.putExtra(Constants.RETURNEDADDRESS, strAddressOutput);
Bundle args = new Bundle();
args.putString(Constants.PLACE, gPlace);
args.putParcelable(Constants.MAPCENTRE, gMapCentre);
args.putParcelableArray(Constants.LATLNGS, strLatLng);
tdMap.putExtra("bundle", args);
startActivity(tdMap);
}
}
The Receiving Class is this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map);
MapFragment mapFrag = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
if (savedInstanceState == null) {
needsInit = true;
}
mapFrag.getMapAsync(this);
mPlace = (EditText) findViewById(R.id.txAddress);
mAddressList = (Spinner) findViewById(R.id.spinAddressList);
mPlace.setText(getIntent().getStringExtra(Constants.PLACE));
String[] recAddressAA = getIntent().getStringArrayExtra(Constants.RETURNEDADDRESS); // NULLS from Geocoder?
recAddressOutput = recAddressAA;
String testAddressOutput = Arrays.toString(recAddressAA);
Bundle bundleMapCentre = getIntent().getParcelableExtra("bundle");
mMapCentre = bundleMapCentre.getParcelable (Constants.MAPCENTRE);
Bundle bundleLatLng = getIntent().getParcelableExtra("bundle");
LatLng[] mLatLng = bundleLatLng.getParcelableArrayList(Constants.LATLNGS);
mAdapter = new ArrayAdapter<String>(MainMap.this, android.R.layout.simple_spinner_item, recAddressOutput);
mAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mAddressList.setAdapter(mAdapter);
});
}
The line 'LatLng[] mLatLng = bundleLatLng.getParcelableArrayList(Constants.LATLNGS);' errors but I have stepped back to see if this a workable approach
Intent lets you pass through ints, doubles, strings, etc. but if you want to pass a custom object you will have to create the custom object implementing Parceable. You can see a little bit about how to do that here

Android BroadcastReceiver : get object from onReceive method

I'm trying to pass an array list containing Wi-Fi informations from a class that exdends from BroadcastReceiver to another class .I can pass a normal vriable between two classes with the getter. But i'm getting an empty array, because the onReceive methode is not executed .I would like to execute the onReceive methode in another class(but i can't instantiate it ) or to get the array created in the onReceive methode in another class with a getter (but i cant get the list).Please how can i get this array in the second class.
This is the WifiData class
public class WifiData extends BroadcastReceiver{
List<String[]> wifiValues = new ArrayList<String[]>();
WifiManager wifi;
Button enab;
String resultsString ;
String[] myStringArray;
int aa = 10;
int a=10 ;
List<String[]> getWifi (){
return wifiValues ;
}
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
List<ScanResult> results = wifi.getScanResults();
resultsString = results.toString() ;
for(int i=0;i<results.size();i++){
Log.i("Wifi SSID",results.get(i).level+"");
wifiValues.add(new String[] { results.get(i).level +"" });
}
}
}
}
This is SalesStackedBarChart class that have to get the wifi infomation and create a chart :
public class SalesStackedBarChart extends AbstractDemoChart {
public Intent execute(Context context) {
WifiData wi = new WifiData ();
// values.add(new double[] {wi.getWifi() });
Log.i("aaaa",wi.getWifi()+"");
}
}
Thank you.
You are trying to show the data in graph using AChartEngine right?
Create a new activity and put the chart in that layout. Read here how to use the AChartEngine.
Now when you are passing the data from the first class(activity) to the second class(activity), you can pass the data using the intent. Add extra to the Intent using intent.putExtras().First create a bundle. In that bundle put the data using appropriate method like putSerializableExtra() or putParcelableExtra() and in the second class(activity) call getIntent and catch that intent in a temp variable.
From that you can retrieve the data using intent.getExtras().getSerializableExtra() etc. And you can load the data into AChartEngine data to be displayed as a graph.
This is a working solution :
Starting with WifiActivity activity ,wich will determin wifi scan list ,and send it to the TruitonAChartEngineActivity class.
WifiActivity activity
public class WifiActivity extends Activity {
/** Called when the activity is first created. */
WifiManager wifi;
Button enab;
String resultsString ;
String[] myStringArray;
int aa = 10;
//tableau pris à partir de http://www.radio-electronics.com/info/wireless/wi-fi/80211-channels-number-frequencies-bandwidth.php
int [ ] [ ] Center_Frequency_2 = { { 1,2,3,4,5,6,7,8,9,10,11,12,13,14 },
{ 2412, 2417, 2422, 2427, 2432,2437,2442,2447,2452 ,2457,2462,2467,2472,2484},
};
public class Receiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){
final List<ScanResult> results = wifi.getScanResults();
resultsString = results.toString() ;
Log.i("resultsString*****************",resultsString);
final String [ ] [ ] chanelRssi = new String [results.size()][2];
String[] tabResults = new String[results.size()];
for(int i=0;i<results.size();i++){
if (results.get(i).frequency /1000 == 2) {
for (int j =0;j<14;j++)
{ if (Center_Frequency_2[1][j] == results.get(i).frequency)
tabResults[i]=results.get(i).SSID +" (" + results.get(i).BSSID + ") \n"+ results.get(i).frequency +"\n"+ results.get(i).level +"\n"+ results.get(i).capabilities +"\n"+"canal "+Center_Frequency_2[0][j] ;
chanelRssi[i][0]=Center_Frequency_2[0][j]+"";
chanelRssi[i][1]=results.get(i).level +"";
}
}
}
Button send = (Button) findViewById(R.id.barChartButton);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("click","click");
Toast.makeText(getApplicationContext(),
"Position :"+resultsString , Toast.LENGTH_LONG)
.show();
Intent intent1 = new Intent (getApplicationContext(),TruitonAChartEngineActivity.class);
Bundle bundleObject = new Bundle();
bundleObject.putSerializable("key", (Serializable) results);
intent1.putExtras(bundleObject);
startActivityForResult(intent1,0);
/* Intent intent1 = new Intent (getApplicationContext(),TruitonAChartEngineActivity.class);
startActivityForResult(intent1,0);*/
}
});
}
}
private void startActivities(Intent intent, int i) {
// TODO Auto-generated method stub
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi);
ConnectivityManager cxMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
Receiver receiver = new Receiver();
registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
registerReceiver(receiver,new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
}
And the TruitonAChartEngineActivity class
public class TruitonAChartEngineActivity extends ActionBarActivity {
private static final int SERIES_NR = 2;
String message1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_truiton_achart_engine);
XYMultipleSeriesRenderer renderer = getTruitonBarRenderer();
myChartSettings(renderer);
Bundle v = getIntent().getExtras();
ArrayList<ScanResult> classObject = (ArrayList<ScanResult>) v.getSerializable("key");
// message1 = v.getString("message1");
/* Toast.makeText(getApplicationContext(),
"Position :" , Toast.LENGTH_LONG)
.show();*/
/* Toast.makeText(getApplicationContext(),
"Position classObject :"+classObject , Toast.LENGTH_LONG)
.show();*/
for(int index = 0; index < classObject.size(); index++){
String Object = classObject.get(index).level+"";
Toast.makeText(getApplicationContext(), "Id is :"+Object, Toast.LENGTH_SHORT).show();
}
Intent intent = ChartFactory.getBarChartIntent(this, getTruitonBarDataset(), renderer, Type.DEFAULT);
startActivity(intent);
}}

Starting Another Activity on InfoWindowClickListener

I am simply trying to navigate on Another Activity from my FragmentActivity having GoogleMap there. I have following code for InfoWindowClickListener
googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String distance[] = marker.getSnippet().split(" - ");
String distanceString = distance[0];
String idString = marker.getId();
String stationid = markershashmap.get(idString);
Toast.makeText(getApplicationContext(), "Clicked",
Toast.LENGTH_SHORT).show();
Intent dockitdetailsIntent = new Intent(
getApplicationContext(), AnotherActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
dockitdetailsIntent.putExtra("stationId", stationid);
dockitdetailsIntent.putExtra("distance", distanceString);
parentActivity.startChildActivity("Activity Name",
dockitdetailsIntent);
}
});
But when I click the InfoWindow, my device hangs and then I have to force close the not responding app. When i use startActivity(dockitdetailsIntent) it works fine but Tab removes. But I want to use the Next Activity into the similar tabs. Please suggest me why my device hangs out and doesn't respond.
Create Handler and Put Intent logic into this like below:
mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker m1) {
// TODO Auto-generated method stub
try{
String[] str2=str.split("contactID");
Message mesg = new Message();
Bundle b = new Bundle();
b.putString("contact_id", str2[1]);
mesg.setData(b);
handler.sendMessage(mesg);
}catch(Exception e){
e.printStackTrace();
}
}
});
And now create one handler like below:
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle b = msg.getData();
Bundle b1 = new Bundle();
b1.putString("ContactID", b.getString("contact_id"));
b1.putBoolean("showBack", true);
Intent edit = new Intent(getParent(), ContactDetails2.class);
edit.putExtras(b1);
TabGroupActivity parentActivity = (TabGroupActivity) getParent();
parentActivity.startChildActivity("ContactDetails2", edit);
}
};
Try this. It's working in my case

android new intent error

I am new on android und I try to transfer data between two Activities.
Eclipse tell me that the line:
Intent i = new Intent(this, PostDataActivity.class);
Constructor Intent is undefined. What can I do?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.ansehen);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GpsData(StartActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String mlat = String.valueOf(latitude);
// \n is for new line
Intent i = new Intent(this, PostDataActivity.class);
i.putExtra("Value1", "This value one for ActivityTwo ");
You are trying to initialize your Intent from inside an OnClickListener. Hence, the this parameter you are passing to your constructor refers to the listener, and not your Activity.
To fix the problem use :
Intent i = new Intent(YourActivityName.this, PostDataActivity.class);
use
Intent i = new Intent(YourActivityName.this, PostDataActivity.class);

How to parse and plot gpx file has an android MapView

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.

Categories

Resources