0

got this message and i do not know how to solve it. i'm getting data from a device (latitude, longitude, device_name, altitude). when trying to get the device in real time moving i got this Log:

W/System.err: java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable
W/System.err:     at com.gabontech.gprstrack.activities.CurrentePositionActivity$6.doInBackground(CurrentePositionActivity.java:254)
W/System.err:     at com.gabontech.gprstrack.activities.CurrentePositionActivity$6.doInBackground(CurrentePositionActivity.java:242)
W/System.err:     at android.os.AsyncTask$3.call(AsyncTask.java:378)
W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err:     at java.lang.Thread.run(Thread.java:919)

i don't understand why. is there any probleme with my marker? please help . Also the marker does not move on the map. There is a mistake somewhere!

here is me code:

public class CurrentePositionActivity extends DrawerBaseActivity implements OnMapReadyCallback {
ActivityCurrentePositionBinding activityCurrentePositionBinding;
    private static final String TAG = "Mappoisition Activity";
    private GoogleMap map;
    private String stopTime;
    private boolean isRefreshLoced = false;
    private long lastRefreshTime;

    private Timer timer;
    private AsyncTask downloadingAsync;
    private Marker m;
    ImageButton zoomin,zoomout;
    ImageButton map_layer_icon, maplayer;
    RelativeLayout content_layout, nodata_layout;
    private int autoZoomedTimes = 0;
    private HashMap<Integer, Marker> deviceIdMarkers;
    private HashMap<String, Device> markerIdDevices;
    private HashMap<Integer, Polyline> deviceIdPolyline;
    private HashMap<Integer, LatLng> deviceIdLastLatLng;
    // private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
    boolean isAutoZoomEnabled = false;
    boolean isTrafficEnabled = true;
    boolean isShowTailsEnabled = true;
    boolean isShowGeofencesEnabled = true;
    private boolean isMaptraficactived = true;
    ApiInterface.GetGeofencesResult geofencesResult;
    ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();

    ArrayList<HistoryItem> historyItems;
    ApiInterface.GetHistoryResult getHistoryResult;
    ArrayList<HistoryItemCoord> historyItemCoords;
    ArrayList<HistoryItemClass> historyItemClasses;
    HistoryItem item;
    Device device ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityCurrentePositionBinding = ActivityCurrentePositionBinding.inflate(getLayoutInflater());
        setContentView(activityCurrentePositionBinding.getRoot());
        ButterKnife.bind(this);

        //fin de declaration de boutons
        deviceIdMarkers = new HashMap<>();
        markerIdDevices = new HashMap<>();
        deviceIdPolyline = new HashMap<>();
        deviceIdLastLatLng = new HashMap<>();

        zoomin = findViewById(R.id.zoom_in);
        zoomout = findViewById(R.id.zoom_out);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        if (mapFragment != null) {
            mapFragment.getMapAsync(this);
        }

        item = new Gson().fromJson(getIntent().getStringExtra("item"), HistoryItem.class);
           device = new Gson().fromJson(getIntent().getStringExtra("device"), Device.class);


