Issue with onRequestPermissionsResult() - java

I'm able to grant or deny permissions in my fragment but I'm trying to call a method when permission has been granted but it doesn't seem to get called.
public final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 1;
In onCreateView(): (This works)
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
retrieveGyms();
} else {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_COARSE_LOCATION);
}
retrieveGyms() is not called when permission is granted from dialog, but permission does get granted.
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_COARSE_LOCATION: {
if (permissions.length == 1 && permissions[0] == Manifest.permission.ACCESS_COARSE_LOCATION && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
retrieveGyms();
} else {
// Location permission denied.
}
}
}
}
Showing retrieveGyms() just to show what it does and what I'm expecting
public void retrieveGyms() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://gyminyapp.azurewebsites.net/api/Gym", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
gymsArray = response;
// HashMap<String, Object> returnedGyms = new HashMap<String, Object>();
for (int i = 0; i < gymsArray.length(); i++) {
try {
// TODO: check distance from current user location and remove if not within search radius
String latitude = gymsArray.getJSONObject(i).getString("latitude");
String longitude = gymsArray.getJSONObject(i).getString("longitude");
Double doubleLat = Double.parseDouble(latitude);
Double doubleLong = Double.parseDouble(longitude);
LatLng gymCoord = new LatLng(doubleLat, doubleLong);
String name = gymsArray.getJSONObject(i).getString("name");
Object gymAddress = gymsArray.getJSONObject(i).get("address");
JSONObject gymAddressJSONObj = (JSONObject)gymAddress;
String streetAddress = gymAddressJSONObj.getString("streetAddress");
String city = gymAddressJSONObj.getString("city");
String state = gymAddressJSONObj.getString("state");
int zipCode = gymAddressJSONObj.getInt("zipCode");
String zipCodeString = Integer.toString(zipCode);
String addressString = streetAddress + " " + city + ", " + state + " " + zipCodeString;
Marker marker = mMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker))
.flat(false)
.title(name)
.snippet(addressString)
.position(gymCoord));
// Add marker to markers array
markers.add(marker);
} catch (JSONException e) {
e.printStackTrace();
}
// Zoom map to fit all markers
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
int padding = 75;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.animateCamera(cameraUpdate);
}
}
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable e) {
}
});
}

Related

Weather App, how to get latitude and longitude from MapActivity

