mardi 14 juin 2016

ArrayList.throwIndexOutOfBoundsException Android studio

After launching app, I Click On category, it shows 1 store, after clicking on that store it shows detail, now I back to listing. re-click on same store, it shows below error and crash the app.

Below is the error I receive:

    E/AndroidRuntime: FATAL EXCEPTION: main
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at java.util.ArrayList.get(ArrayList.java:304)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at freak.store.Home$getstoredetail1$1.onItemClick(Home.java:437)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.widget.AdapterView.performItemClick(AdapterView.java:298)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.widget.AbsListView.performItemClick(AbsListView.java:1086)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.widget.AbsListView$PerformClick.run(AbsListView.java:2855)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.widget.AbsListView$1.run(AbsListView.java:3529)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:615)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:4745)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-14 14:20:08.773 7754-7754/freak.store E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
06

below is the code:

public class Gmap extends FragmentActivity {
private GoogleMap googleMap;
private HashMap<CustomMarker, Marker> markersHashMap;
private Iterator<Entry<CustomMarker, Marker>> iter;
private CameraUpdate cu;
private CustomMarker customMarkerOne, customMarkerTwo, customMarkerThree;
private CustomMarker customMarkersrc, customMarkerdest;

Button btn_map, btn_detail;
Button btn_root, btn_circle, btn_zoom, btn_arrow, btn_current;

String lat, lng, map, nm, ad, id, rate, latitude, longitude;
int locationCount = 0;
int start = 0;
String key;
String Error;
Button btn_anim;
boolean anim = true;
String load;
String name, address, idf, ratting;

SharedPreferences sharedPreferences;

PopupWindow popup;
ArrayList<Storegetset> rest1;

ProgressDialog progressDialog;

String[] separateddata;
View layout12;

Boolean isInternetPresent = false;
ConnectionDetector cd;

GPSTracker gps;
double latitudecur;
double longitudecur;


v2GetRouteDirection v2GetRouteDirection;
Document document;
LatLng fromPosition;
LatLng toPosition;
double destlat, destlng;
MarkerOptions markerOptions;
Marker newMark;
MySupportMapFragment customMapFragment;
Projection projection;
private ArrayList<LatLng> arrayPoints = null;

// PolylineOptions polylineOptions;
private View mMapShelterView;
public static final String MY_PREFS_NAME = "Store";
private GestureDetector mGestureDetector;
private boolean mDrawFinished = false;
private ArrayList<LatLng> mLatlngs = new ArrayList<LatLng>();
private PolylineOptions mPolylineOptions;
private PolygonOptions mPolygonOptions;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gmap);



    v2GetRouteDirection = new v2GetRouteDirection();
    cd = new ConnectionDetector(getApplicationContext());

    isInternetPresent = cd.isConnectingToInternet();
    // check for Internet status
    if (isInternetPresent) {
        // Internet Connection is Present
        // make HTTP requests
        // showAlertDialog(getApplicationContext(), "Internet Connection",
        // "You have internet connection", true);
        arrayPoints = new ArrayList<LatLng>();
        markersHashMap = new HashMap<CustomMarker, Marker>();
        gps = new GPSTracker(Gmap.this);
        // check if GPS enabled
        if (gps.canGetLocation()) {
            try {
                latitudecur = gps.getLatitude();
                longitudecur = gps.getLongitude();

                Log.d("latlng", "" + latitude + " : " + longitude);
            } catch (NumberFormatException e) {
                // TODO: handle exception
            }


            // n is for new line

        } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }

        initialize();
        getintent();

        try {
            // Loading map
            initilizeMap();
            initializeUiSettings();
            initializeMapLocationSettings();
            initializeMapTraffic();
            initializeMapType();
            initializeMapViewSettings();

        } catch (Exception e) {
            e.printStackTrace();
        }
        // markerOptions = new MarkerOptions();
        // getting latitude and longitude from this class
        Log.d("loadornot", ""+load);

        try {
            rest1=Home.rest;


            Log.d("size", ""+rest1.size());
            setCustomMarkerOnePosition();
            //new getstoredetail().execute();
            fromPosition = new LatLng(latitudecur, longitudecur);
            toPosition = new LatLng(destlat, destlng);
        } catch (NullPointerException e) {
            // TODO: handle exception
        } catch (NumberFormatException e) {
            // TODO: handle exception
        }

        buttonmethod();

    } else {
        // Internet connection is not present
        // Ask user to connect to Internet
        RelativeLayout rl_back = (RelativeLayout) findViewById(R.id.rl_back);
        if (rl_back == null) {
            Log.d("second", "second");
            RelativeLayout rl_dialoguser = (RelativeLayout) findViewById(R.id.rl_infodialog);

            try {
                layout12 = getLayoutInflater().inflate(R.layout.connectiondialog, rl_dialoguser, false);

            } catch (InflateException e) {
                // TODO: handle exception
            }

            rl_dialoguser.addView(layout12);
            rl_dialoguser.startAnimation(AnimationUtils.loadAnimation(Gmap.this, R.anim.popup));
            Button btn_yes = (Button) layout12.findViewById(R.id.btn_yes);
            btn_yes.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    finish();
                }
            });
        }
        // showAlertDialog(getApplicationContext(),
        // "No Internet Connection",
        // "You don't have internet connection.", false);

    }
}

