Home > Mobile >  my app is crashing when there is no internet and i want my markers or my map to refresh each second
my app is crashing when there is no internet and i want my markers or my map to refresh each second

Time:11-17

i made a googlemap app where my markers are displyed. the problem is when there no internet, the app is crashing. The code under onResume does not solve the problem. also i want to refresh the map or markers each second on the map. if you have any ideas please i am here to learn from all of you.

here is my MapActivity code :

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback
{
    private static final String TAG = "MapActivity";
    @Bind(R.id.back)
    View back;
    @Bind(R.id.zoom_in)
    View zoom_in;
    @Bind(R.id.zoom_out)
    View zoom_out;
    @Bind(R.id.updatetimer)
    TextView updatetimer;
    @Bind(R.id.autozoom)
    ImageView autozoom;
    @Bind(R.id.showtails)
    ImageView showtails;
    @Bind(R.id.geofences)
    ImageView showGeofences;
    @Bind(R.id.map_layer)
    ImageView map_layer_icon;
    private GoogleMap map;

    @Bind(R.id.content_layout)
    View content_layout;
    @Bind(R.id.loading_layout)
    View loading_layout;
    @Bind(R.id.nodata_layout)
    View nodata_layout;
    private Timer timer;
    private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą

    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;
    private long lastRefreshTime;
    boolean isAutoZoomEnabled = true;
    boolean isShowTitlesEnabled;
    boolean isShowTailsEnabled = true;
    boolean isShowGeofencesEnabled = true;
    private String stopTime;
    private AsyncTask downloadingAsync;

    private boolean isRefreshLoced = false;

    ApiInterface.GetGeofencesResult geofencesResult;
    ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
    float previousZoomLevel = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        ButterKnife.bind(this);
        deviceIdMarkers = new HashMap<>();
        markerIdDevices = new HashMap<>();
        deviceIdPolyline = new HashMap<>();
        deviceIdLastLatLng = new HashMap<>();
        //        deviceIdSmallMarkerInfo = new HashMap<>();

       

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        timer = new Timer();
        timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                runOnUiThread(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        float timeleft = 10 - Math.round(System.currentTimeMillis() - lastRefreshTime) / 1000f;
                        if (timeleft < 0)
                            timeleft = 0;
                        updatetimer.setText(String.format("%.0f", timeleft));
                        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();
        }
    }

    private void refresh()
    {
        if (isRefreshLoced)
            return;
        isRefreshLoced = true;
        lastRefreshTime = System.currentTimeMillis();
        final String api_key = (String) DataSaver.getInstance(this).load("api_key");
        API.getApiInterface(this).getDevices(api_key, getResources().getString(R.string.lang), new Callback<ArrayList<ApiInterface.GetDevicesItem>>()
        {
            @Override
            public void success(final ArrayList<ApiInterface.GetDevicesItem> getDevicesItems, Response response)
            {
                Log.d(TAG, "success: loaded devices array");
                final ArrayList<Device> allDevices = new ArrayList<>();
                if (getDevicesItems != null)
                    for (ApiInterface.GetDevicesItem item : getDevicesItems)
                        allDevices.addAll(item.items);
                API.getApiInterface(MapActivity.this).getFieldsDataForEditing(api_key, getResources().getString(R.string.lang), 1, new Callback<ApiInterface.GetFieldsDataForEditingResult>()
                {
                    @Override
                    public void success(final ApiInterface.GetFieldsDataForEditingResult getFieldsDataForEditingResult, Response response)
                    {
                        Log.d(TAG, "success: loaded icons");
                        downloadingAsync = new AsyncTask<Void, Void, Void>()
                        {
                            ArrayList<MarkerOptions> markers;
                            ArrayList<Integer> deviceIds;

                            @Override
                            protected Void doInBackground(Void... params)
                            {
                                // add markers
                                int dp100 = Utils.dpToPx(MapActivity.this, 50);
                                markers = new ArrayList<>();
                                deviceIds = new ArrayList<>();
                                if (getFieldsDataForEditingResult == null || getFieldsDataForEditingResult.device_icons == null)
                                    return null;
                                for (Device item : allDevices)
                                {
                                    if (isCancelled())
                                        break;
                                    if (item.device_data.active == 1)
                                    {
                                        // ieškom ikonos masyve
                                        DeviceIcon mapIcon = null;
                                        for (DeviceIcon icon : getFieldsDataForEditingResult.device_icons)
                                            if (item.device_data.icon_id == icon.id)
                                                mapIcon = icon;

                                        String server_base = (String) DataSaver.getInstance(MapActivity.this).load("server_base");

                                        try
                                        {
                                            Log.d("MapActivity", "DOWNLOADING BITMAP: "   server_base   mapIcon.path);
                                            Bitmap bmp = BitmapFactory.decodeStream(new URL(server_base   mapIcon.path).openConnection().getInputStream());

                                            int srcWidth = bmp.getWidth();
                                            int srcHeight = bmp.getHeight();

                                            int maxWidth = Utils.dpToPx(MapActivity.this, mapIcon.width);
                                            int maxHeight = Utils.dpToPx(MapActivity.this, mapIcon.height);

                                            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(new LatLng(item.lat, item.lng));
                                            //                                            marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
                                            //                                            marker.setIcon(new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
                                            m.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));

                                            // info window
                                            //                                            MapMarkerInfoWindow infoWindow = new MapMarkerInfoWindow(MapActivity.this, item, R.layout.layout_map_infowindow, map);
                                            //                                            marker.setInfoWindow(infoWindow);

                                            markers.add(m);
                                            deviceIds.add(item.id);
                                        } catch (OutOfMemoryError outOfMemoryError)
                                        {
                                            Toast.makeText(MapActivity.this, "Out of memory! Too many devices are selected to be displayed", Toast.LENGTH_LONG).show();
                                        } catch (Exception e)
                                        {
                                            e.printStackTrace();
                                        }
                                    }
                                }
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid)
                            {
                                ArrayList<GeoPoint> points = new ArrayList<>();

                                if (autoZoomedTimes < 1)
                                {
                                    new Handler().postDelayed(new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            runOnUiThread(new Runnable()
                                            {
                                                @Override
                                                public void run()
                                                {
                                                    if (markers.size() > 1)
                                                    {
                                                        try
                                                        {
                                                            LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                                            for (MarkerOptions item : markers)
                                                                builder.include(item.getPosition());
                                                            LatLngBounds bounds = builder.build();
                                                            //                                int padding = 0; // offset from edges of the map in pixels
                                                            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
                                                            map.animateCamera(cu);
                                                        } catch (Exception e)
                                                        {

                                                        }
                                                    } else if (markers.size() > 0)
                                                    {
                                                        map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
                                                    }
                                                    autoZoomedTimes  ;
                                                }
                                            });
                                        }
                                    }, 50);
                                } else if (isAutoZoomEnabled)
                                {
                                    if (markers.size() > 1)
                                    {
                                        try
                                        {
                                            LatLngBounds.Builder builder = new LatLngBounds.Builder();
                                            for (MarkerOptions item : markers)
                                                builder.include(item.getPosition());
                                            LatLngBounds bounds = builder.build();
                                            //                                int padding = 0; // offset from edges of the map in pixels
                                            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
                                            map.animateCamera(cu);
                                        } catch (Exception e)
                                        {

                                        }
                                    } else if (markers.size() > 0)
                                    {
                                        map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
                                    }
                                    autoZoomedTimes  ;
                                }

                                Log.d(TAG, "onPostExecute: icons downloaded and added to map, total markers: "   markers.size());

                                loading_layout.setVisibility(View.GONE);
                                if (markers.size() != 0)
                                    content_layout.setVisibility(View.VISIBLE);
                                else
                                    nodata_layout.setVisibility(View.VISIBLE);

                                for (int i = 0; i < markers.size(); i  )
                                {
                                    MarkerOptions options = markers.get(i);
                                    int deviceId = deviceIds.get(i);

                                    Marker m;

                                    Polyline polyline;
                                    if (deviceIdMarkers.containsKey(deviceId))
                                    {
                                        Log.d("aa", "moving to"   options.getPosition());
                                        deviceIdMarkers.get(deviceId).setPosition(new LatLng(options.getPosition().latitude, options.getPosition().longitude));
                                        m = deviceIdMarkers.get(deviceId);

                                        polyline = deviceIdPolyline.get(deviceId);
                                    } else
                                    {
                                        Log.d("aa", "putting new");
                                        m = map.addMarker(options);
                                        deviceIdMarkers.put(deviceId, m);
                                        polyline = map.addPolyline(new PolylineOptions());
                                        deviceIdPolyline.put(deviceId, polyline);
                                    }

                                    Device thatonedevice = null;
                                    for (Device device : allDevices)
                                        if (device.id == deviceId)
                                            thatonedevice = device;
                                    markerIdDevices.put(m.getId(), thatonedevice);


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

                                        m.setRotation((float) Math.toDegrees(Math.atan2(dirLng, dirLat)));
                                    }
                                    deviceIdLastLatLng.put(deviceId, 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(MapActivity.this, 2));
                                    polyline.setColor(Color.parseColor(thatonedevice.device_data.tail_color));
                                }


                                // else

                                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>(MapActivity.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(MapActivity.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(MapActivity.this, 300);
                                        map.setPadding(0, px, 0, 0);
                                        stopTime = "...";
                                        final Device device = markerIdDevices.get(marker.getId());
                                        if (device != null)
                                        {
                                            API.getApiInterface(MapActivity.this).deviceStopTime((String) DataSaver.getInstance(MapActivity.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(MapActivity.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();
                    }

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

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

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        map = googleMap;
        refresh();
    }

this MapActivity is slow to load, could you teach me a way to make it goes faster? Best regard :) waiting for your propositions. PS: i have removed some functions to make the code look short but i kept the most important in is case.

CodePudding user response:

For the crashing issue create a class


public class NetWorkChecker {
    static NetworkInfo wifi, mobile;

    public static Boolean check(Context c) {

        ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (wifi != null && wifi.isConnected() && wifi.isAvailable()) {

            return true;
        } else if (mobile != null && mobile.isAvailable() && mobile.isConnected()) {

            return true;
        } else {
            //Toast.makeText(c, "No Network Connection", Toast.LENGTH_SHORT).show();
           // ((Activity) c).finish();
            displayMobileDataSettingsDialog(c,"No Network Connection","No Network Connection");
            return false;
        }

    }

    public static AlertDialog displayMobileDataSettingsDialog(final Context context, String title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setCancelable(false);
        builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
                context.startActivity(intent);
            }
        });

        builder.show();
        return builder.create();
    }

}

to check if the devise have an active internet connection call

if (!NetWorkChecker.check(this)){

////do your refres

}



  • Related