It's my first time using stackoverflow so sorry for my question. I have been learning java and swift for only 4-5 month, so I'm just a beginner.
I'm writing a simple app with google Map and some other features like Weather Activity.
Map Activity running perfectly, Weather Activity also, but only with static latitude and longitude:
asyncTask.execute("28.125696","-15.440090" );
How to implement get currentLocation.getLatitude(), currentLocation.getLongitude() from MainActivityWeather in asyncTask.execute(...); ?
Am I thinking right? Is it a good way to build a weather app with a current location data? Map Activity:
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onMapReady: map is ready");
mMap = googleMap;
if (mLocationPermissionsGranted) {
getDeviceLocation();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
init();
}
}
private static final String TAG = "MapActivity";
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COURSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 15f;
public static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(
new LatLng(-40, -168), new LatLng(71, 136)
);
//widgets
private AutoCompleteTextView mSearchText;
private ImageView mGps;
//vars
private Boolean mLocationPermissionsGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutoCompleteAdapter mPlaceAutoCompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private PlaceInfo mPlace;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mSearchText = (AutoCompleteTextView) findViewById(R.id.input_search);
mGps = (ImageView) findViewById(R.id.ic_gps);
getLocationPermission();
BottomNavigationView bottomNav = findViewById(R.id.bottom_nav);
BottomNavigationViewHelper.removeShiftMode(bottomNav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.nav_menu:
Intent intent0 = new Intent(MapActivity.this, MainActivity.class);
startActivity(intent0);
break;
case R.id.nav_note:
Intent intent1 = new Intent(MapActivity.this, MainListActivity.class);
startActivity(intent1);
break;
case R.id.nav_map:
break;
case R.id.nav_attraction:
Intent intent3 = new Intent(MapActivity.this, MainActivityGrid.class);
startActivity(intent3);
break;
}
return false;
}
});
}
private void init(){
Log.d(TAG, "init: initializing");
mGoogleApiClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.enableAutoManage(this, this)
.build();
mSearchText.setOnItemClickListener(mAutocompleteClickListener );
mPlaceAutoCompleteAdapter = new PlaceAutoCompleteAdapter(this, mGoogleApiClient, LAT_LNG_BOUNDS, null);
mSearchText.setAdapter(mPlaceAutoCompleteAdapter);
mSearchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if(actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| keyEvent.getAction() == KeyEvent.ACTION_DOWN
|| keyEvent.getAction() == KeyEvent.KEYCODE_ENTER){
//execute our method for searching
geoLocate();
}
return false;
}
});
mGps.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: clicked gps icon");
getDeviceLocation();
}
});
hideSoftKeyboard();
}
private void geoLocate(){
Log.d(TAG, "geoLocate: geolocating");
String searchString = mSearchText.getText().toString();
Geocoder geocoder = new Geocoder(MapActivity.this);
List<Address> list = new ArrayList<>();
try{
list = geocoder.getFromLocationName(searchString,1);
}catch (IOException e) {
Log.d(TAG, "geoLocate: IOException " +e.getMessage());
}
if(list.size() > 0 ){
Address address = list.get(0);
Log.d(TAG, "geoLocate: found a location "+ address.toString());
moveCamera(new LatLng(address.getLatitude(), address.getLongitude()), DEFAULT_ZOOM, address.getAddressLine(0));
}
}
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if(task.isSuccessful()&& task.getResult() != null){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()),
DEFAULT_ZOOM, "My location");
}else{
Log.d(TAG, "onComplete: current location is null");
Toast.makeText(MapActivity.this, "unable to get current location", Toast.LENGTH_SHORT).show();
}
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}
private void moveCamera(LatLng latLng, float zoom, String title){
Log.d(TAG, "moveCamera: moving the camera to: lat: " + latLng.latitude + ", lng: " + latLng.longitude );
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
if(!title.equals("My location")){
MarkerOptions options = new MarkerOptions().position(latLng).title(title);
mMap.addMarker(options);
}
hideSoftKeyboard();
}
private void initMap(){
Log.d(TAG, "initMap: initializing map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(MapActivity.this);
}
private void getLocationPermission(){
Log.d(TAG, "getLocationPermission: getting location permissions");
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),
COURSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = true;
initMap();
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}else{
ActivityCompat.requestPermissions(this,
permissions,
LOCATION_PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult: called.");
mLocationPermissionsGranted = false;
switch(requestCode){
case LOCATION_PERMISSION_REQUEST_CODE:{
if(grantResults.length > 0){
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
mLocationPermissionsGranted = false;
Log.d(TAG, "onRequestPermissionsResult: permission failed");
return;
}
}
Log.d(TAG, "onRequestPermissionsResult: permission granted");
mLocationPermissionsGranted = true;
//initialize our map
initMap();
}
}
}
}
private void hideSoftKeyboard(){
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
private AdapterView.OnItemClickListener mAutocompleteClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
hideSoftKeyboard();
final AutocompletePrediction item = mPlaceAutoCompleteAdapter.getItem(i);
final String placeId = item.getPlaceId();
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(#NonNull PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
Log.d(TAG, "onResult: Place query did not mplete successfully" + places.getStatus().toString());
places.release();
return;
}
final Place place = places.get(0);
try{
mPlace = new PlaceInfo();
mPlace.setName(place.getName().toString());
Log.d(TAG, "onResult: name: " + place.getName());
mPlace.setAddress(place.getAddress().toString());
Log.d(TAG, "onResult: address: " + place.getAddress());
mPlace.setAttributions(place.getAttributions().toString());
Log.d(TAG, "onResult: attributions: " + place.getAttributions());
mPlace.setId(place.getId());
Log.d(TAG, "onResult: id:" + place.getId());
mPlace.setLatlng(place.getLatLng());
Log.d(TAG, "onResult: latlng: " + place.getLatLng());
mPlace.setRating(place.getRating());
Log.d(TAG, "onResult: rating: " + place.getRating());
mPlace.setPhoneNumber(place.getPhoneNumber().toString());
Log.d(TAG, "onResult: phone number: " + place.getPhoneNumber());
mPlace.setWebsiteUri(place.getWebsiteUri());
Log.d(TAG, "onResult: website uri: " + place.getWebsiteUri());
Log.d(TAG, "onResult: place: " + mPlace.toString());
}catch (NullPointerException e){
Log.e(TAG, "onResult: NullPointerException: " + e.getMessage() );
}
moveCamera(new LatLng(place.getViewport().getCenter().latitude,
place.getViewport().getCenter().longitude), DEFAULT_ZOOM, mPlace.getName());
places.release();
}
};}
Wheather Activities:
public class MainActivityWeather extends AppCompatActivity {
private static final String TAG = "WeatherActivity";
TextView cityField, detailsField, currentTemperatureField, humidity_field, pressure_field, weatherIcon, updatedField;
Typeface weatherFont;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// getSupportActionBar().hide();
setContentView(R.layout.activity_main_weather);
weatherFont = Typeface.createFromAsset(getApplicationContext().getAssets(), "fonts/weathericons-regular-webfont.ttf");
cityField = (TextView)findViewById(R.id.city_field);
updatedField = (TextView)findViewById(R.id.updated_field);
detailsField = (TextView)findViewById(R.id.details_field);
currentTemperatureField = (TextView)findViewById(R.id.current_temperature_field);
humidity_field = (TextView)findViewById(R.id.humidity_field);
pressure_field = (TextView)findViewById(R.id.pressure_field);
weatherIcon = (TextView)findViewById(R.id.weather_icon);
weatherIcon.setTypeface(weatherFont);
Function.placeIdTask asyncTask =new Function.placeIdTask(new Function.AsyncResponse() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: "+weather_humidity);
pressure_field.setText("Pressure: "+weather_pressure);
weatherIcon.setText(Html.fromHtml(weather_iconText));
}
});
asyncTask.execute( ); // asyncTask.execute("Latitude", "Longitude")
}}
public class Function {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?lat=%s&lon=%s&units=metric";
private static final String OPEN_WEATHER_MAP_API = "fdbf72863aba44b6fc7ce9e3324a689f";
public static String setWeatherIcon(int actualId, long sunrise, long sunset){
int id = actualId / 100;
String icon = "";
if(actualId == 800){
long currentTime = new Date().getTime();
if(currentTime>=sunrise && currentTime<sunset) {
icon = "";
} else {
icon = "";
}
} else {
switch(id) {
case 2 : icon = "";
break;
case 3 : icon = "";
break;
case 7 : icon = "";
break;
case 8 : icon = "";
break;
case 6 : icon = "";
break;
case 5 : icon = "";
break;
}
}
return icon;
}
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6, String output7, String output8);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
public placeIdTask(AsyncResponse asyncResponse) {
delegate = asyncResponse;//Assigning call back interfacethrough constructor
}
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON(params[0], params[1]);
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
String iconText = setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn, iconText, ""+ (json.getJSONObject("sys").getLong("sunrise") * 1000));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
}
}
public static JSONObject getWeatherJSON(String lat, String lon){
try {
URL url = new URL(String.format(OPEN_WEATHER_MAP_URL, lat, lon));
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty("x-api-key", OPEN_WEATHER_MAP_API);
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuffer json = new StringBuffer(1024);
String tmp="";
while((tmp=reader.readLine())!=null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if(data.getInt("cod") != 200){
return null;
}
return data;
}catch(Exception e){
return null;
}
}}