private void getintent() {
    // TODO Auto-generated method stub

    try {
        Intent iv = getIntent();
        lat = iv.getStringExtra("lat");
        lng = iv.getStringExtra("lng");
        map = iv.getStringExtra("map");
        nm = iv.getStringExtra("nm");
        ad = iv.getStringExtra("ad");
        id = iv.getStringExtra("id");
        rate = iv.getStringExtra("rate");
        latitude = iv.getStringExtra("latitude");
        longitude = iv.getStringExtra("longitude");

        Log.d("lat", "" + lat);
        Log.d("lng", "" + lng);
        Log.d("lat1", "" + latitude);
        Log.d("lng1", "" + longitude);
    } catch (NullPointerException e) {
        // TODO: handle exception
    }


    MapsInitializer.initialize(getApplicationContext());
    btn_map = (Button) findViewById(R.id.btn_map);
    btn_map.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub



            Gmap.this.finish();

        }
    });

}

private void initialize() {
    // TODO Auto-generated method stub
    // rest1 = Home.rest;

    rest1 = new ArrayList<Storegetset>();

    btn_detail = (Button) findViewById(R.id.btn_detail);
    btn_detail.setVisibility(View.INVISIBLE);
}

// class call for latitude longitude and id of particular restaurant
public class getstoredetail extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {
        getdetailforNearMe();
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        setCustomMarkerOnePosition();

    }

}

private void getdetailforNearMe() {
    // TODO Auto-generated method stub

    URL hp = null;
    try {
        rest1.clear();

        hp = new URL(getString(R.string.link) + "rest/nearbystore.php?lat=" + latitudecur + "&&long=" + longitudecur
                + "&from=0&to=10");
        Log.d("URL", "" + hp);
        URLConnection hpCon = hp.openConnection();
        hpCon.connect();

        InputStream input = hpCon.getInputStream();
        Log.d("input", "" + input);

        BufferedReader r = new BufferedReader(new InputStreamReader(input));

        String x = "";
        x = r.readLine();
        String total = "";

        while (x != null) {
            total += x;
            x = r.readLine();
        }
        Log.d("URL", "" + total);
        JSONObject jObject = new JSONObject(total);
        Log.d("URL1", "" + jObject);
        JSONArray j = jObject.getJSONArray("Stores");
        // JSONArray j = new JSONArray(total);

        Log.d("URL1", "" + j);
        for (int i = 0; i < j.length(); i++) {

            JSONObject Obj;
            Obj = j.getJSONObject(i);

            Storegetset temp = new Storegetset();


            temp.setStore_id(Obj.getString("store_id"));
            temp.setName(Obj.getString("name"));
            temp.setAddress(Obj.getString("address"));
            temp.setDistance(Obj.getString("distance"));
            temp.setLat(Obj.getString("latitude"));
            temp.setLongi(Obj.getString("longitude"));
            temp.setFeatured(Obj.getString("featured"));
            temp.setRatting(Obj.getString("ratting"));
            temp.setThumbnail(Obj.getString("thumbnail"));


            String lat12 = Obj.getString("latitude");
            String lng12 = Obj.getString("longitude");
            Log.d("name90", "" + lat12);
            Log.d("name90", "" + lng12);

            rest1.add(temp);

        }


    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Error = e.getMessage();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Error = e.getMessage();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Error = e.getMessage();
    } catch (NullPointerException e) {
        // TODO: handle exception
        Error = e.getMessage();
    }
}