        zoomin.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                map.animateCamera(CameraUpdateFactory.zoomIn());
            }
        });


        zoomout.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                map.animateCamera(CameraUpdateFactory.zoomOut());
            }
        });
    }

                    

    
    @Override
    protected void onResume()
    {
        super.onResume();
        timer = new Timer();
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                runOnUiThread(() -> {
                    float timeleft = 10 - Math.round(System.currentTimeMillis() - lastRefreshTime) / 1000f;
                    if (System.currentTimeMillis() - lastRefreshTime >= 10 * 1000)
                        if (map != null)
                            refresh();
                });
            }
        }, 0, 1000);
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        try
        {
            timer.cancel();
            timer.purge();
            downloadingAsync.cancel(true);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {

        map = googleMap;
        refresh();
        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        
    }
    private void refresh(){
                          device = new Gson().fromJson(getIntent().getStringExtra("device"), Device.class);
                          LatLng geopoint = new LatLng(Double.valueOf(device.lat), Double.valueOf(device.lng));
                        if (isRefreshLoced)
                        return;
                        isRefreshLoced = true;
                        lastRefreshTime = System.currentTimeMillis();
                        Log.d(TAG, "success: loaded icons");
                        downloadingAsync = new AsyncTask<Void, Void, Void>() {
                            MarkerOptions marker = new MarkerOptions();
                            int deviceId = device.id;
                            @Override
                            protected Void doInBackground(Void... params)
                            {
                                          int dp100 = Utils.dpToPx(CurrentePositionActivity.this, 50);
                                        String server_base = (String) DataSaver.getInstance(CurrentePositionActivity.this).load("server_base");
                                       // LatLng geopoint = new LatLng(Double.valueOf(device.lat), Double.valueOf(device.lng));
                                        try
                                        {
                                            Drawable dr = getResources().getDrawable(R.drawable.ic_direction);
                                            Bitmap bmp = ((BitmapDrawable) dr).getBitmap();
                                            int srcWidth = bmp.getWidth();
                                            int srcHeight = bmp.getHeight();

                                            int maxWidth = Utils.dpToPx(CurrentePositionActivity.this, 40);
                                            int maxHeight = Utils.dpToPx(CurrentePositionActivity.this, 40);

                                            float ratio = Math.min((float) maxWidth / (float) srcWidth, (float) maxHeight / (float) srcHeight);
                                            int dstWidth = (int) (srcWidth * ratio);
                                            int dstHeight = (int) (srcHeight * ratio);

                                            bmp = bmp.createScaledBitmap(bmp, dp100, dp100, true);

                                            // marker
                                            MarkerOptions m = new MarkerOptions();
                                            m.position(geopoint);
                                            m.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
                                            // info windo
                                            map.addMarker(m);
                                            map.moveCamera(CameraUpdateFactory.newCameraPosition(CameraPosition.fromLatLngZoom(geopoint, 14)));
                                        } catch (OutOfMemoryError outOfMemoryError)
                                        {
                                            Toast.makeText(CurrentePositionActivity.this, "votre balise" + device.name, Toast.LENGTH_LONG).show();
                                        } catch (Exception e)
                                        {
                                            e.printStackTrace();
                                        }
                                return null;
                            }
                            @Override
                            protected void onPostExecute(Void aVoid){
                                if (autoZoomedTimes < 1)
                                {
                                    new Handler().postDelayed(new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            runOnUiThread(new Runnable()
                                            {
                                                @Override
                                                public void run()
                                                {
                                                    if (marker != null)
                                                    {
                                                        try
                                                        {
                                                            LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                                                builder.include(new LatLng(Double.valueOf(device.lat), Double.valueOf(device.lng)));
                                                            LatLngBounds bounds = builder.build();
                                                            //                                int padding = 0; // offset from edges of the map in pixels
                                                            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(CurrentePositionActivity.this, 50));
                                                            map.animateCamera(cu);
                                                        } catch (Exception e)
                                                        {

                                                        }
                                                    }
                                                    autoZoomedTimes++;
                                                }
                                            });
                                        }
                                    }, 50);
                                } else if (isAutoZoomEnabled)
                                {
                                    try
                                    {

                                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                            builder.include(m.getPosition());
                                        LatLngBounds bounds = builder.build();
                                        //                                int padding = 0; // offset from edges of the map in pixels
                                        CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(CurrentePositionActivity.this, 50));
                                        map.animateCamera(cu);
                                    } catch (Exception ignored)
                                    {

                                    }
                                    map.moveCamera(CameraUpdateFactory.newLatLngZoom(geopoint, 15));
                                    autoZoomedTimes++;
                                }

                                Log.d(TAG, "onPostExecute: icons downloaded and added to map, total markers: " + geopoint);
                                    Marker m;

                                    Polyline polyline;
                                    if (deviceIdMarkers.containsKey(deviceId))
                                    {
                                        Log.d("aa", "moving to" + marker.getPosition());
                                        Objects.requireNonNull(deviceIdMarkers.get(deviceId)).setPosition(new LatLng(device.lat, device.lng));
                                        m = deviceIdMarkers.get(deviceId);

                                        polyline = deviceIdPolyline.get(deviceId);
                                    } else
                                    {
                                        Log.d("aa", "putting new");
                                        m = map.addMarker(new MarkerOptions().position(new LatLng(Double.valueOf(device.lat), Double.valueOf(device.lng))));
                                        deviceIdMarkers.put(device.id, m);
                                        polyline = map.addPolyline(new PolylineOptions());
                                        deviceIdPolyline.put(device.id, polyline);
                                    }

                                    Device thatonedevice = null;
                                            thatonedevice = device;
                                assert m != null;
                                markerIdDevices.put(m.getId(), thatonedevice);


                                    // update marker rotation based on driving direction
                                    if (thatonedevice != null && deviceIdLastLatLng.containsKey(deviceId))
                                    {
                                        double dirLat = thatonedevice.lat - Objects.requireNonNull(deviceIdLastLatLng.get(deviceId)).latitude;
                                        double dirLng = thatonedevice.lng - Objects.requireNonNull(deviceIdLastLatLng.get(deviceId)).longitude;

                                        m.setRotation((float) Math.toDegrees(Math.atan2(dirLng, dirLat)));
                                    }
                                    deviceIdLastLatLng.put(device.id, new LatLng(thatonedevice.lat, thatonedevice.lng));

                                    List<LatLng> polylinePoints = new ArrayList<>();
                                    for (TailItem item : thatonedevice.tail)
                                        polylinePoints.add(new LatLng(Double.valueOf(item.lat), Double.valueOf(item.lng)));
                                    polyline.setPoints(polylinePoints);
                                    polyline.setWidth(Utils.dpToPx(CurrentePositionActivity.this, 2));
                                    polyline.setColor(Color.parseColor(thatonedevice.device_data.tail_color));

                                map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
                                {
                                    @Override
                                    public View getInfoWindow(Marker marker)
                                    {
                                        return null;
                                    }

                                    @Override
                                    public View getInfoContents(final Marker marker)
                                    {
                                        synchronized (this)
                                        {

                                        }
                                        final Device device = markerIdDevices.get(marker.getId());
                                        if (device != null)
                                        {
                                            View view = getLayoutInflater().inflate(R.layout.layout_map_infowindow, null);
                                            view.bringToFront();
                                            view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener()
                                            {
                                                @Override
                                                public void onClick(View v)
                                                {
                                                    marker.hideInfoWindow();
                                                }
                                            });
                                            TextView device_name = (TextView) view.findViewById(R.id.device_name);
                                            device_name.setText(device.name);
                                            TextView altitude = (TextView) view.findViewById(R.id.altitude);
                                            altitude.setText(String.valueOf(device.altitude) + " " + device.unit_of_altitude);
                                            TextView time = (TextView) view.findViewById(R.id.time);
                                            time.setText(device.time);
                                            TextView stopTimeView = (TextView) view.findViewById(R.id.stopTime);
                                            stopTimeView.setText(stopTime);
                                            TextView speed = (TextView) view.findViewById(R.id.speed);
                                            speed.setText(device.speed + " " + device.distance_unit_hour);
                                            TextView address = (TextView) view.findViewById(R.id.address);
                                            address.setText(device.address);

                                            final ArrayList<Sensor> showableSensors = new ArrayList<>();
                                            for (Sensor item : device.sensors)
                                                if (item.show_in_popup > 0)
                                                    showableSensors.add(item);

                                            ListView sensors_list = (ListView) view.findViewById(R.id.sensors_list);
                                            sensors_list.setAdapter(new AwesomeAdapter<Sensor>(CurrentePositionActivity.this)
                                            {
                                                @Override
                                                public int getCount()
                                                {
                                                    return showableSensors.size();
                                                }

                                                @NonNull
                                                @Override
                                                public View getView(int position, View convertView, @NonNull ViewGroup parent)
                                                {
                                                    if (convertView == null)
                                                        convertView = getLayoutInflater().inflate(R.layout.adapter_map_sensorslist, null);

                                                    Sensor item = showableSensors.get(position);
                                                    TextView name = (TextView) convertView.findViewById(R.id.name);
                                                    name.setText(item.name);
                                                    TextView value = (TextView) convertView.findViewById(R.id.value);
                                                    value.setText(item.value);
                                                    return convertView;
                                                }
                                            });

                                            List<Address> addresses;
                                            try
                                            {
                                                addresses = new Geocoder(CurrentePositionActivity.this).getFromLocation(device.lat, device.lng, 1);
                                                if (addresses.size() > 0)
                                                    address.setText(addresses.get(0).getAddressLine(0));
                                            } catch (IOException e)
                                            {
                                                e.printStackTrace();
                                            }
                                            return view;
                                        }
                                        return null;
                                    }
                                });
                                map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
                                {
                                    @Override
                                    public boolean onMarkerClick(final Marker marker)
                                    {
                                        int px = Utils.dpToPx(CurrentePositionActivity.this, 300);
                                        map.setPadding(0, px, 0, 0);
                                        stopTime = "...";
                                        final Device device = markerIdDevices.get(marker.getId());
                                        if (device != null)
                                        {
                                            API.getApiInterface(CurrentePositionActivity.this).deviceStopTime((String) DataSaver.getInstance(CurrentePositionActivity.this).load("api_key"), "en", device.id, new Callback<ApiInterface.DeviceStopTimeResult>()
                                            {
                                                @Override
                                                public void success(ApiInterface.DeviceStopTimeResult result, Response response)
                                                {
                                                    stopTime = result.time;
                                                    marker.showInfoWindow();
                                                }

                                                @Override
                                                public void failure(RetrofitError retrofitError)
                                                {
                                                    Toast.makeText(CurrentePositionActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
                                                }
                                            });
                                        }

                                        return false;
                                    }
                                });
                                map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
                                {
                                    @Override
                                    public void onInfoWindowClick(Marker marker)
                                    {
                                        marker.hideInfoWindow();
                                    }
                                });

                                map.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener()
                                {
                                    @Override
                                    public void onInfoWindowClose(Marker marker)
                                    {
                                        map.setPadding(0, 0, 0, 0);
                                    }
                                });
                                //                                updateSmallMarkerData(allDevices);
                                isRefreshLoced = false;
                            }
                        }.execute();

                    }


    private void putGeofenceNameMarkers(int textSize) {
        for (Geofence geofence : geofencesResult.items.geofences)
        {
            if (geofence.active == 1)
            {
                String strText = geofence.name;

                Paint.FontMetrics fm = new Paint.FontMetrics();
                Paint paintText = new Paint();
                paintText.setColor(Color.parseColor(geofence.polygon_color));
                paintText.setTextAlign(Paint.Align.CENTER);
                paintText.setTypeface(Typeface.create(Typeface.DEFAULT, Typeface.BOLD));
                paintText.getFontMetrics(fm);

                Rect rectText = new Rect();
                paintText.getTextBounds(strText, 0, strText.length(),
                        rectText);
                Bitmap.Config conf = Bitmap.Config.ARGB_8888;
                Bitmap bmpText = Bitmap.createBitmap(rectText.width(),
                        rectText.height(), conf);
                Canvas canvas = new Canvas(bmpText);
                canvas.drawText(strText, canvas.getWidth() / 2,
                        canvas.getHeight() - rectText.bottom, paintText);
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(centroid(geofence.coordinatesList))
                        .icon(BitmapDescriptorFactory.fromBitmap(bmpText))
                        .anchor(0.5f, 1);
                Marker marker = map.addMarker(markerOptions);
                polygonsWithDetails.add(new PolygonWithName(map.addPolygon(new PolygonOptions()
                        .addAll(geofence.coordinatesList)
                        .strokeColor(Color.parseColor(geofence.polygon_color))
                        .fillColor(Color.parseColor("#59" + geofence.polygon_color.substring(1))))
                        , paintText, markerOptions, marker, geofence));
            }
        }
    }

    private LatLng centroid(List<LatLng> points)
    {
        double[] centroid = {0.0, 0.0};

        for (int i = 0; i < points.size(); i++)
        {
            centroid[0] += points.get(i).latitude;
            centroid[1] += points.get(i).longitude;
        }

        int totalPoints = points.size();
        centroid[0] = centroid[0] / totalPoints;
        centroid[1] = centroid[1] / totalPoints;

        return new LatLng(centroid[0], centroid[1]);
    }

}

1 Answers1

0

Bitmap bmp = ((BitmapDrawable) dr).getBitmap();

dr is a VectorDrawable and cannot be cast to BitmapDrawable.

To get the bitmap of it, can refer to: Getting Bitmap from vector drawable

TylerQITX
  • 318
  • 2
  • 9