-1

As I am new to android I couldn't fix this skipped 1000+ frames issue.Help me to sort out this and help me to add loading progress bar while this skipping frames action takes place before opening map. This is my map code.

RouteMap.java

public class RouteMap extends android.support.v4.app.FragmentActivity
        implements OnClickListener, OnInfoWindowClickListener,
        DirecitonReceivedListener, OnMapReadyCallback {
    public List<String> destinations;
    ImageView img_home, img_menu;
    private GoogleMap mMap;
    ProgressDialog prgDialog;
    model modelData;
    private Button btnDirection;
    double latitude, longitude;
    LinearLayout linear_back;
    LatLng startPosition, start;
    String startPositionTitle;
    Vibrator vibrator;
    String startPositionSnippet;
    Double desc1_long, desc1_lat;
    LatLng destinationPosition1;
    String destinationPositionTitle;
    String destinationPositionSnippet;
    MarkerOptions mDestination1, mStart;
    ToggleButton tbMode;
    GPSTracker gps;
    Geocoder gCoder;
    ArrayList<Address> addresses = null;
    ArrayList<Address> adres2 = null;
    SupportMapFragment mapFragment;
    public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
    TextView back_txt;
    openMap openMap;
    String mapStatus = "start";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_map);
        back_txt = (TextView) findViewById(R.id.txt_back);

        try {
            back_txt = (TextView) findViewById(R.id.txt_back);
            modelData = model.getInstance();
            vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
            gps = new GPSTracker(RouteMap.this);
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            gCoder = new Geocoder(RouteMap.this);
            addresses = (ArrayList<Address>) gCoder.getFromLocation(latitude, longitude, 1);

            tbMode = (ToggleButton) findViewById(R.id.tbMode);
            mapFragment = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map));
            mapFragment.getMapAsync(this);
            btnDirection = (Button) findViewById(R.id.btnDirection);
            btnDirection.setOnClickListener(this);
            tbMode.setChecked(true);

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
        }

    }

    public int calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {

        final int R = 6371;
        try {
            Double latDistance = deg2rad(venueLat - userLat);
            Double lonDistance = deg2rad(venueLng - userLng);
            Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                    + Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(venueLat))
                    * Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
            Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
            double distance = R * c * 1000; // convert to meters

            double height = 0 - 0;
            distance = Math.pow(distance, 2) + Math.pow(height, 2);
            return (int) Math.sqrt(distance);
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(), "Please Check your Destination's GeoCode ", Toast.LENGTH_LONG).show();
        }
        return 0;
    }

    private double deg2rad(double deg) {return (deg * Math.PI / 180.0);}
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap=googleMap;
        //setUpMap();

        try {
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            mMap.setMyLocationEnabled(true);
            mMap.setIndoorEnabled(true);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
            mMap.getUiSettings().setCompassEnabled(true);
            mMap.getUiSettings().setAllGesturesEnabled(true);

            String[] arr = new String[modelData.outletList.size()];

            for(int i=0;i<modelData.outletList.size();i++)
            {
                String str1 = modelData.outletList.get(i)[2];
                String str2 = modelData.outletList.get(i)[3];
                String newString = str1+","+str2;
                arr[i] = newString;
            }
            String[] latTempArr = arr;
            String strKey = "";
            double curLatitude = latitude;
            double curLongtitude = longitude;
            double desLat;
            double desLng;

            Map<String, Integer> final_arr = new HashMap<String, Integer>();
            Map<String, Integer> final_arr2 = new HashMap<String, Integer>();
            List<Integer> intTempArr = new ArrayList<Integer>();
            List<Integer> intTempArr2 = new ArrayList<Integer>();

            for(int j=0;j<arr.length;j++)
            {
                intTempArr =  new ArrayList<Integer>();
                for (int k=0;k<latTempArr.length;k++)
                {
                    String[] arr_temp = latTempArr[k].split(",");
                    //System.out.println(arr_temp[0]);
                    desLat = Double.parseDouble(arr_temp[0]);
                    desLng = Double.parseDouble(arr_temp[1]);
                    int temp = calculateDistance(curLatitude,curLongtitude,desLat,desLng);
                    intTempArr.add(temp);

                    final_arr.put(latTempArr[k],temp);
                }

                Collections.sort(intTempArr);

                Integer[] array = new Integer[intTempArr.size()];
                intTempArr.toArray(array);

                for (Map.Entry<String, Integer> entry : final_arr.entrySet()) {

                    try{
                        if (entry.getValue().equals(array[0])) { //get next best path

                            List<String> list = new ArrayList<String>(Arrays.asList(latTempArr)); // remove the best path to find next one
                            list.remove(entry.getKey());
                            latTempArr = list.toArray(new String[0]);

                            String[] arr_temp2 = entry.getKey().split(",");
                            //System.out.println(arr_temp[0]);
                            curLatitude = Double.parseDouble(arr_temp2[0]);
                            curLongtitude = Double.parseDouble(arr_temp2[1]);
                            strKey = entry.getKey();
                            intTempArr2.add(entry.getValue());
                            final_arr2.put(strKey,entry.getValue());
                        }
                    }
                    catch(Exception e)
                    {

                    }

                }
                //System.out.println(intTempArr);
            }

            //int i = 0;
            destinations = new ArrayList<String>();
            for(int i =0;i<intTempArr2.size();i++) {
                for(String Key : final_arr2.keySet()) {
                    //System.out.println();
                    if(final_arr2.get(Key) == intTempArr2.get(i)) {
                        destinations.add(Key);
                        break;
                    }
                }
            }

            System.out.println(destinations);
            for(int i = 0;i < destinations.size();i++) {
                //Toast.makeText(getApplicationContext(), " ListItem : " + i, Toast.LENGTH_LONG).show();
                String desti1 = destinations.get(i);
                String[] des = desti1.split(",");
                desc1_lat = Double.parseDouble(des[0]);
                desc1_long = Double.parseDouble(des[1]);

                startPosition = new LatLng(latitude, longitude);
                startPositionTitle = addresses.get(0).getLocality();
                startPositionSnippet = addresses.get(0).getAddressLine(1)+"," +" "+ addresses.get(0).getAddressLine(2);

                try {
                    adres2 = (ArrayList<Address>) gCoder.getFromLocation(desc1_lat, desc1_long, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                destinationPosition1 = new LatLng(desc1_lat, desc1_long);
                destinationPositionTitle = adres2.get(0).getLocality();
                destinationPositionSnippet =adres2.get(0).getAddressLine(1)+"," +" "+adres2.get(0).getAddressLine(2);
                // mMap.setOnInfoWindowClickListener(this);

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

                    @Override
                    public View getInfoContents(Marker marker) {
                        View v = getLayoutInflater().inflate(R.layout.marker, null);

                        TextView info= (TextView) v.findViewById(R.id.info);

                        info.setText(marker.getSnippet().toString());

                        return v;
                    }
                });

                mDestination1 = new MarkerOptions()
                        .position(destinationPosition1)
                        .title(destinationPositionTitle)
                        .snippet(destinationPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));

                mStart = new MarkerOptions()
                        .position(startPosition)
                        .title(startPositionTitle)
                        .snippet(startPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));

                mMap.addMarker(mDestination1);
                mMap.addMarker(mStart);

                latitude = desc1_lat;
                longitude = desc1_long;
                LatLng locations = new LatLng(latitude,longitude);
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 5.5f));
            }
        }catch (Exception ex)
        {
            /*Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();*/
        }

    }

    public void clearMap() {
        mMap.clear();
    }

    @Override
    public void onClick(View v) {
        try
        {
            Locale mLocale = new Locale("en");
            Log.d("Display language = ", "" + mLocale.getDisplayLanguage());


            gCoder = new Geocoder(RouteMap.this,mLocale);
            gps = new GPSTracker(RouteMap.this);
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();


            for(int i = 0;i<destinations.size();i++) {
                String desti1 = destinations.get(i);
                String[] des = desti1.split(",");
                desc1_lat = Double.parseDouble(des[0]);
                desc1_long = Double.parseDouble(des[1]);

                startPosition = new LatLng(latitude, longitude);

                startPositionTitle = addresses.get(0).getLocality();
                startPositionSnippet = addresses.get(0).getAddressLine(1)+","+" "+addresses.get(0).getAddressLine(2);


                destinationPosition1 = new LatLng(desc1_lat, desc1_long);
                destinationPositionTitle = adres2.get(0).getLocality();
                destinationPositionSnippet =adres2.get(0).getAddressLine(1)+","+""+ adres2.get(0).getAddressLine(2);

                mMap.setOnInfoWindowClickListener(this);

                mStart = new MarkerOptions()
                        .position(startPosition)
                        .title(startPositionTitle)
                        .snippet(startPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));

                mDestination1 = new MarkerOptions()
                        .position(destinationPosition1)
                        .title(destinationPositionTitle)
                        .snippet(destinationPositionSnippet)
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));

                if (v == btnDirection) {
                    //  clearMap();

                    mMap.addMarker(mDestination1);
                    mMap.addMarker(mStart);

                    if (tbMode.isChecked()) {

                        new GetRotueListTask(RouteMap.this, startPosition,
                                destinationPosition1, GMapV2Direction.MODE_DRIVING, this)
                                .execute();

                    } else {
                        new GetRotueListTask(RouteMap.this, startPosition,
                                destinationPosition1, GMapV2Direction.MODE_WALKING, this)
                                .execute();
                    }
                }
                latitude = desc1_lat;
                longitude = desc1_long;



            }
        }catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public void OnDirectionListReceived(List<LatLng> mPointList) {
        try
        {
            if (mPointList != null) {
                PolylineOptions rectLine = new PolylineOptions().width(10).color(
                        Color.RED);
                for (int i = 0; i < mPointList.size(); i++) {
                    rectLine.add(mPointList.get(i));
                }
                mMap.addPolyline(rectLine);

                gps = new GPSTracker(RouteMap.this);
                latitude = gps.getLatitude();
                longitude = gps.getLongitude();

                start = new LatLng(latitude, longitude);


                CameraPosition mCPFrom = new CameraPosition.Builder()
                        .target(start).zoom(15.5f).bearing(0).tilt(25)
                        .build();
                final CameraPosition mCPTo = new CameraPosition.Builder()
                        .target(destinationPosition1).zoom(15.5f).bearing(0)
                        .tilt(50).build();

                changeCamera(CameraUpdateFactory.newCameraPosition(mCPFrom),
                        new CancelableCallback() {
                            @Override
                            public void onFinish() {
                                changeCamera(CameraUpdateFactory
                                                .newCameraPosition(mCPTo),
                                        new CancelableCallback() {

                                            @Override
                                            public void onFinish() {

                                                LatLngBounds bounds = new LatLngBounds.Builder()
                                                        .include(start)
                                                        .include(
                                                                destinationPosition1)
                                                        .build();
                                                changeCamera(
                                                        CameraUpdateFactory
                                                                .newLatLngBounds(
                                                                        bounds, 50),
                                                        null, false);
                                            }

                                            @Override
                                            public void onCancel() {
                                            }
                                        }, false);
                            }

                            @Override
                            public void onCancel() {
                            }
                        }, true);
            }
        }catch (Exception ex)
        {
            Toast.makeText(getApplicationContext(), "Please Check your Data Connection", Toast.LENGTH_LONG).show();
        }

    }

    private void changeCamera(CameraUpdate update, CancelableCallback callback,
                              boolean instant) {

        if (instant) {
            mMap.animateCamera(update, 1, callback);
        } else {
            mMap.animateCamera(update, 4000, callback);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onInfoWindowClick(Marker marker) {

    }


    private class openMap extends AsyncTask<String, Void, String>
    {
        ProgressDialog mProgressDialog;
        Context ctx;
        public openMap(Context ctx)
        {
            this.ctx=ctx;
            mProgressDialog = new ProgressDialog(RouteMap.this);
        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.setMessage("Loading Map..Please wait....");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            // Toast.makeText(getApplicationContext(), "Syncing DB...", Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(String... urls)
        {
            return "Success";
        }

        @Override
        protected void onPostExecute(String result)
        {
            mProgressDialog.dismiss();

            try
            {
                if(result.equalsIgnoreCase("Success")) {

                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
                }

            }catch (Exception e){}


        }
    }
}

From this code above what changes should I make to fix the Skipped 1000+ frames issue and also help me add loader before opening the map...

Vishal Vaishnav
  • 3,346
  • 3
  • 26
  • 57
s.vijay
  • 31
  • 8

2 Answers2

0

The code that you write in OnMapReady function is to much, please remove that code from there I can see there are more then 4 "for" loops in onMapReady, move that part to to some where else like OnCreate() create all maps and lists that you want.

Just ues OnMapReady function for placing markers

Samarth Sevak
  • 521
  • 4
  • 16
  • even if i try placing the loop part in separate function, map is not displaying the required ouput,It shows only my location....But the above code displays the correct output but it takes lot of time loading saying skipped frames – s.vijay Aug 10 '17 at 08:44
  • Do you know why it shows that ? The main reason is that you use the main app's UI thread do perform the same so it skips the similar type of frames and the render the main UI – Samarth Sevak Aug 10 '17 at 10:30
  • can u pls explain me hw do i want to make the changes? – s.vijay Aug 10 '17 at 10:48
  • TRY THIS.... RUNONUI THREAD.....................................new Handler().post(new Runnable() { @Override public void run() { // Code here will run in UI thread } }); – Samarth Sevak Aug 10 '17 at 10:59
0

Geocoder.getFromLocation() is an expensive call that does a network call to Google's servers, so don't make it on the UI thread.

Have a look at Processes and Threads in the android developer docs for various ways of making the request in the background.

AndrewR
  • 10,759
  • 10
  • 45
  • 56