private void initilizeMap() {

    googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
    sharedPreferences = getSharedPreferences("location", 0);

    try {
        // Getting number of locations already stored
        locationCount = sharedPreferences.getInt("locationCount", 0);
    } catch (NumberFormatException e) {
        // TODO: handle exception
    }

    // check if map is created successfully or not
    if (googleMap == null) {
        Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
    }

    (findViewById(R.id.mapFragment)).getViewTreeObserver()
            .addOnGlobalLayoutListener(new android.view.ViewTreeObserver.OnGlobalLayoutListener() {

                @Override
                public void onGlobalLayout() {
                    // gets called after layout has been done but
                    // before
                    // display
                    // so we can get the height then hide the view
                    if (android.os.Build.VERSION.SDK_INT >= 16) {
                        (findViewById(R.id.mapFragment)).getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    } else {
                        (findViewById(R.id.mapFragment)).getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }

                }
            });
}

// set position in google map from latitude and longitude
public void setCustomMarkerOnePosition() {

    if (map.equals("yes")) {

        for (int i = 0; i < rest1.size(); i++) {

            try {
                String lat1 = rest1.get(i).getLat();
                String lng1 = rest1.get(i).getLongi();
                name = rest1.get(i).getName() + ":" + rest1.get(i).getStore_id() + ":" + rest1.get(i).getRatting();
                address = rest1.get(i).getAddress();
                idf = rest1.get(i).getStore_id();
                ratting = rest1.get(i).getRatting();
                Log.d("lat1", "" + lat1);
                Log.d("lng1", "" + lng1);
                customMarkerOne = new CustomMarker("markerOne", Double.parseDouble(lat1), Double.parseDouble(lng1));

                // addMarker(customMarkerOne);
                markerOptions = new MarkerOptions().position(

                new LatLng(customMarkerOne.getCustomMarkerLatitude(), customMarkerOne.getCustomMarkerLongitude()))
                        .icon(BitmapDescriptorFactory.defaultMarker())
                        .snippet(rest1.get(i).getName() + "n" + rest1.get(i).getAddress())
                        .title(rest1.get(i).getName() + ":" + rest1.get(i).getStore_id() + ":"
                                + rest1.get(i).getRatting() + ":" + rest1.get(i).getAddress() + ":"
                                + rest1.get(i).getLat() + ":" + rest1.get(i).getLongi());

                final Marker newMark = googleMap.addMarker(markerOptions);


                addMarkerToHashMap(customMarkerOne, newMark);
                zoomToMarkers(btn_detail);
            } catch (NullPointerException e) {
                // TODO: handle exception
            } catch (NumberFormatException e) {
                // TODO: handle exception
            }

            googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

                @Override
                public View getInfoWindow(Marker arg0) {
                    return null;
                }

                @Override
                public View getInfoContents(Marker marker) {

                    LinearLayout info = new LinearLayout(Gmap.this);
                    info.setOrientation(LinearLayout.VERTICAL);

                    try {
                        TextView snippet = new TextView(Gmap.this);
                        snippet.setTextColor(Color.BLACK);
                        snippet.setText(marker.getSnippet());
                        snippet.setTypeface(null, Typeface.BOLD);
                        snippet.setGravity(Gravity.CENTER);

                        // info.addView(title);
                        info.addView(snippet);
                    } catch (NullPointerException e) {
                        // TODO: handle exception
                    }



                    return info;
                }
            });

            // on click of google map marker
            googleMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {

                    try {
                        String title = marker.getTitle();
                        separateddata = title.split(":");
                        Log.d("1", "" + separateddata[0]);
                        Log.d("2", "" + separateddata[1]);
                        Log.d("3", "" + separateddata[2]);
                        String addressmap = separateddata[3].toLowerCase();
                        destlat = Double.parseDouble(separateddata[4]);
                        destlng = Double.parseDouble(separateddata[5]);
                        Intent intent = new Intent(Gmap.this, Detailpage.class);
                        intent.putExtra("id", "" + separateddata[1]);
                        intent.putExtra("name", "" + separateddata[0]);
                        intent.putExtra("rating", "" + separateddata[2]);
                        startActivity(intent);
                    } catch (NullPointerException e) {
                        // TODO: handle exception
                    } catch (NumberFormatException e) {
                        // TODO: handle exception
                    }

                }
            });
            googleMap.setOnMarkerClickListener(new OnMarkerClickListener() {

                @Override
                public boolean onMarkerClick(Marker arg0) {
                    // TODO Auto-generated method stub

                    try {
                        String title = arg0.getTitle();
                        separateddata = title.split(":");
                        destlat = Double.parseDouble(separateddata[4]);
                        destlng = Double.parseDouble(separateddata[5]);
                        arg0.showInfoWindow();
                    } catch (NullPointerException e) {
                        // TODO: handle exception
                    } catch (NumberFormatException e) {
                        // TODO: handle exception
                    }

                    return true;
                }
            });


            // on click of particular restaurant full detail
            btn_detail.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    Intent intent = new Intent(Gmap.this, Detailpage.class);
                    intent.putExtra("id", "" + separateddata[1]);
                    intent.putExtra("name", "" + separateddata[0]);
                    intent.putExtra("rating", "" + separateddata[2]);
                    startActivity(intent);
                }
            });
        }

    } else {
        customMarkerOne = new CustomMarker("markerOne", Double.parseDouble(lat), Double.parseDouble(lng));

        addMarker(customMarkerOne);

    }
}

