ArcGIS for Android with Popup and Routing - Java for Android App Development

Hi,
I want do develop an Android App with the SDK 'ArcGIS for Android'. There I have downloaded two Samples: PopupInWebMapForViewing an Routing. And thats my target: I want these two samples in one Projekt or in one .java-File.
I'm done this, but the App doesn't work on my Smartphone. It only shows up, that the App has stopped. If I comment out all the stuff from Routing, it will work. And if I uncomment all expect of the Layers from the Routing, it will also work. The Routing will be activate by long clicking on the map. But in this case, the App will crash.
I don't know much about java but its a projekt for the university. I hope that someone can help me.
Thank you all very much in advance for your help and sorry for my bad english.
Here's the code:
Code:
public class BAAppActivity extends Activity {
MapView map;
////////////////////////////// Popup /////////////////////////////
PopupContainer popupContainer;
PopupDialog popupDialog;
ProgressDialog progressDialog;
AtomicInteger count;
////////////////////////////// Routing /////////////////////////////
ArcGISTiledMapServiceLayer tileLayer;
GraphicsLayer routeLayer, hiddenSegmentsLayer;
// Symbol used to make route segments "invisible"
SimpleLineSymbol segmentHider = new SimpleLineSymbol(Color.WHITE, 5);
// Symbol used to highlight route segments
SimpleLineSymbol segmentShower = new SimpleLineSymbol(Color.RED, 5);
// Label showing the current direction, time, and length
TextView directionsLabel;
// List of the directions for the current route (used for the ListActivity)
ArrayList<String> curDirections = null;
// Current route, route summary, and gps location
Route curRoute = null;
String routeSummary = null;
Point mLocation = null;
// Global results variable for calculating route on separate thread
RoutingResult mResults = null;
// Variable to hold server exception to show to user
Exception mException = null;
// Handler for processing the results
final Handler mHandler = new Handler();
final Runnable mUpdateResults = new Runnable() {
public void run() {
updateUI();
}
};
////////////////////////////// Routing /////////////////////////////
// Progress dialog to show when route is being calculated
ProgressDialog dialog;
// Spatial references used for projecting points
final SpatialReference wm = SpatialReference.create(102100);
final SpatialReference egs = SpatialReference.create(4326);
// Index of the currently selected route segment (-1 = no selection)
int selectedSegmentID = -1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
////////////////////////////// Routing /////////////////////////////
setContentView(R.layout.main);
////////////////////////////// Popup /////////////////////////////
// Lade die Basemap von ArcGIS online.
map = new MapView(this, "some map", "", "");
setContentView(map);
////////////////////////////// Routing /////////////////////////////
// Retrieve the map and initial extent from XML layout
map = (MapView) findViewById(R.id.map);
// Add tiled layer to MapView
tileLayer = new ArcGISTiledMapServiceLayer(
"Layer");
map.addLayer(tileLayer);
// Add the route graphic layer (shows the full route)
routeLayer = new GraphicsLayer();
map.addLayer(routeLayer);
// Add the hidden segments layer (for highlighting route segments)
hiddenSegmentsLayer = new GraphicsLayer();
map.addLayer(hiddenSegmentsLayer);
// Make the segmentHider symbol "invisible"
segmentHider.setAlpha(1);
// Get the location service and start reading location. Don't auto-pan
// to center our position
LocationService ls = map.getLocationService();
ls.setLocationListener(new MyLocationListener());
ls.start();
ls.setAutoPan(false);
// Set the directionsLabel with initial instructions.
directionsLabel = (TextView) findViewById(R.id.directionsLabel);
directionsLabel.setText(getString(R.string.route_label));
/**
* On single clicking the directions label, start a ListActivity to show
* the list of all directions for this route. Selecting one of those
* items will return to the map and highlight that segment.
*
*/
directionsLabel.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (curDirections == null)
return;
Intent i = new Intent(getApplicationContext(),
ShowDirections.class);
i.putStringArrayListExtra("directions", curDirections);
startActivityForResult(i, 1);
}
});
/**
* On long clicking the directions label, removes the current route and
* resets all affiliated variables.
*
*/
directionsLabel.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
routeLayer.removeAll();
hiddenSegmentsLayer.removeAll();
curRoute = null;
curDirections = null;
directionsLabel.setText(getString(R.string.route_label));
return true;
}
});
////////////////////////////// Popup /////////////////////////////
// Tippe auf die Karte und öffne ein Popup für das selektierte Feature.
map.setOnSingleTapListener(new OnSingleTapListener() {
private static final long serialVersionUID = 1L;
public void onSingleTap(float x, float y) {
////////////////////////////// Routing /////////////////////////////
// Get all the graphics within 20 pixels the click
int[] indexes = hiddenSegmentsLayer.getGraphicIDs(x, y, 20);
// Hide the currently selected segment
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentHider);
if (indexes.length < 1) {
// If no segments were found but there is currently a route,
// zoom to the extent of the full route
if (curRoute != null) {
map.setExtent(curRoute.getEnvelope(), 250);
directionsLabel.setText(routeSummary);
}
return;
}
// Otherwise update our currently selected segment
selectedSegmentID = indexes[0];
Graphic selected = hiddenSegmentsLayer
.getGraphic(selectedSegmentID);
// Highlight it on the map
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentShower);
String direction = ((String) selected.getAttributeValue("text"));
double time = ((Double) selected.getAttributeValue("time"))
.doubleValue();
double length = ((Double) selected.getAttributeValue("length"))
.doubleValue();
// Update the label with this direction's information
String label = String.format(
"%s%nTime: %.1f minutes, Length: %.1f miles",
direction, time, length);
directionsLabel.setText(label);
// Zoom to the extent of that segment
map.setExtent(selected.getGeometry(), 50);
////////////////////////////// Popup /////////////////////////////
if (map.isLoaded()) {
// PopupContainer realisieren.
popupContainer = new PopupContainer(map);
int id = popupContainer.hashCode();
popupDialog = null;
// spinner (Auswahl) anzeigen.
if (progressDialog == null || !progressDialog.isShowing())
progressDialog = ProgressDialog.show(map.getContext(), "", "Rufe Informationen ab...");
// Loop durch jeden Layer in der Basemap.
int tolerance = 20;
Envelope env = new Envelope(map.toMapPoint(x, y), 20 * map.getResolution(), 20 * map.getResolution());
Layer[] layers = map.getLayers();
count = new AtomicInteger();
for (Layer layer : layers) {
// Wenn der Layer noch nicht geladen wurde oder unsichtbar ist, nichts machen.
if (!layer.isInitialized() || !layer.isVisible())
continue;
if (layer instanceof ArcGISFeatureLayer) {
// Frage den FeatureLayer ab und zeige die Popups.
ArcGISFeatureLayer featureLayer = (ArcGISFeatureLayer) layer;
if (featureLayer.getPopupInfo() != null) {
// Frage den FeatureLayer ab, welcher mit den Popupdefinitionen verknüpft ist.
count.incrementAndGet();
new RunQueryFeatureLayerTask(x, y, tolerance, id).execute(featureLayer);
}
}
else if (layer instanceof ArcGISDynamicMapServiceLayer) {
// Frage den DynamicLayer ab und zeige die Popups.
ArcGISDynamicMapServiceLayer dynamicLayer = (ArcGISDynamicMapServiceLayer) layer;
// Empfange Layerinfos für jeden Sub-Layer des dynamic map service layer.
ArcGISLayerInfo[] layerinfos = dynamicLayer.getAllLayers();
if (layerinfos == null)
continue;
// Loop durch jeden Sub-Layer.
for (ArcGISLayerInfo layerInfo : layerinfos) {
// erhalte PopupInfo für die Sub-Layer.
PopupInfo popupInfo = dynamicLayer.getPopupInfo(layerInfo.getId());
// Überspringe Sub-Layer, welche keine Popup-Definitionen enthalten.
if (popupInfo == null) {
continue;
}
// Überprüfe ob der Sub-Layer sichtbar ist.
ArcGISLayerInfo info = layerInfo;
while (info != null && info.isVisible()) {
info = info.getParentLayer();
}
// Überspringe unsichtbare Sub-Layer.
if (info != null && ! info.isVisible()) {
continue;
};
// Überprüfe ob der Sub-Layer innerhalb des Skalenbereichs ist.
double maxScale = (layerInfo.getMaxScale() != 0) ? layerInfo.getMaxScale():popupInfo.getMaxScale();
double minScale = (layerInfo.getMinScale() != 0) ? layerInfo.getMinScale():popupInfo.getMinScale();
if ((maxScale == 0 || map.getScale() > maxScale) && (minScale == 0 || map.getScale() < minScale)) {
// Frage die Sub-Layer ab, welche mit den Popup-Definitionen verknüpft sind und sichtbar sind und im Skalenbereich liegen.
count.incrementAndGet();
new RunQueryDynamicLayerTask(env, layer, layerInfo.getId(), dynamicLayer.getSpatialReference(), id).execute(dynamicLayer.getUrl() + "/" + layerInfo.getId());
}
}
}
}
}
}
});
////////////////////////////// Routing /////////////////////////////
/**
* On long pressing the map view, route from our current location to the
* pressed location.
*
*/
map.setOnLongPressListener(new OnLongPressListener() {
private static final long serialVersionUID = 1L;
public void onLongPress(final float x, final float y) {
// Clear the graphics and empty the directions list
routeLayer.removeAll();
hiddenSegmentsLayer.removeAll();
curDirections = new ArrayList<String>();
mResults = null;
// retrieve the user clicked location
final Point loc = map.toMapPoint(x, y);
// Show that the route is calculating
dialog = ProgressDialog.show(BAAppActivity.this, "",
"Calculating route...", true);
// Spawn the request off in a new thread to keep UI responsive
Thread t = new Thread() {
@Override
public void run() {
try {
// Start building up routing parameters
RoutingParameters rp = new RoutingParameters();
NAFeaturesAsFeature rfaf = new NAFeaturesAsFeature();
// Convert point to EGS (decimal degrees)
Point p = (Point) GeometryEngine.project(loc, wm,
egs);
// Create the stop points (start at our location, go
// to pressed location)
StopGraphic point1 = new StopGraphic(mLocation);
StopGraphic point2 = new StopGraphic(p);
rfaf.setFeatures(new Graphic[] { point1, point2 });
rfaf.setCompressedRequest(true);
rp.setStops(rfaf);
// Set the routing service output SR to our map
// service's SR
rp.setOutSpatialReference(wm);
// Create a new routing task pointing to an
// NAService (null credentials -> free service)
RoutingTask rt = new RoutingTask(
"RoutingTask",
null);
// Solve the route and use the results to update UI
// when received
mResults = rt.solve(rp);
mHandler.post(mUpdateResults);
} catch (Exception e) {
mException = e;
mHandler.post(mUpdateResults);
}
}
};
// Start the operation
t.start();
}
});
}
////////////////////////////// Popup /////////////////////////////
private void createPopupViews(Graphic[] graphics, final int id) {
if (id != popupContainer.hashCode()) {
if (progressDialog != null && progressDialog.isShowing() && count.intValue() == 0)
progressDialog.dismiss();
return;
}
if (popupDialog == null) {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
// Mache einen Dialog für die popups und zeige ihn.
popupDialog = new PopupDialog(map.getContext(), popupContainer);
popupDialog.show();
}
}
// Frage den Feature Layer durch einen Trefferüberprüfung ab.
private class RunQueryFeatureLayerTask extends AsyncTask<ArcGISFeatureLayer, Void, Graphic[]> {
private int tolerance;
private float x;
private float y;
private ArcGISFeatureLayer featureLayer;
private int id;
public RunQueryFeatureLayerTask(float x, float y, int tolerance, int id) {
super();
this.x = x;
this.y = y;
this.tolerance = tolerance;
this.id = id;
}
@Override
protected Graphic [] doInBackground(ArcGISFeatureLayer...params) {
for (ArcGISFeatureLayer featureLayer : params) {
this.featureLayer = featureLayer;
// Grafik-IDs in der Nähe der Punkte abrufen.
int[] ids = featureLayer.getGraphicIDs(x, y, tolerance);
if (ids != null && ids.length > 0) {
ArrayList<Graphic> graphics = new ArrayList<Graphic>();
for (int id : ids) {
// Grafiken basierend auf den IDs erhalten.
Graphic g = featureLayer.getGraphic(id);
if (g == null)
continue;
graphics.add(g);
}
// Liefert ein Array von Grafiken in der Nähe des Punktes.
return graphics.toArray(new Graphic[0]);
}
}
return null;
}
@Override
protected void onPostExecute(Graphic[] graphics) {
count.decrementAndGet();
if (graphics == null || graphics.length == 0) {
if (progressDialog != null && progressDialog.isShowing() && count.intValue() == 0)
progressDialog.dismiss();
return;
}
for (Graphic gr : graphics) {
Popup popup = featureLayer.createPopup(map, 0, gr);
popupContainer.addPopup(popup);
}
createPopupViews(graphics, id);
}
}
// Frage den Dynamic Map Service Layer mit QueryTask ab.
private class RunQueryDynamicLayerTask extends AsyncTask<String, Void, FeatureSet> {
private Envelope env;
private SpatialReference sr;
private int id;
private Layer layer;
private int subLayerId;
public RunQueryDynamicLayerTask(Envelope env, Layer layer, int subLayerId, SpatialReference sr, int id) {
super();
this.env = env;
this.sr = sr;
this.id = id;
this.layer = layer;
this.subLayerId = subLayerId;
}
@Override
protected FeatureSet doInBackground(String... urls) {
for (String url : urls) {
// Erhalte Grafiken innerhalb der Hülle.
Query query = new Query();
query.setInSpatialReference(sr);
query.setOutSpatialReference(sr);
query.setGeometry(env);
query.setMaxFeatures(10);
query.setOutFields(new String[] { "*" });
QueryTask queryTask = new QueryTask(url);
try {
FeatureSet results = queryTask.execute(query);
return results;
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(final FeatureSet result) {
count.decrementAndGet();
if (result == null) {
if (progressDialog != null && progressDialog.isShowing() && count.intValue() == 0)
progressDialog.dismiss();
return;
}
Graphic[] graphics = result.getGraphics();
if (graphics == null || graphics.length == 0) {
if (progressDialog != null && progressDialog.isShowing() && count.intValue() == 0)
progressDialog.dismiss();
return;
}
// Überprüfen, ob die angeforderte PopupContainer-Id identisch mit dem aktuellen PopupContainer ist.
// Andernfalls verlasse die veralteten Abfragen.
if (id != popupContainer.hashCode()) {
// Spinner verwerfen.
if (progressDialog != null && progressDialog.isShowing() && count.intValue() == 0)
progressDialog.dismiss();
return;
}
PopupInfo popupInfo = layer.getPopupInfo(subLayerId);
if (popupInfo == null) {
// Spinner verwerfen.
if (progressDialog != null && progressDialog.isShowing() && count.intValue() == 0)
progressDialog.dismiss();
return;
}
for (Graphic gr : graphics) {
Popup popup = layer.createPopup(map, subLayerId, gr);
popupContainer.addPopup(popup);
}
createPopupViews(graphics, id);
}
}
// Ein angepasster Vollbild-Dialog.
private class PopupDialog extends Dialog {
private PopupContainer popupContainer;
public PopupDialog(Context context, PopupContainer popupContainer) {
super(context, android.R.style.Theme);
this.popupContainer = popupContainer;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
LinearLayout layout = new LinearLayout(getContext());
layout.addView(popupContainer.getPopupContainerView(), LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
setContentView(layout, params);
}
}
////////////////////////////// Routing /////////////////////////////
/**
* Updates the UI after a successful rest response has been received.
*/
void updateUI() {
dialog.dismiss();
if (mResults == null) {
Toast.makeText(BAAppActivity.this, mException.toString(),
Toast.LENGTH_LONG).show();
return;
}
curRoute = mResults.getRoutes().get(0);
// Symbols for the route and the destination (blue line, checker flag)
SimpleLineSymbol routeSymbol = new SimpleLineSymbol(Color.BLUE, 3);
PictureMarkerSymbol destinationSymbol = new PictureMarkerSymbol(
getResources().getDrawable(R.drawable.flag_finish));
// Add all the route segments with their relevant information to the
// hiddenSegmentsLayer, and add the direction information to the list
// of directions
for (RoutingDirection rd : curRoute.getRoutingDirections()) {
HashMap<String, Object> attribs = new HashMap<String, Object>();
attribs.put("text", rd.getText());
attribs.put("time", Double.valueOf(rd.getTime()));
attribs.put("length", Double.valueOf(rd.getLength()));
curDirections.add(String.format(
"%s%nTime: %.1f minutes, Length: %.1f miles", rd.getText(),
rd.getTime(), rd.getLength()));
hiddenSegmentsLayer.addGraphic(new Graphic(rd.getGeometry(),
segmentHider, attribs, null));
}
// Reset the selected segment
selectedSegmentID = -1;
// Add the full route graphic and destination graphic to the routeLayer
Graphic routeGraphic = new Graphic(curRoute.getRoute().getGeometry(),
routeSymbol);
Graphic endGraphic = new Graphic(
((Polyline) routeGraphic.getGeometry()).getPoint(((Polyline) routeGraphic
.getGeometry()).getPointCount() - 1), destinationSymbol);
routeLayer.addGraphics(new Graphic[] { routeGraphic, endGraphic });
// Get the full route summary and set it as our current label
routeSummary = String.format(
"%s%nTotal time: %.1f minutes, length: %.1f miles",
curRoute.getRouteName(), curRoute.getTotalTime(),
curRoute.getTotalLength());
directionsLabel.setText(routeSummary);
// Zoom to the extent of the entire route with a padding
map.setExtent(curRoute.getEnvelope(), 250);
}
/**
* On returning from the list of directions, highlight and zoom to the
* segment that was selected from the list. (Activity simply resumes if the
* back button was hit instead).
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Response from directions list view
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
String direction = data.getStringExtra("returnedDirection");
if (direction == null)
return;
// Look for the graphic that corresponds to this direction
for (int index : hiddenSegmentsLayer.getGraphicIDs()) {
Graphic g = hiddenSegmentsLayer.getGraphic(index);
if (direction
.contains((String) g.getAttributeValue("text"))) {
// When found, hide the currently selected, show the new
// selection
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentHider);
hiddenSegmentsLayer.updateGraphic(index, segmentShower);
selectedSegmentID = index;
// Update label with information for that direction
directionsLabel.setText(direction);
// Zoom to the extent of that segment
map.setExtent(
hiddenSegmentsLayer.getGraphic(
selectedSegmentID).getGeometry(), 50);
break;
}
}
}
}
}
private class MyLocationListener implements LocationListener {
public MyLocationListener() {
super();
}
/**
* If location changes, update our current location. If being found for
* the first time, zoom to our current position with a resolution of 20
*/
public void onLocationChanged(Location loc) {
if (loc == null)
return;
boolean zoomToMe = (mLocation == null) ? true : false;
mLocation = new Point(loc.getLongitude(), loc.getLatitude());
if (zoomToMe) {
Point p = (Point) GeometryEngine.project(mLocation, egs, wm);
map.zoomToResolution(p, 20.0);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS Disabled",
Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "GPS Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
@Override
protected void onPause() {
super.onPause();
map.pause();
}
@Override
protected void onResume() {
super.onResume();
map.unpause();
}
}
I know, it's a long code. Maybe someone find an error or something else.
Best regards
losaruka

The first problem in the logs is in your onCreate method, why are you calling setContentView twice in that method? I don't know the lib you are using but you definitely can't do that...

Hi, thank you for the help.
Now the app runs. But i've got some new problems. In my previous code the layers weren't right insert in the code. I can't insert a whole map. I had to add an extra FeatureLayer.
And now, if I tap on a feature the app stock at a loop, in which the program will look for a featurelayer. i dont know why?!
Another thing is, if I want to get the whole routeoverview, the app will crash. But the code seems to be ok. I don't know, wheres the problem.
Here's the layers:
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
map = (MapView) findViewById(R.id.map);
// Add tiled layer to MapView
tileLayer = new ArcGISTiledMapServiceLayer(
"tileLAyer");
map.addLayer(tileLayer);
// Add feature layer to MapView
featureLayer = new ArcGISFeatureLayer(
"featureLayer", MODE.ONDEMAND);
map.addLayer(featureLayer);
// Add the route graphic layer (shows the full route)
routeLayer = new GraphicsLayer();
map.addLayer(routeLayer);
// Add the hidden segments layer (for highlighting route segments)
hiddenSegmentsLayer = new GraphicsLayer();
map.addLayer(hiddenSegmentsLayer);
// Make the segmentHider symbol "invisible"
segmentHider.setAlpha(1);
// Get the location service and start reading location. Don't auto-pan
// to center our position
LocationService ls = map.getLocationService();
ls.setLocationListener(new MyLocationListener());
ls.start();
ls.setAutoPan(false);
// Set the directionsLabel with initial instructions.
directionsLabel = (TextView) findViewById(R.id.directionsLabel);
directionsLabel.setText(getString(R.string.route_label));
And here's the loop for the FeatureLayer and the second onSingleTap' for the Routing overview:
Code:
map.setOnSingleTapListener(new OnSingleTapListener() {
private static final long serialVersionUID = 1L;
public void onSingleTap(float x, float y) {
if (map.isLoaded()) {
// PopupContainer realisieren.
popupContainer = new PopupContainer(map);
int id = popupContainer.hashCode();
popupDialog = null;
// spinner (Auswahl) anzeigen.
if (progressDialog == null || !progressDialog.isShowing())
progressDialog = ProgressDialog.show(map.getContext(), "", "Rufe Informationen ab...");
// Loop durch jeden Layer in der Basemap.
int tolerance = 20;
// Envelope env = new Envelope(map.toMapPoint(x, y), 20 * map.getResolution(), 20 * map.getResolution());
Layer[] layers = map.getLayers();
count = new AtomicInteger();
for (Layer layer : layers) {
// Wenn der Layer noch nicht geladen wurde oder unsichtbar ist, nichts machen.
if (!layer.isInitialized() || !layer.isVisible())
continue;
if (layer instanceof ArcGISFeatureLayer) {
// Frage den FeatureLayer ab und zeige die Popups.
ArcGISFeatureLayer featureLayer = (ArcGISFeatureLayer) layer;
if (featureLayer.getPopupInfo() != null) {
// Frage den FeatureLayer ab, welcher mit den Popupdefinitionen verknüpft ist.
count.incrementAndGet();
new RunQueryFeatureLayerTask(x, y, tolerance, id).execute(featureLayer);
}
}
}
}
}
////////////////////////////// Routing /////////////////////////////
public void onSingleTap1(float x, float y) {
// Get all the graphics within 20 pixels the click
int[] indexes = hiddenSegmentsLayer.getGraphicIDs(x, y, 20);
// Hide the currently selected segment
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentHider);
if (indexes.length < 1) {
// If no segments were found but there is currently a route,
// zoom to the extent of the full route
if (curRoute != null) {
map.setExtent(curRoute.getEnvelope(), 250);
directionsLabel.setText(routeSummary);
}
return;
}
// Otherwise update our currently selected segment
selectedSegmentID = indexes[0];
Graphic selected = hiddenSegmentsLayer
.getGraphic(selectedSegmentID);
// Highlight it on the map
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentShower);
String direction = ((String) selected.getAttributeValue("text"));
double time = ((Double) selected.getAttributeValue("time"))
.doubleValue();
double length = ((Double) selected.getAttributeValue("length"))
.doubleValue();
// Update the label with this direction's information
String label = String.format(
"%s%nTime: %.1f minutes, Length: %.1f miles",
direction, time, length);
directionsLabel.setText(label);
// Zoom to the extent of that segment
map.setExtent(selected.getGeometry(), 50);
}
});
I know that 'onSingleTap1(float x, float y)' doesn't work. But i need to test the code, so in this way I get no error
Hope someone can help
Greets

Need help
losaruka said:
Hi, thank you for the help.
Now the app runs. But i've got some new problems. In my previous code the layers weren't right insert in the code. I can't insert a whole map. I had to add an extra FeatureLayer.
And now, if I tap on a feature the app stock at a loop, in which the program will look for a featurelayer. i dont know why?!
Another thing is, if I want to get the whole routeoverview, the app will crash. But the code seems to be ok. I don't know, wheres the problem.
Here's the layers:
Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
map = (MapView) findViewById(R.id.map);
// Add tiled layer to MapView
tileLayer = new ArcGISTiledMapServiceLayer(
"tileLAyer");
map.addLayer(tileLayer);
// Add feature layer to MapView
featureLayer = new ArcGISFeatureLayer(
"featureLayer", MODE.ONDEMAND);
map.addLayer(featureLayer);
// Add the route graphic layer (shows the full route)
routeLayer = new GraphicsLayer();
map.addLayer(routeLayer);
// Add the hidden segments layer (for highlighting route segments)
hiddenSegmentsLayer = new GraphicsLayer();
map.addLayer(hiddenSegmentsLayer);
// Make the segmentHider symbol "invisible"
segmentHider.setAlpha(1);
// Get the location service and start reading location. Don't auto-pan
// to center our position
LocationService ls = map.getLocationService();
ls.setLocationListener(new MyLocationListener());
ls.start();
ls.setAutoPan(false);
// Set the directionsLabel with initial instructions.
directionsLabel = (TextView) findViewById(R.id.directionsLabel);
directionsLabel.setText(getString(R.string.route_label));
And here's the loop for the FeatureLayer and the second onSingleTap' for the Routing overview:
Code:
map.setOnSingleTapListener(new OnSingleTapListener() {
private static final long serialVersionUID = 1L;
public void onSingleTap(float x, float y) {
if (map.isLoaded()) {
// PopupContainer realisieren.
popupContainer = new PopupContainer(map);
int id = popupContainer.hashCode();
popupDialog = null;
// spinner (Auswahl) anzeigen.
if (progressDialog == null || !progressDialog.isShowing())
progressDialog = ProgressDialog.show(map.getContext(), "", "Rufe Informationen ab...");
// Loop durch jeden Layer in der Basemap.
int tolerance = 20;
// Envelope env = new Envelope(map.toMapPoint(x, y), 20 * map.getResolution(), 20 * map.getResolution());
Layer[] layers = map.getLayers();
count = new AtomicInteger();
for (Layer layer : layers) {
// Wenn der Layer noch nicht geladen wurde oder unsichtbar ist, nichts machen.
if (!layer.isInitialized() || !layer.isVisible())
continue;
if (layer instanceof ArcGISFeatureLayer) {
// Frage den FeatureLayer ab und zeige die Popups.
ArcGISFeatureLayer featureLayer = (ArcGISFeatureLayer) layer;
if (featureLayer.getPopupInfo() != null) {
// Frage den FeatureLayer ab, welcher mit den Popupdefinitionen verknüpft ist.
count.incrementAndGet();
new RunQueryFeatureLayerTask(x, y, tolerance, id).execute(featureLayer);
}
}
}
}
}
////////////////////////////// Routing /////////////////////////////
public void onSingleTap1(float x, float y) {
// Get all the graphics within 20 pixels the click
int[] indexes = hiddenSegmentsLayer.getGraphicIDs(x, y, 20);
// Hide the currently selected segment
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentHider);
if (indexes.length < 1) {
// If no segments were found but there is currently a route,
// zoom to the extent of the full route
if (curRoute != null) {
map.setExtent(curRoute.getEnvelope(), 250);
directionsLabel.setText(routeSummary);
}
return;
}
// Otherwise update our currently selected segment
selectedSegmentID = indexes[0];
Graphic selected = hiddenSegmentsLayer
.getGraphic(selectedSegmentID);
// Highlight it on the map
hiddenSegmentsLayer.updateGraphic(selectedSegmentID,
segmentShower);
String direction = ((String) selected.getAttributeValue("text"));
double time = ((Double) selected.getAttributeValue("time"))
.doubleValue();
double length = ((Double) selected.getAttributeValue("length"))
.doubleValue();
// Update the label with this direction's information
String label = String.format(
"%s%nTime: %.1f minutes, Length: %.1f miles",
direction, time, length);
directionsLabel.setText(label);
// Zoom to the extent of that segment
map.setExtent(selected.getGeometry(), 50);
}
});
I know that 'onSingleTap1(float x, float y)' doesn't work. But i need to test the code, so in this way I get no error
Hope someone can help
Greets
Click to expand...
Click to collapse
Were you successful?

Related

How to prevent laggy scrolling ListView w ImageView-Items filled with cached images?

Hello community,
I've got a ListActivity in my app, which shows Views including TextViews, for showing artist, title and album information of some mp3-Files (queried by my cursor), and an ImageView, for showing an albumart => Similar to the Tracklist in the music app.
Here's the code for my custom SimpleCursorAdapter and it's binding to the ListView:
Code:
void setListAdapterOverride() {
String[] fromColumns = new String[] {
AudioColumns.ARTIST,
MediaColumns.TITLE,
AudioColumns.ALBUM,
AudioColumns.ALBUM_ID
};
int[] toColumns = new int[] {
R.id.tv_artist,
R.id.tv_title,
R.id.tv_album,
R.id.iv_albumArt
};
cursorAdapter = new customAdapter(getBaseContext(), R.layout.listviewitem, cursor, fromColumns, toColumns);
setListAdapter(cursorAdapter);
if (MyDebug.Log)
Log.d("Activity", "ListAdapter gesetzt");
}
class customAdapter extends SimpleCursorAdapter {
int layout;
Cursor cursor;
String[] from;
int[] to;
public customAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
this.layout = layout;
this.cursor = c;
this.from = from;
this.to = to;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.listviewitem, parent, false);
if (MyDebug.Log)
Log.d("Activity", "Inflate");
}
cursor.moveToPosition(position);
TextView artist = (TextView) row.findViewById(to[0]);
TextView title = (TextView) row.findViewById(to[1]);
TextView album = (TextView) row.findViewById(to[2]);
ImageView albumArt = (ImageView) row.findViewById(to[3]);
artist.setText(cursor.getString(cursor.getColumnIndex(from[0])));
title.setText(cursor.getString(cursor.getColumnIndex(from[1])));
album.setText(cursor.getString(cursor.getColumnIndex(from[2])));
Cursor albumArtCursor = contentResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, new String[] { MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART }, MediaStore.Audio.Albums._ID + "='" + cursor.getInt(cursor.getColumnIndex(from[3])) + "'", null, null);
albumArtCursor.moveToFirst();
String albumArtUri = albumArtCursor.getString(albumArtCursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
if (albumArtUri == null) albumArtUri = "default";
if (!imageCache.containsKey(albumArtUri)) {
Bitmap albumArtBitmap;
if (!albumArtUri.equals("default")) {
Options opts = new Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(albumArtUri, opts);
Integer[] bitmapSize = new Integer[] { opts.outWidth, opts.outHeight };
Integer scaleFactor = 1;
while ((bitmapSize[0]/2 > 50) && (bitmapSize[1]/2 > 50)) {
scaleFactor++;
bitmapSize[0] /= 2;
bitmapSize[1] /= 2;
}
opts = new Options();
opts.inSampleSize = scaleFactor;
albumArtBitmap = BitmapFactory.decodeFile(albumArtUri, opts);
} else {
albumArtBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mp_song_list);
}
imageCache.put(albumArtUri, albumArtBitmap);
}
albumArt.setImageBitmap(imageCache.get(albumArtUri));
return row;
}
}
imageCache is a Hashmap<String, Bitmap> for caching the Bitmaps, so they don't have to be decoded from file again when they had been cached before.
In a former version of the code, I didn't have the imageCache, so the albumarts were decoded from file everytime a new row has been added. That slowed down ListView-scrolling. By adding the imageCache scrolling in ListView doesn't lag that much as before, but it's lagging a bit sometimes.
Can anyone help me to further optimize my code to completely prevent lagging when I scroll the ListView?
Thanks regards ChemDroid