My App is failing to log in with no possible explanation whatsoever

The app just would not move past the log in page and the error pointing me to an inbuilt documentation
04-14 22:10:48.482 4206-4206/com.onyebuchboss.bossweatherbitcoinapp E/StorageHelpers: No value for version
org.json.JSONException: No value for version
at org.json.JSONObject.get(JSONObject.java:389)
at org.json.JSONObject.getString(JSONObject.java:550)
at com.google.firebase.auth.internal.zzz.zzc(Unknown Source)
at com.google.firebase.auth.internal.zzz.zzbi(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.(Unknown Source)
at com.google.firebase.auth.internal.zzj.(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.zza(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.getInstance(Unknown Source)
at java.lang.reflect.Method.invoke(Native Method)
at com.google.firebase.FirebaseApp.zza(Unknown Source)
at com.google.firebase.FirebaseApp.zzc(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1748)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1723)
at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
at android.app.ActivityThread.installProvider(ActivityThread.java:5153)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:4748)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4688)
at android.app.ActivityThread.-wrap1(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
my code
public class WeatherActivity extends AppCompatActivity {
final int REQUEST_CODE = 123;
//the openweather url to be used
final String WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather";
//the API key
final String APP_ID = "c9e6cb73daaf09d1bf0d1502d964bf60";
//time between location update (5000 milliseconds or 5 seconds)
final long MIN_TIME = 5000;
//Distance between location in metres
final float MIN_DISTANCE = 1000;
final String TAG = "WeatherApp";
//For the app to detect the user's location,
//we set the LOCATION_PROVIDER
String LOCATION_PROVIDER = LocationManager.GPS_PROVIDER;
//declare the variables to be linked to the layout
TextView mTemperature;
TextView mCity;
ImageView mWeatherImage;
//declare the LocationListener and LocationManager
LocationManager mLocationManager;
LocationListener mLocationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weather_layout);
//Link the elements in the Layout here
mCity = (TextView) findViewById(R.id.locationFetching);
mTemperature = (TextView) findViewById(R.id.tempereatureView);
mWeatherImage = (ImageView) findViewById(R.id.weatherImage);
ImageButton ChangeCityButton = (ImageButton) findViewById(R.id.changeCityButton);
//The Intent method used below is mostly used for switching between Activities
ChangeCityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent changeCityIntent = new Intent(WeatherActivity.this, ChangeCityController.class);
// finish();
startActivity(changeCityIntent);
}
});
}
//the onResume method is one of android lifecycle method
//that starts/execute after the onCreate method
#Override
protected void onResume() {
super.onResume();
//retrieving the city name passed in the
//ChangecityController
//City was used in the PutExtra method in changeCity
Intent myIntent = getIntent();
String city =myIntent.getStringExtra("City");
//if the user does not enter a particular city
//retrieve user current city
if(city != null) {
getWeatherForNewLocation(city);
} else {
getWeatherForCurrentLocation();
}
}
//The method to retrieve any city entered by the user
private void getWeatherForNewLocation(String city) {
//the request params passes in the required parameters to retrieve data using the API
//The openWeatherMap API being used in this project, "q" and acity's name
//is to be assigned to iy
RequestParams params = new RequestParams();
params.put("q", city);
params.put("appid", APP_ID);
networkingCalls(params);
}
// get weather situation for current city -getWeatherForCurrentCityHere()
private void getWeatherForCurrentLocation() {
//create an instance of LocationManager
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//the Location listener does the checking of the location for update
mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "onLocationChanged: callback received");
//get the longitude and latitude of current locaion
//stored as a string
String Longitude = String.valueOf(location.getLongitude());
String Latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "onLocation Latitude is: " + Latitude);
Log.d(TAG, "onLocationChanged: longitude " + Longitude);
RequestParams params = new RequestParams();
params.put("lat", Latitude);
params.put("lon", Longitude);
params.put("appid", APP_ID);
networkingCalls(params);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled: callback");
}
};
//REQUEST A LOCATION UPDATE PASSING THE LOCATION PROVIDER TO BE USED, MIN TIME,
// MIN DISTANCE AND mLISTENER as the receiver
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.
//request permissions to use the user's device GPS
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
}
//the override method below gives the result of the
// permission request to use the user's GPS
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//check to see if the request code matches the Request Code we gave
//during the request
if(requestCode == REQUEST_CODE){
if(grantResults.length> 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "onRequestPermissionsResult(): Granted!");
getWeatherForCurrentLocation();
}else{
Log.d(TAG, "onRequestPermissionsResult: Permission Denied");
}
}
}
//create the networkingCalls method here
//this method, we implement an HttpRequest, using it to make a Get request
private void networkingCalls(RequestParams params){
AsyncHttpClient client = new AsyncHttpClient();
//the Json object handler is used to notify whether the Getrequest failed or was successful
//the json response hanler receive 2 messages - onSucess and onFailure
//both methods are declared below
client.get(WEATHER_URL, params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response){
Log.d(TAG, "onSuccess: " + response.toString());
// call the json from the WeatherDataModel
WeatherDataModel weatherData = WeatherDataModel.fromJson(response);
updateUI(weatherData);
}
#Override
public void onFailure(int statuscode, Header[] headers, Throwable e, JSONObject response){
Log.e(TAG, "onFailure: "+ e.toString());
Log.d(TAG, "Status code: " + statuscode);
Toast.makeText(WeatherActivity.this, "Request failed", Toast.LENGTH_SHORT).show();
}
});
}
private void updateUI(WeatherDataModel weather){
mTemperature.setText(weather.getTemperature());
mCity.setText(weather.getCity());
int resourceID = getResources().getIdentifier(weather.getIconname(), "drawable", getPackageCodePath());
mWeatherImage.setImageResource(resourceID);
}
//This code below frees up memory
//when mListener is not in use and it is automatically generated
#Override
protected void onPause() {
super.onPause();
if(mLocationManager != null) mLocationManager.removeUpdates(mLocationListener);
}
}
public class WeatherDataModel {
private String mTemperature;
private String mCity;
private String mIconname;
private int mCondition;
//create a weatherdatamodel fromJson:
public static WeatherDataModel fromJson(JSONObject jsonObject) {
WeatherDataModel weatherData = new WeatherDataModel();
//we surround the json parsing code with a try-catch statement
//to handle errors like nan and empty values
try {
//get json object called -id, that is nested oin an object "0", thats also nested in an array called weather
weatherData.mCondition = jsonObject.getJSONArray("weather").getJSONObject(0).getInt("id");
weatherData.mCity = jsonObject.getString("name");
weatherData.mIconname = updateWeatherIcon(weatherData.mCondition);
double temp = jsonObject.getJSONObject("main").getDouble("temp") - 273.15;
int rdValue = (int) Math.rint(temp);
weatherData.mTemperature= Integer.toString(rdValue);
return weatherData;
}catch (JSONException e){
e.printStackTrace();
return null;
}
}
private static String updateWeatherIcon(int condition) {
if (condition >= 0 && condition < 300) {
return "tstorm1";
} else if (condition >= 300 && condition < 500) {
return "light_rain";
} else if (condition >= 500 && condition < 600) {
return "shower3";
} else if (condition >= 600 && condition <= 700) {
return "snow4";
} else if (condition >= 701 && condition <= 771) {
return "fog";
} else if (condition >= 772 && condition < 800) {
return "tstorm3";
} else if (condition == 800) {
return "sunny";
} else if (condition >= 801 && condition <= 804) {
return "cloudy2";
} else if (condition >= 900 && condition <= 902) {
return "tstorm3";
} else if (condition == 903) {
return "snow5";
} else if (condition == 904) {
return "sunny";
} else if (condition >= 905 && condition <= 1000) {
return "tstorm3";
}
return "dunno";
}
//create a Get() for the variable created, so it can be retrieved in the weatherActivity
public String getTemperature() {
return mTemperature + "°";
}
public String getCity() {
return mCity;
}
public String getIconname() {
return mIconname;
}
}
Try checking if the JSON object exists first:
if (jsonObjectjsonObject.getJSONArray("weather").getJSONObject(0).has("id")) {
weatherData.mCity = jsonObject.getString("name");
weatherData.mIconname = updateWeatherIcon(weatherData.mCondition);
}
I'm seeing the same stacktrace with slightly different message after building with Firebase SDK 15.0.0 (released April 10):
org.json.JSONException: No value for userMetadata
For me, the exception is non-fatal and only occurs the first time the new build is run on a device. I think it can be ignored.
If you are seeing the error repeatedly, or it is causing problems, downgrade to Firebase 12.0.1.