public void showDirections(View view) {
    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(
            "http://maps.google.com/maps?" + "saddr=" + latitude + "," + longitude + "&daddr=" + lat + "," + lng));
    intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
    startActivity(intent);
}



public void zoomToMarkers(View v) {
    zoomAnimateLevelToFitMarkers(120);
}



public void initializeUiSettings() {
    googleMap.getUiSettings().setCompassEnabled(true);
    googleMap.getUiSettings().setRotateGesturesEnabled(false);
    googleMap.getUiSettings().setTiltGesturesEnabled(true);
    googleMap.getUiSettings().setZoomControlsEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
}

public void initializeMapLocationSettings() {
    googleMap.setMyLocationEnabled(true);
}

public void initializeMapTraffic() {
    googleMap.setTrafficEnabled(true);
}

public void initializeMapType() {
    googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}

public void initializeMapViewSettings() {
    googleMap.setIndoorEnabled(true);
    googleMap.setBuildingsEnabled(false);
}

// this is method to help us set up a Marker that stores the Markers we want
// to plot on the map
public void setUpMarkersHashMap() {
    if (markersHashMap == null) {
        markersHashMap = new HashMap<CustomMarker, Marker>();
    }
}

// this is method to help us add a Marker into the hashmap that stores the
// Markers
public void addMarkerToHashMap(CustomMarker customMarker, Marker marker) {
    setUpMarkersHashMap();
    markersHashMap.put(customMarker, marker);
}

// this is method to help us find a Marker that is stored into the hashmap
public Marker findMarker(CustomMarker customMarker) {
    iter = markersHashMap.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry mEntry = iter.next();
        CustomMarker key = (CustomMarker) mEntry.getKey();
        if (customMarker.getCustomMarkerId().equals(key.getCustomMarkerId())) {
            Marker value = (Marker) mEntry.getValue();
            return value;
        }
    }
    return null;
}

// this is method to help us add a Marker to the map
public void addMarker(CustomMarker customMarker) {

    for (int i = 0; i < rest1.size(); i++) {
        Storegetset tempobj = rest1.get(i);
        Log.d("tempobj", "" + tempobj);
        MarkerOptions markerOption = new MarkerOptions().position(

        new LatLng(customMarker.getCustomMarkerLatitude(), customMarker.getCustomMarkerLongitude()))
                .icon(BitmapDescriptorFactory.defaultMarker()).title(tempobj.getName());

        Marker newMark = googleMap.addMarker(markerOption);

        addMarkerToHashMap(customMarker, newMark);
    }

}

// this is method to help us remove a Marker
public void removeMarker(CustomMarker customMarker) {
    if (markersHashMap != null) {
        if (findMarker(customMarker) != null) {
            findMarker(customMarker).remove();
            markersHashMap.remove(customMarker);
        }
    }
}