FC when using interface to launch new fragment form listView

I have an async task that loads a list view of items. I am currently trying to set the onClick to load a new fragment with an "id" that is being retrieved from the list item that is clicked. I have no errors in my code that the Android Studio shows me.
When I run the app and click on the item in the list view I get this FC:
02-13 19:49:56.813 20334-20334/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.ReadJSONResult$1.onItemClick(ReadJSONResult.java:140)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
02-13 19:50:42.112 20864-20870/? E/jdwp﹕ Failed sending reply to debugger: Broken pipe
line 140 in ReadJSONResult is:
listenerBeer.onArticleSelected(idToSend);
That line is part of this whole onClick:
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
All the code for ReadJSONResult is:
public class ReadJSONResult extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public ReadJSONResult(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//code for on click
OnArticleSelectedListener listenerBeer;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
//end code for onClick
@override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Searching Beer Cellar");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(c ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
//todo: all the get functions go here
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
BeerSearchAdapter is:
public class BeerSearchAdapter extends ArrayAdapter<BeerData> {
Context context;
int layoutResourceId;
List<BeerData> data = null;
public BeerSearchAdapter(Context context, int layoutResourceId, List<BeerData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data.get(position);
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
My Search.java where the interface comes form is here:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//todo: code body goes here
// Inflate the layout for this fragment
return v;
}
@override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
Log.d("click", "inside the on create");
//inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setIconified(false);
searchView.setOnQueryTextListener(this);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult(getActivity()).execute(jsonUrl);
return false;
}
@override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
@override
public void onArticleSelected(String b){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
//todo: set to beer fragment
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
Let me know if you need any other code, I am stomped on this and could use a second pair of eyes. Thanks.

SharedPreferences Context Issue

I have created a questionnaire in the beginning of the app in order to base a user model off the answers chosen. The values of the chosen options are stored as Shared Preferences as shown below. With the data retrieved I am then trying to tag a Google map with certain tags based on the answers chosen. The issue I am encountering is that of reading the stored Shared Preference values across the different activities, from the Question2 Activity, to that of the Map Activity (code below). Any pointers on how to solve the *context* conflict would be greatly appreciated.
Question2 Activity:
Code:
public class Question2 extends Activity{
RadioButton q2a1,q2a2,q2a3;
Button btn2;
public static final String MY_PREF = "MyPreferences";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.activity_question2, null);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question2);
q2a1 = (RadioButton) findViewById(R.id.q2a1);
q2a2 = (RadioButton) findViewById(R.id.q2a2);
q2a3 = (RadioButton) findViewById(R.id.q2a3);
btn2 = (Button) findViewById(R.id.q2_button);
btn2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
SharedPreferences prefernces = getSharedPreferences(MY_PREF, 0);
SharedPreferences.Editor editor = prefernces.edit();
if (q2a1.isChecked()){
editor.putInt("answer_value2", 1);
editor.commit();
}
if (q2a2.isChecked()){
editor.putInt("answer_value2", 2);
editor.commit();
}
if (q2a3.isChecked()){
editor.putInt("answer_value2", 3);
editor.commit();
}else {
editor.putInt("answer_value2", 0);
editor.commit();
}
editor.commit();
Intent intent = new Intent(getApplicationContext(), Question3.class);
startActivity(intent);
}
});
}
}
Map Activity:
Code:
public class MapActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.mapLayout)).getMap();
map.setMyLocationEnabled(true);
SharedPreferences preferences = getSharedPreferences(Question2.MY_PREF,MODE_PRIVATE);
int q1answer = preferences.getInt("answer_value", 0);
int q2answer = preferences.getInt("answer_value2", 0);
int q3answer = preferences.getInt("answer_value3", 0);
if(q1answer == 1){
//method
}
if(q1answer == 2){
//method
}
if(q1answer == 3){
//method
}
if(q2answer == 1){
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(HEALTHSHOP).title("Health Shop").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grasy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MINT).title("Mint").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 2){
Toast.makeText(getApplicationContext(), "Your result is " + q2answer, Toast.LENGTH_SHORT).show();
map.addMarker(new MarkerOptions().position(FOOD_FOOD).title("Food & Food").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(M_S).title("M&S").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(JUBILEE).title("Jubilee").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(GRASSYHOPPER).title("Grassy Hopper").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}if(q2answer == 3){
map.addMarker(new MarkerOptions().position(NEWYORKSBEST).title("New York's Best").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(SUBWAY).title("Subway").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(PASTIZZERIA).title("Pastizerria").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(MCD).title("Mc Donald's").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.addMarker(new MarkerOptions().position(BURGERKING).title("Burger King").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
if(q3answer == 1){
//implementation
}if(q3answer == 2){
//implementation
}if(q3answer == 3){
//implementation
}if(q3answer == 4){
//implementation
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
Use this
create this class in your package
Code:
public class SharedPrefence{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyPreferences";
// Answers (make variable public to access from outside)
public static final String KEY_ANSWER_TWO = "answer_value2";
//similarly other answers tag can be added(this is the key of preference)
// Constructor
public SharedPrefence(Context context) {
_context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create Answer.
* */
public void createAnswer(int ans) {
// Storing name in pref
editor.putInt(KEY_ANSWER_TWO, ans);
// commit changes
editor.commit();
}
public int getAnswer(String tag,int default) {
return pref.getString(tag, default);
}
}
now create an activity and initialise this class in the starting with the activity context.
next call the create answer method of this class and you are done.
also no need to create sharedprefence in each activity.
and it's even better if you create only one activity and use ViewPager for all questions.you can google for it.
And if this was useful click on thanks below.
:victory::victory::victory::victory:

How do I implement a onscroll Listener to my listview?

I have a large data to load from JSON.
I have implemented a custom list view by following a tutorial, now since the data is huge I want it load as the user scrolls.
This is my LoadRestaurant class code which is inside the main activity.
Code:
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(SearchAll.this, RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
intent.putExtra("login_id", loginId);
startActivity(intent);
}
});
}
});
}
}
}
I want to load around 20 restaurants and then it auto loads another 20 as soon as user reaches the end of first 20.
There are lots of tutorials online but its confusing to implement.
Please help me out!
The custom ListView, support for automatic loading you can try https://github.com/chrisbanes/Android-PullToRefresh

