I'm using jd-alexander liabrary to show direction route on google map and my issue is, when I request another direction route, new route is created but previously created route is not removed. I want to remove the previous route and then show new route.
#Override
public void onRoutingSuccess(ArrayList<Route> routeArrayList, int i) {
//code to add route to map here.
polylines = new ArrayList<>();
if (polylines.size() > 0) {
erasePolylines();
}
polylines = new ArrayList<>();
//add route(s) to the map.
polylines.clear();
for (i = 0; i < routeArrayList.size(); i++) {
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 3);
polyOptions.addAll(routeArrayList.get(i).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylines.add(polyline);
Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + routeArrayList.get(i).
getDistanceValue() + ": duration - " + routeArrayList.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
}
}
private void erasePolylines(){
for(Polyline line : polylines){
line.remove();
}
polylines.clear();
}
How can I fix this?
polylines = new ArrayList<>();
if (polylines.size() > 0) {
for (Polyline poly : polylines) {
poly.remove();
}
erasePolylines();
}
polylines = new ArrayList<>();
//add route(s) to the map.
polylines.clear();
for (i = 0; i < routeArrayList.size(); i++) {
//In case of more than 5 alternative routes
int colorIndex = i % COLORS.length;
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(getResources().getColor(COLORS[colorIndex]));
polyOptions.width(10 + i * 3);
polyOptions.addAll(routeArrayList.get(i).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylines.add(polyline);
Toast.makeText(getApplicationContext(), "Route " + (i + 1) + ": distance - " + routeArrayList.get(i).
getDistanceValue() + ": duration - " + routeArrayList.get(i).getDurationValue(), Toast.LENGTH_SHORT).show();
}
}
Your code is ok, except here:
//You're initializing your list "POLILYNES" and trying remove empty list, Remove the
//lines I commented.
#Override
public void onRoutingSuccess(ArrayList<Route> routeArrayList, int i) {
//code to add route to map here.
polylines = new ArrayList<>(); // DELETE THIS LINE
if (polylines.size() > 0) {
erasePolylines();
}
polylines = new ArrayList<>(); // DELETE THIS LINE
//add route(s) to the map.
polylines.clear();
...
}
Related
So I am working on a project and I don't know much about the android studio. So what I am doing is, I am using jsoup as my web parser and I am creating a list of products from e-commerce websites. So I want that once I get all the details from the parser, then my next activity starts. Till now I am using handler and setting some delay time in it. But that is not helping because sometimes it takes more than 3-4 seconds.
Below is the code by which I am sending the allproduct ArrayList and producturl ArrayList
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST", (Serializable) allproducts);
args.putSerializable("URLLINKS", (Serializable) producturl);
intent.putExtra("BUNDLE", args);
intent.putExtra(EXTRA_TEXT, searchtext);
startActivity(intent);
}
}, 6500);
Sometimes the listview shows only 2 websites result and sometimes it shows every website.
private class Snapdeal extends AsyncTask<String, Void, ArrayList<String>> {
ArrayList<String> tempurlstore = new ArrayList<>();
String link;
#Override
protected void onPostExecute(ArrayList<String> s) {
String product;
String urlstore;
super.onPostExecute(s);
for (int j = 0; j < 6; j++) {
product = s.get(j);
urlstore = tempurlstore.get(j);
allproducts.add(product);
producturl.add(urlstore);
}
String seemore = "See more products on website....";
allproducts.add(seemore);
producturl.add(link);
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
try {
Document doc = Jsoup.connect(strings[0]).get();
Elements links = doc.getElementsByClass("col-xs-6 favDp product-tuple-listing js-tuple ");
ArrayList<String> mainlist = new ArrayList<String>();
mainlist.add("SNAPDEAL");
link = strings[0];
tempurlstore.add("https://www.snapdeal.com");
for (Element link : links) {
String temp1 = null, temp2 = null, temp3 = null, temp4 = null, temp5 = null;
String permanent1 = null;
Elements elLink = link.getElementsByTag("a");
Elements eltitle = link.getElementsByClass("product-title"); //for product title
Elements elpricebefore = link.getElementsByClass("lfloat product-desc-price strike ");
Elements elpriceafter = link.getElementsByClass("lfloat product-price");
Elements discount = link.getElementsByClass("product-discount");
//product title loop
for (Element titleOfProduct : eltitle) {
temp1 = "Title: " + titleOfProduct.text();
}
//product original price loop
for (Element priceOfProductBefore : elpricebefore) {
temp2 = "Price before: " + priceOfProductBefore.text();
}
//product discounted price loop
for (Element priceOfProductAfter : elpriceafter) {
temp3 = "Discounted price: " + priceOfProductAfter.text();
}
//discount in number loop
for (Element productdiscount : discount) {
temp4 = "Discount: " + productdiscount.text();
}
ArrayList<String> linkArray = new ArrayList<String>();
for (Element elementLink : elLink) {
String MainLink = elementLink.attr("href");
linkArray.add(MainLink);
}
for (int j = 0; j < 1; j++) {
temp5 = linkArray.get(0);
}
if (elpricebefore.text()==null)
{
permanent1 = "\n" + temp1 + "\n" + "Price :" + elpriceafter.text() + "\n" + temp4 + "\n";
}
else
{
permanent1 ="\n" + temp1 + "\n" + temp2 + "\n" + temp3 + "\n" + temp4 + "\n";
}
mainlist.add(permanent1);
tempurlstore.add(temp5);
}
return mainlist;
} catch (Exception e) {
ArrayList<String> exception = new ArrayList<String>();
String ex = e.toString();
exception.add(ex);
return exception;
}
}
}
Above is some part of my project. So this is how I am taking all the products and all from the parser.
So how can I do this that once all the products are ready in the Arraylist then only intent gets started?
Please help. Thank you.
Why are you using a timer instead of a callback from your parser? This is creating a race condition which is at the heart of your issue. The only way around it is to fire your intent only after your parser is complete.
Without seeing the parser code it is tough to know the exact place to add your hook.
You shouldn't use a handler for that. What you could do is use an Observer or use Android's Live Data so the one you choose can let you know when the list is ready so you can start the activity.
In my project I have a method that draws a route inside of map and create a bounds for this route, the problem is, I need to create this bounds with the bottom sheet and not the entire screen!
First I open the Bottom Sheet:
private void openBottom(){
if(latLngs != null){
if(bottomSheetBehavior.getState() != BottomSheetBehavior.STATE_EXPANDED){
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
bottomSheetBehavior.setPeekHeight(300);
}
}
}
And then Draw and the bounds!
private void drawnNewRoute() {
if(polyline == null){
LatLngBounds.Builder builder = new LatLngBounds.Builder();
po = new PolylineOptions();
for(int i = 0, tam = latLngs.size(); i < tam; i++){
po.add(latLngs.get(i));
builder.include(latLngs.get(i));
}
String data = new Gson().toJson(latLngs);
po.color(Color.BLACK).width(10);
polyline = mMap.addPolyline(po);
ArrayList<LatLng> latlang = new ArrayList<>();
latlang.add(latLngs.get(0));
latlang.add(latLngs.get(latLngs.size() -1));
mMarkerNewPosition = mMap.addMarker(new MarkerOptions().position(finalLocaltion).title(finalLocationName));
mMarkerNewPosition.showInfoWindow();
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 120));
location_display_incl.setVisibility(View.GONE);
stopLocation();
InicialAddressTxt.setText(InicialAddress);
double finalLat = latLngs.get(latLngs.size() -1).latitude;
double finalLong = latLngs.get(latLngs.size() -1).longitude;
try {
ADRS = getAddress(finalLat,finalLong);
} catch (IOException e) {
e.printStackTrace();
}
FinalAddressTxt.setText(finalLocationName);
String finalComp = ADRS.getLocality() + "," + address.getAdminArea();
FinalComplement.setText(finalComp);
//zoomToCoverAllMarkersInMap(latlang);
}
else{
polyline.setPoints(latLngs);
}
}
But it keeps getting the whole screen and not just the "available" part of it!
I have the grid with my class Geofence. Separately I use leaflet to create layers aka geofence.
When I get geofence from the server I filling the grid and creating and adding layers to FeatureGroup drawnItems. I set up the property of a layer as geofence's id.
Here is the code:
if (200 == response.getStatusCode()) {
JsArray<Geofence> geofenceJsArray = JsonUtils.safeEval(response.getText());
ILayer iLayer;
for (int i = 0; i < geofenceJsArray.length(); i++) {
geofenceStore.add(geofenceJsArray.get(i));
JsArray<Coordinate> coordinateJsArray = geofenceJsArray.get(i).getCoordinates();
if (geofenceJsArray.get(i).getType() == Type.CIRCLE) {
double lat = coordinateJsArray.get(0).getLatitude();
double lon = coordinateJsArray.get(0).getLongitude();
LatLng latLng = new LatLng(lat, lon);
double radius = geofenceJsArray.get(i).getRadius();
Options options = new Options();
iLayer = new Circle(latLng, radius, options);
iLayer.getJSObject().setProperty("_leaflet_id", geofenceJsArray.get(i).getId());
} else {
PolylineOptions polylineOptions = new PolylineOptions();
LatLng[] latLngArray = new LatLng[coordinateJsArray.length()];
for (int j = 0; j < coordinateJsArray.length(); j++) {
double lat = coordinateJsArray.get(i).getLatitude();
double lon = coordinateJsArray.get(i).getLongitude();
latLngArray[j] = new LatLng(lat, lon);
}
iLayer = new Polygon(latLngArray, polylineOptions);
iLayer.getJSObject().setProperty("_leaflet_id", geofenceJsArray.get(i).getId());
}
drawnItems.addLayer(iLayer);
map.addLayer(iLayer);
}
But when I want to remove some geofence like this:
using this code:
if (204 == response.getStatusCode()) {
ILayer layerForRemove = null;
for (int i = 0; i < drawnItems.getLayers().length; i++) {
LoggerHelper.log(className, "_leaflet_id: " + drawnItems.getLayers()[i].getOptions().getProperty("_leaflet_id") + "");
if (selectedGeofence.getId() == Integer.parseInt(drawnItems.getLayers()[i].getOptions().getProperty("_leaflet_id") + "")) {
layerForRemove = drawnItems.getLayers()[i];
}
}
drawnItems.removeLayer(layerForRemove);
geofenceStore.remove(selectedGeofence);
Info.display("Уведомление", "Геозона " + selectedGeofence.getName() + " успешно удалено!");
LoggerHelper.log(className, "Device " + selectedGeofence.getName() + " has been removed. Bye-bye!");
} else {
Info.display("Ошибка", "Не удалось удалить геозону " + selectedGeofence.getName());
LoggerHelper.log(className, "Error while deleting device. " +
"Error code: " + response.getStatusCode() +
". Error status message: " + response.getStatusText());
}
I receiving _leaflet_id as "null" in this line
LoggerHelper.log(className, "_leaflet_id: " + drawnItems.getLayers()[i].getOptions().getProperty("_leaflet_id") + "");
Why? Because I set up it in this line:
iLayer.getJSObject().setProperty("_leaflet_id", geofenceJsArray.get(i).getId());
Thanks in advance for answer!
You shouldn't handle the _leaflet_id private property of Leaflet layers at all. Trying to do so will create unexpected problems.
You are free to add custom properties to Leaflet layers, and keep references to them, e.g.:
var geofencesById = {}
for (...) {
layer = L.polygon(...);
layer._geofence_id = geofenceJsArray.get(i).getId();
geofencesById[ geofenceJsArray.get(i).getId() ] = layer;
}
I am trying to add a scroll function to my code as currently it merely displays the first couple tweets, enough to fill the canvas but no more. How do I go about adding a scroll/click function so the canvas lists other tweets as well?
This is what I have so far with my Twitter API tokens omitted.
import java.util.Date;
import java.util.Arrays;
ArrayList<String> words = new ArrayList();
void setup() {
//Set the size of the stage, and the background to black.
size(750, 750);
background(0);
//Credentials
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("x");
cb.setOAuthConsumerSecret("x");
cb.setOAuthAccessToken("x");
cb.setOAuthAccessTokenSecret("x");
TwitterFactory twitterFactory;
twitterFactory = new TwitterFactory(cb.build());
Twitter twitter = twitterFactory.getInstance();
Query query = new Query("StackOverFow");
query.count(100);
try {
QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();
for (int i = 0; i < tweets.size (); i++) {
Status t = (Status) tweets.get(i);
User u=(User) t.getUser();
String user=u.getName();
String msg = t.getText();
Date d = t.getCreatedAt();
text("User Name - " + user + " Time - " + d + " Message - " + msg,
20, 15+i*50, width-40, 50);
println("Tweet by " + user + " at " + d + ": " + msg);
//Break the tweet into words
String[] input = msg.split(" ");
println(input);
for (int j = 0; j < input.length; j++) {
//Put each word into the words ArrayList
words.add(input[j]);
}
};
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
}
int j=0;
void mousePressed() {
saveData();
}
void saveData() {
String[] data = new String[words.size()];
words.toArray(data);
saveStrings("data/data.txt", data);
}
You already have a handler for mousePressed, adding click and scroll handling is the same concept: add mouseClicked for full click handling, and mouseWheel() for handling scroll events.
I have a LineString featureSource. For one feature from source I want to take intersected lines by startPoint or endPoint from same featureSource.
I tried this for just endPoint:
Filter filter = ff.intersects(ff.literal(featureLastCoordinate), ff.function("endPoint", ff.literal(featureGeom)));
FeatureCollection<SimpleFeatureType, SimpleFeature> intersectedFeatColl = inputSource.getFeatures(filter);
And this:
Filter filter = ff.and(ff.intersects(ff.property(featureGeomPropName), ff.literal(featureLastCoordinate)), ff.function("endPoint", ff.literal(featureGeom)));
I cant find correct expressions for the filter. For example:
I want to get other lines for yellow line.
Depending on how sure you are that the lines touch you can do something like this:
LineString lineString = (LineString) first.getDefaultGeometry();
Point[] points = { lineString.getStartPoint(), lineString.getEndPoint() };
for (Point p : points) {
Filter f = CQL.toFilter("intersects( " + geom + ", " + p + ")");
SimpleFeatureCollection res = featureSource.getFeatures(f);
if (!res.isEmpty()) {
System.out.println("Point " + p + " touches ");
try (SimpleFeatureIterator itr = res.features()) {
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Polygon poly = (Polygon) p.buffer(10);
f = CQL.toFilter("intersects( " + geom + ", " + poly + ")");
res = featureSource.getFeatures(f);
if (!res.isEmpty()) {
System.out.println("Point " + p + " is close to ");
try (SimpleFeatureIterator itr = res.features()) {
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
}