// this is method to help us fit the Markers into specific bounds for camera
// position
public void zoomAnimateLevelToFitMarkers(int padding) {
    iter = markersHashMap.entrySet().iterator();
    LatLngBounds.Builder b = new LatLngBounds.Builder();

    LatLng ll = null;
    while (iter.hasNext()) {
        Map.Entry mEntry = iter.next();
        CustomMarker key = (CustomMarker) mEntry.getKey();
        ll = new LatLng(key.getCustomMarkerLatitude(), key.getCustomMarkerLongitude());
        b.include(ll);
    }
    LatLngBounds bounds = b.build();
    Log.d("bounds", "" + bounds);

    // Change the padding as per needed
    cu = CameraUpdateFactory.newLatLngBounds(bounds, 200, 400, 12);

    googleMap.animateCamera(cu);
    googleMap.moveCamera(cu);

}

// this is method to help us move a Marker.
public void moveMarker(CustomMarker customMarker, LatLng latlng) {
    if (findMarker(customMarker) != null) {
        findMarker(customMarker).setPosition(latlng);
        customMarker.setCustomMarkerLatitude(latlng.latitude);
        customMarker.setCustomMarkerLongitude(latlng.longitude);
    }
}

// this is method to animate the Marker. There are flavours for all Android
// versions
public void animateMarker(CustomMarker customMarker, LatLng latlng) {
    if (findMarker(customMarker) != null) {

        LatLngInterpolator latlonInter = new LinearFixed();
        latlonInter.interpolate(20,
                new LatLng(customMarker.getCustomMarkerLatitude(), customMarker.getCustomMarkerLongitude()),
                latlng);

        customMarker.setCustomMarkerLatitude(latlng.latitude);
        customMarker.setCustomMarkerLongitude(latlng.longitude);

        if (android.os.Build.VERSION.SDK_INT >= 14) {
            MarkerAnimation.animateMarkerToICS(findMarker(customMarker),
                    new LatLng(customMarker.getCustomMarkerLatitude(), customMarker.getCustomMarkerLongitude()),
                    latlonInter);
        } else if (android.os.Build.VERSION.SDK_INT >= 11) {
            MarkerAnimation.animateMarkerToHC(findMarker(customMarker),
                    new LatLng(customMarker.getCustomMarkerLatitude(), customMarker.getCustomMarkerLongitude()),
                    latlonInter);
        } else {
            MarkerAnimation.animateMarkerToGB(findMarker(customMarker),
                    new LatLng(customMarker.getCustomMarkerLatitude(), customMarker.getCustomMarkerLongitude()),
                    latlonInter);
        }
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();

}

private void buttonmethod() {
    // TODO Auto-generated method stub

    btn_arrow = (Button) findViewById(R.id.btn_arrow);
    btn_arrow.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            try {
                key = "route";
                Log.d("destlat", "" + destlat);
                Log.d("destlng", "" + destlng);
                fromPosition = new LatLng(latitudecur, longitudecur);
                // fromPosition = new LatLng(39.70, -85.73);
                toPosition = new LatLng(destlat, destlng);

                Log.d("frompos", "" + fromPosition);
                Log.d("topos", "" + toPosition);
            } catch (NullPointerException e) {
                // TODO: handle exception
            } catch (NumberFormatException e) {
                // TODO: handle exception
            }

            if (String.valueOf(destlat).equals("0.0")) {
                Toast.makeText(Gmap.this, "select your destination point marker to find your route",
                        Toast.LENGTH_LONG).show();
            } else {

                GetRouteTask getRoute = new GetRouteTask();

                // draw a route between current location and particular
                // destination
                getRoute.execute();
            }

        }
    });

    btn_current = (Button) findViewById(R.id.btn_current);
    btn_current.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            LatLng latLng = new LatLng(latitudecur, longitudecur);
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
        }
    });

    btn_circle = (Button) findViewById(R.id.btn_circle);
    btn_circle.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            key = "remove";
            GetRouteTask getRoute = new GetRouteTask();

            // draw a route between current location and particular
            // destination
            getRoute.execute();

        }
    });

    btn_zoom = (Button) findViewById(R.id.btn_zoom);
    btn_zoom.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            new getstoredetail().execute();
        }
    });

    btn_arrow.setVisibility(View.INVISIBLE);
    btn_circle.setVisibility(View.INVISIBLE);
    btn_current.setVisibility(View.INVISIBLE);
    btn_zoom.setVisibility(View.INVISIBLE);
    btn_anim = (Button) findViewById(R.id.btn_anim);

    btn_anim.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            if (anim) {

                Animation shake = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_down);
                Animation shake1 = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_down1);
                Animation shake2 = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_sown2);
                Animation shake3 = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_down3);

                btn_zoom.setVisibility(View.VISIBLE);
                btn_zoom.startAnimation(shake);
                btn_arrow.setVisibility(View.VISIBLE);
                btn_arrow.startAnimation(shake1);
                btn_current.setVisibility(View.VISIBLE);
                btn_current.startAnimation(shake2);
                btn_circle.setVisibility(View.VISIBLE);
                btn_circle.startAnimation(shake3);

                anim = false;
            } else {

                Animation shake = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_up);
                Animation shake1 = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_up1);
                Animation shake2 = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_up2);
                Animation shake3 = AnimationUtils.loadAnimation(Gmap.this, R.anim.slide_up3);

                btn_arrow.startAnimation(shake1);
                btn_circle.startAnimation(shake3);
                btn_current.startAnimation(shake2);
                btn_zoom.startAnimation(shake);
                btn_arrow.setVisibility(View.INVISIBLE);
                btn_circle.setVisibility(View.INVISIBLE);
                btn_current.setVisibility(View.INVISIBLE);
                btn_zoom.setVisibility(View.INVISIBLE);
                anim = true;
            }

        }
    });
}