Skipped 1492 frames! The application may be doing too much work on its main thread.How to show loader while skipping frames in app? [duplicate]

This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
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...
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.
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

how to implement "no route found " Mesaage when route is not available on Google Map

I am creating an app. I am getting error(My app is crashed) when i find Address out of country on Google map. The reason behind it direction Route.So I want to display a message when no route found "no route found".Using a following code-
public class MainActivity extends AppCompatActivity implements OnItemClickListener, OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener {
private ActionBarDrawerToggle actionBarDrawerToggle;
private DrawerLayout drawerLayout;
private ListView navList;
GoogleMap mMap;
SupportMapFragment mFragment;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
Marker CurrentMarker, NearbyPlace, FindMarker;
LocationRequest mLocationRequest;
AutoCompleteTextView autoCompView = null
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
findbtn = (Button) findViewById(R.id.findbtn);
autoCompView = (AutoCompleteTextView) findViewById(R.id.editplace);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(this, R.layout.list_item));
autoCompView.setOnItemClickListener(this);
setListnerOnWidget();
}
private void setListnerOnWidget() {
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = autoCompView.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
};
findbtn.setOnClickListener(listener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
buildGoogleApiClient();
mGoogleApiClient.connect();
}
private String getDirectionsUrl(LatLng origin, LatLng dest) {
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
String sensor = "sensor=false";
String parameters = str_origin + "&" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
protected synchronized void buildGoogleApiClient() {
Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
double mLatitude=address.getLatitude();
double mLongitude=address.getLongitude();
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=4000");
sb.append("&types=" + "liquor_store");
sb.append("&sensor=true");
sb.append("&key=AI*************************");
Log.d("Map", "<><>api: " + sb.toString());
//query places with find location
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
//for direction Route
LatLng origin = CurrentMarker.getPosition();
LatLng dest = FindMarker.getPosition();
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}
public StringBuilder sbMethod(Location location) {
//current location
double mLatitude = location.getLatitude();
double mLongitude =location.getLongitude();
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=4000");
sb.append("&types=" + "liquor_store");
sb.append("&sensor=true");
sb.append("&key=AIzaSyC47V7li_j9_M_HyYEW8D5Z2nyFYX7DkuI");
Log.d("Map", "<><>api: " + sb.toString());
return sb;
}
#Override
public void onConnected( Bundle bundle) {
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
//place marker at current position
//mGoogleMap.clear();
latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CurrentMarker = mMap.addMarker(markerOptions);
}
mLocationRequest = new LocationRequest();
//mLocationRequest.setInterval(5000); //5 seconds
// mLocationRequest.setFastestInterval(3000); //3 seconds
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//mLocationRequest.setSmallestDisplacement(0.1F); //1/10 meter
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed( ConnectionResult connectionResult) {
Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
if (CurrentMarker != null){
CurrentMarker.remove();
}
latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CurrentMarker = mMap.addMarker(markerOptions);
Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
StringBuilder sbValue = new StringBuilder(sbMethod(location));
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sbValue.toString());
if (mGoogleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
private class PlacesTask extends AsyncTask<String, Integer, String>
{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
Log.d("result", "<><> result: " + result);
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
private String downloadUrl(String strUrl) throws IOException
{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
Place_JSON placeJson = new Place_JSON();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJson.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
Log.d("Map", "list size: " + list.size());
// Clears all the existing markers;
if (!firstRun) {
mMap.clear();
}
firstRun = false;
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
Log.d("Map", "place: " + name);
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// Placing a marker on the touched position
NearbyPlace = mMap.addMarker(markerOptions);
}
}
}
public class Place_JSON {
//Receives a JSONObject and returns a list
public List<HashMap<String, String>> parse(JSONObject jObject) {
JSONArray jPlaces = null;
try {
//Retrieves all the elements in the 'places' array
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
//Invoking getPlaces with the array of json object
//where each json object represent a place
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> place = null;
//Taking each place, parses and adds to list object
for (int i = 0; i < placesCount; i++) {
try {
// Call getPlace with place JSON object to parse the place
place = getPlace((JSONObject) jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
// Parsing the Place JSON object
private HashMap<String, String> getPlace(JSONObject jPlace)
{
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity = "-NA-";
String latitude = "";
String longitude = "";
String reference = "";
try {
// Extracting Place name, if available
if (!jPlace.isNull("name")) {
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if (!jPlace.isNull("vicinity")) {
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
reference = jPlace.getString("reference");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
place.put("reference", reference);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
private class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParTask parTask = new ParTask();
// Invokes the thread for parsing the JSON data
parTask.execute(result);
}
}
//A class to parse the Google Places in JSON format
private class ParTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.GRAY);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: "+url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
//Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
DirectionsJSONParser
public class DirectionsJSONParser {
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
Please tell me how to implement message "No Route Found" when no route found Google map
Thanks

Android - Cant get latitude/longitude value to store and pass on variable

I am trying to store the latitude/longitude to variables x3 and x4 to pass on Spot[] array but it returns 0. I tried printing it on onConnected method and it works fine.
I also tried other methods to add marker on google map and I put map.addMarker on onConnected method instead but my app closes. If u can suggest where to put addMarker please do. Thanks.
GoogleMap map;
private static Location mLastLocation;
private static GoogleApiClient mGoogleApiClient;
static double x3;
static double x4;
LatLng userloc;
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
x3 = mLastLocation.getLatitude();
x4 = mLastLocation.getLongitude();
userloc = new LatLng(x3,x4);
txtPlateno.setText(String.valueOf(x3+" - "+x4)); // PRINT TEST ONLY WITH CORRECT RESULT
}
}
private static Spot[] SPOTS_ARRAY = new Spot[]{
new Spot("YOU ARE HERE", "DESC ", "", new LatLng(x3, x4)), // NOT SHOWN IN MAP AT ALL
new Spot("Besabella Parking Lot",
"Address: Sta Cruz Labogon, Mandaue City\n " +
"Fee: \n " +
"No. of available space: \n " +
"Distance:" + x3 + "KM", "", new LatLng(10.351763, 123.953683)),
// TESTING x3 ON DISTANCE WITH RESULT 0.0
};
You can call add marker after getting lat/long and also can move camera on that for reference you can check following code
public class MapDialogFragment extends DialogFragment implements LibListner, OnClickListener, OnInfoWindowClickListener {
private View dialog;
private MarkerOptions markerOptions;
private SupportMapFragment mMapFragment;
private GoogleMap mMap;
private TextView tvBackText, tvback;
// private ArrayList<String> getClickedTitle;
private ArrayList<Data> newData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Utility.Log("onCreateView");
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// //
getDialog().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// getDialog().getWindow()
// .getAttributes().windowAnimations = R.style.DialogAnimation;
if (dialog != null) {
ViewGroup parent = (ViewGroup) dialog.getParent();
if (parent != null)
parent.removeView(dialog);
}
try {
dialog = inflater.inflate(R.layout.dlg_map, container, false);
} catch (Exception e) {
/* map is already there, just return view as it is */
}
return dialog;
}
#Override
public void onStart() {
super.onStart();
// Utility.Log("onStart");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Utility.Log("onCreate");
FragmentManager fm = getChildFragmentManager();
mMapFragment = (SupportMapFragment) fm.findFragmentById(R.id.mapView);
if (mMapFragment == null) {
mMapFragment = SupportMapFragment.newInstance();
fm.beginTransaction().replace(R.id.mapView, mMapFragment).commit();
}
}
#Override
public void onActivityCreated(Bundle arg0) {
super.onActivityCreated(arg0);
init();
loadMap();
initMap();
listner();
}
private void loadMap() {
String map = Utility.BASE_URL + "mall/location";
new GetLibResponse(MapDialogFragment.this, new LocationGeneralModel(), getActivity(), map, Utility.LOCATIONCOMMON, true, true);
}
#Override
public void onResume() {
super.onResume();
try {
int chkGooglePlayServices = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
markerOptions = new MarkerOptions();
if (chkGooglePlayServices != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(chkGooglePlayServices, getActivity(), 1122).show();
} else {
mMap = mMapFragment.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
mMap.setMyLocationEnabled(false);
mMap.setOnInfoWindowClickListener(this);
// if (isSearch) {
// mMap.setOnMapClickListener(MapDialogFragment.this);
// mMap.setOnMapLongClickListener(MapDialogFragment.this);
// mMap.setOnMarkerDragListener(MapDialogFragment.this);
//
// if (latitude != null && longitude != null && latitude != "" && longitude != "") {
// mMap.clear();
// markerOptions
// .position(
// new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)));
// mMap.addMarker(markerOptions);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)),
// 15.0f));
//
// }
// } else {
// mMap.clear();
// markerOptions
// .position(
// new LatLng(Double.parseDouble(flat), Double.parseDouble(flong)));
// mMap.addMarker(markerOptions);
// mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
// new LatLng(Double.parseDouble(flat), Double.parseDouble(flong)),
// 15.0f));
// }
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
tvback = (TextView) dialog.findViewById(R.id.frg_location_tvBack);
tvback.setOnClickListener(this);
tvBackText = (TextView) dialog.findViewById(R.id.frg_location_tvBackText);
tvBackText.setOnClickListener(this);
}
private void listner() {
}
private void initMap() {
}
private MainFragmentActivity mainActivity() {
return ((MainFragmentActivity) getActivity());
}
#Override
public void onResponseComplete(Object clsGson, int requestCode) {
if (requestCode == Utility.LOCATIONCOMMON) {
if (mainActivity() != null) {
mainActivity().mLocationGeneralModel = (LocationGeneralModel) clsGson;
if ((mainActivity().mLocationGeneralModel != null) && (mainActivity().mLocationGeneralModel.data != null)
&& (mainActivity().mLocationGeneralModel.data.size() != 0)) {
ArrayList<Double> vLat = new ArrayList<Double>();
ArrayList<Double> vLong = new ArrayList<Double>();
ArrayList<String> vName = new ArrayList<String>();
ArrayList<Data> newData = new ArrayList<LocationGeneralModel.Data>();
for (int pin = 0; pin < mainActivity().mLocationGeneralModel.data.size(); pin++) {
try {
if (!mainActivity().mLocationGeneralModel.data.get(pin).vLat.equals("")) {
// Log.d("TAG", mainActivity().mLocationGeneralModel.data.get(pin).vLat);
vLat.add(Double.parseDouble(mainActivity().mLocationGeneralModel.data.get(pin).vLat));
vLong.add(Double.parseDouble(mainActivity().mLocationGeneralModel.data.get(pin).vLong));
vName.add((mainActivity().mLocationGeneralModel.data.get(pin).vName_en));
double vLatitude[] = new double[vLat.size()];
double vLongitude[] = new double[vLong.size()];
for (int getArray = 0; getArray < vLat.size(); getArray++) {
vLatitude[getArray] = vLat.get(getArray);
vLongitude[getArray] = vLong.get(getArray);
newData.add(mainActivity().mLocationGeneralModel.data.get(pin));
}
multipleMarker(vLatitude, vLongitude, vName, newData);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
#Override
public void onResponseError(String errorMessage, int requestCode) {
}
private void multipleMarker(double latitude[], double longitude[], ArrayList<String> vName, ArrayList<Data> newData) {
this.newData = newData;
mMap.clear();
// LatLngBounds.Builder builder = new LatLngBounds.Builder();
// for (Marker marker : markers) {
// builder.include(marker.getPosition());
// }
// LatLngBounds bounds = builder.build();
// getClickedTitle = new ArrayList<String>();
for (int i = 0; i < latitude.length; i++) {
// Log.d("TAG", "Marker Add" + latitude[i] + " " + longitude[i]);
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude[i], longitude[i])).title(vName.get(i));
mMap.addMarker(marker);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude[i], longitude[i]), 5));
}
// getClickedTitle = vName;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.frg_location_tvBack:
dismiss();
break;
case R.id.frg_location_tvBackText:
dismiss();
break;
}
}
#Override
public void onInfoWindowClick(Marker arg0) {
for (int counter = 0; counter < newData.size(); counter++) {
if (arg0.getTitle().equals(newData.get(counter).vName_en)) {
Data data = newData.get(counter);
MallPerticularsFragment mFragment = new MallPerticularsFragment();
Bundle bundle = new Bundle();
bundle.putString("mall_name", data.vName_en);
bundle.putString("mall_locEn", data.vLocation);
mFragment.setArguments(bundle);
((MainFragmentActivity) getActivity()).displayFragmentWithArg(mFragment);
}
}
}
}

Categories

Resources