How to draw or erase on a photo loaded onto a Imageview?

As what was stated on the header I want to implement either a "paint" function for user to edit paint/censor unwanted parts of a photo displayed on a imageview before uploading it to a server in the edited format and a redo function if user makes a mistake while editing?
How do I come about doing it, I've read relevant topics on Canvas, or FingerPaint but still puzzled on how to implement it based on my project here? Tried referencing to the links here and here but without success in implementing the codes into my project code due to my lack of programming skills.
Thanks for any help rendered!
Tried integrating the codes below into my code above (image preview after taking a photo with the camera) for user to start editing via painting but still not working? Thanks for any help rendered!
Code:
public class Drawing extends View {
private Paint mPaint, mBitmapPaint;
Intent intent = getIntent();
Bitmap mBitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
private Canvas mCanvas;
private Path mPath;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private int color, size, state;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Integer> colors = new ArrayList<Integer>();
private ArrayList<Integer> sizes = new ArrayList<Integer>();
public Drawing(Context c) {
super(c);
}
public Drawing(Context c,int width, int height, int size, int color, int state) {
super(c);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
// mBitmapPaint = new Paint(Paint.DITHER_FLAG);
// mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
setColor(color);
setSize(size);
setState(state);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
// canvas.drawColor(Color.TRANSPARENT);
// canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
//
// if (state == 0)
// mBitmap.eraseColor(Color.TRANSPARENT);
for (int i = 0; i < paths.size(); i++) {
mPaint.setColor(colors.get(i));
mPaint.setStrokeWidth(sizes.get(i));
canvas.drawPath(paths.get(i), mPaint);
}
mPaint.setColor(color);
mPaint.setStrokeWidth(size);
canvas.drawPath(mPath, mPaint);
}
public void setColor(int color) {
this.color = color;
}
public void setSize(int size) {
this.size = size;
}
public void setState(int state) {
this.state = state;
// if (state == 0)
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
// else
// mPaint.setXfermode(null);
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
sizes.remove(sizes.size() - 1);
colors.remove(colors.size() - 1);
invalidate();
}
}
private void touch_start(float x, float y) {
undonePaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
colors.add(color);
sizes.add(size);
paths.add(mPath);
mPath = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}

Categories

Resources