private class GetRouteTask extends AsyncTask<String, Void, String> {

    private ProgressDialog Dialog;
    String response = "";

    @Override
    protected void onPreExecute() {
        Dialog = new ProgressDialog(Gmap.this);
        Dialog.setMessage("Loading");
        Dialog.show();
    }

    @Override
    protected String doInBackground(String... urls) {
        // Get All Route values
        document = v2GetRouteDirection.getDocument(fromPosition, toPosition,
                com.shopved.nearby.utils.v2GetRouteDirection.MODE_DRIVING);
        response = "Success";
        return response;

    }

    @Override
    protected void onPostExecute(String result) {
        googleMap.clear();
        if (response.equalsIgnoreCase("Success")) {
            ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
            PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.RED);

            for (int i = 0; i < directionPoint.size(); i++) {
                rectLine.add(directionPoint.get(i));
            }
            // Adding route on the map
            if (key.equals("route")) {
                googleMap.addPolyline(rectLine);

                // mGoogleMap.addPolyline(rectLine);
                Log.d("destlatitude", "" + destlat);
                Log.d("destlatitude", "" + destlng);
                markerOptions.position(toPosition);
                markerOptions.draggable(true);
                // changes
                customMarkersrc = new CustomMarker("markerOne", latitudecur, longitudecur);
                customMarkerdest = new CustomMarker("markerOne", destlat, destlng);
                newMark = googleMap.addMarker(markerOptions);
                // mGoogleMap.addMarker(markerOptions);

                addMarkerToHashMap(customMarkersrc, newMark);
                addMarkerToHashMap(customMarkerdest, newMark);
                zoomToMarkers1(btn_detail);
            } else if (key.equals("remove")) {
                markerOptions.position(toPosition);
                markerOptions.draggable(true);
                // changes
                customMarkersrc = new CustomMarker("markerOne", latitudecur, longitudecur);
                customMarkerdest = new CustomMarker("markerOne", destlat, destlng);
                newMark = googleMap.addMarker(markerOptions);
                // mGoogleMap.addMarker(markerOptions);

                addMarkerToHashMap(customMarkersrc, newMark);
                addMarkerToHashMap(customMarkerdest, newMark);
                zoomToMarkers1(btn_detail);
            }

        }

        Dialog.dismiss();
    }
}

public void zoomToMarkers1(View v) {
    zoomAnimateLevelToFitMarkers1(120);
}

public void zoomAnimateLevelToFitMarkers1(int padding) {
    iter = markersHashMap.entrySet().iterator();
    LatLngBounds.Builder b = new LatLngBounds.Builder();

    LatLng ll = null;
    while (iter.hasNext()) {
        Map.Entry mEntry = iter.next();
        CustomMarker key = (CustomMarker) mEntry.getKey();

        ll = new LatLng(key.getCustomMarkerLatitude(), key.getCustomMarkerLongitude());
        b.include(ll);
    }
    try {
        LatLngBounds bounds = b.build();
        Log.d("boundsroute", "" + bounds);

        // Change the padding as per needed
        cu = CameraUpdateFactory.newLatLngBounds(bounds, 25);
        googleMap.animateCamera(cu);


    } catch (IllegalStateException e) {
        // TODO: handle exception
        e.printStackTrace();
    }

}

}

Aucun commentaire:

Enregistrer un commentaire