I'm trying to get the address line from longitude and latitude in a text view but it never shows in the text view and the map is blank.
this is my code including the toolbar and navigation bottom and the permission:
public class Map extends AppCompatActivity {
SupportMapFragment supportMapFragment;
FusedLocationProviderClient client;
private Toolbar toolbar;
View view;
TextView textLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
client = LocationServices.getFusedLocationProviderClient(this);
textLocation = findViewById(R.id.location);
if(ActivityCompat.checkSelfPermission(Map.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
getLocation();
}else {
ActivityCompat.requestPermissions(Map.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},44);
}
view = this.getWindow().getDecorView();
view.setBackgroundResource(R.color.lightGray);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageView toolbar_icon = findViewById(R.id.toolbar_icon);
TextView toolbar_title = findViewById(R.id.toolbar_title);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setSelectedItemId(R.id.map);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.map:
return true;
case R.id.camera:
startActivity(new Intent(getApplicationContext()
,Camera.class));
overridePendingTransition(0, 0);
return true;
case R.id.home:
startActivity(new Intent(getApplicationContext()
,MainActivity.class));
overridePendingTransition(0, 0);
return true;
case R.id.friends:
startActivity(new Intent(getApplicationContext()
,Friends.class));
overridePendingTransition(0, 0);
}
return false;
}
});
}
get the location from google map and here where I'm trying to get the line address in the textView:
private void getLocation() {
Task<Location> task = client.getLastLocation() ;
task.addOnSuccessListener((new OnSuccessListener<Location>() {
#Override
public void onSuccess(final Location location) {
if(location != null){
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions op = new MarkerOptions().position(latLng).title("IM HERE");
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.addMarker(op);
try {
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
textLocation.setText(addresses.get(0).getAddressLine(0 ));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
}));
}
request for permission:
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case 44: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLocation();
}
}
}
}
latitude and longitude for my current location are shown right but still, the map is blank and the address line is not shown in the TextView.
Related
When I try to open the Navigation Home the App crashes
Navigation Home image
I have tried initializing the mMap but the app still crashes. Please help me out
My error >
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.clear()' on a null object reference
at com.example.gpshelper.Activity.home$2.onLocationResult(home.java:138)
Here's my Code
public class home extends AppCompatActivity implements OnMapReadyCallback, NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
Toolbar toolbar;
NavigationView navigationView;
ActionBarDrawerToggle actionBarDrawerToggle;
GoogleMap mMap;
LocationRequest locationRequest;
FusedLocationProviderClient fusedLocationProviderClient;
LatLng latLng;
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
TextView header_name, header_email;
DatabaseReference databaseReference;
String current_uid;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
drawerLayout = findViewById(R.id.drawerlayout);
toolbar = findViewById(R.id.home_toolbar);
setSupportActionBar(toolbar);
navigationView = findViewById(R.id.nev_view);
//navigationView.setNavigationItemSelectedListener(this);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
databaseReference = FirebaseDatabase.getInstance().getReference("users");
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
current_uid = firebaseUser.getUid();
callpermissionlistener();
update_location();
dynamicheaderlistener();
}
private void dynamicheaderlistener() {
View header = navigationView.getHeaderView(0);
header_name = header.findViewById(R.id.header_name_text);
header_email = header.findViewById(R.id.header_email_text);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String current_name = dataSnapshot.child(current_uid).child("firstname").getValue(String.class);
String current_email = dataSnapshot.child(current_uid).child("email").getValue(String.class);
String s1 = "Hi "+current_name;
header_name.setText(s1);
header_email.setText(current_email);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void update_location() {
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)== PermissionChecker.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)==PermissionChecker.PERMISSION_GRANTED)
{
fusedLocationProviderClient = new FusedLocationProviderClient(this);
locationRequest = new LocationRequest()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(3000) //update interval
.setFastestInterval(5000); //fastest interval
fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null)
{
mMap.clear();
final double lat = locationResult.getLastLocation().getLatitude();
final double log = locationResult.getLastLocation().getLongitude();
latLng = new LatLng(lat, log);
mMap.addMarker(new MarkerOptions().position(latLng).title("your current location"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15F));
//update latitude and longitude
Map <String, Object> update = new HashMap<>();
update.put("latitude", lat);
update.put("longitude", log);
databaseReference.child(current_uid).updateChildren(update).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Toast.makeText(home.this, "updated", Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(home.this,"location not found", Toast.LENGTH_SHORT).show();
}
}
},getMainLooper());
}
else
{
callpermissionlistener();
}
}
private void callpermissionlistener() {
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
.setRationaleDialogTitle("location permission")
.setSettingsDialogTitle("warrning");
Permissions.check(this, permissions, rationale, options, new PermissionHandler() {
#Override
public void onGranted() {
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
mapFragment.getMapAsync(home.this);
update_location();
}
#Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
callpermissionlistener();
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
backpressedwarrning();
}
//super.onBackPressed();
}
public void backpressedwarrning(){
builder = new AlertDialog.Builder(home.this);
builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Exit");
alert.show();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// LatLng sydney = new LatLng(-34, 151);
//mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
//.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.nev_home:
startActivity(new Intent(home.this, home.class));
finish();
break;
case R.id.nev_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new profilefagment()).commit();
/*getSupportActionBar().setTitle("profile");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);*/
break;
case R.id.nev_joiningc:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new joincirclefragment()).commit();
break;
case R.id.nev_invite:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new invitecodefragment()).commit();
break;
case R.id.nev_mycircle:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new mycirclefragment()).commit();
break;
case R.id.nev_logout:
firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null)
{
firebaseAuth.signOut();
finish();
startActivity(new Intent(home.this, login_screen.class));
}
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
It's because somehow before initializing mMap from the onMapReady(), it called mMap.clear();
To prevent the crash, make sure to null-check the mMap first and then access it.
For e.g.
if (mMap != null) {
...
mMap.clear();
mMap.addMarker(...);
mMap. moveCamera(...);
...
}
I'm new in android so please help me. I want to open fragment with map inside another fragment so I made a transaction in the first fragment:
View rootView = inflater.inflate(R.layout.fragment_location, container, false);
btn = rootView.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
MapsFragment gMaps = new MapsFragment();
assert getFragmentManager() != null;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.mainlayout, gMaps()); //HERE IS A PROBLEM
transaction.commit();
}
});
return rootView;
When gMaps() is called it shows an error Method call expected
Screenshot
Here is MapsFragment.java code
public class MapsFragment extends FragmentActivity implements OnMapReadyCallback, APIService.fetchResults {
private GoogleMap mMap;
private APIService apiService;
private IntentFilter connectivityIntentFilter;
private BottomSheetDialog bottomSheetDialog;
private View dialogView;
private Boolean isOpenOnly;
private Integer maxPrice;
private Integer radius;
private Place previousPlace;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (!NetworkChecker.getInstance().isNetworkAvailable(context)) {
Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_active_connection), Snackbar.LENGTH_SHORT).show();
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_maps);
apiService = new APIService(this);
connectivityIntentFilter = new IntentFilter(CONNECTIVITY_ACTION);
GooglePlayServiceChecker googlePlayServiceChecker = new GooglePlayServiceChecker();
if (!googlePlayServiceChecker.checkGooglePlayServices(this)) {
Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_google_play_services), Snackbar.LENGTH_SHORT).show();
finish();
}
final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
assert mapFragment != null;
mapFragment.getMapAsync(this);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS)
.build();
autocompleteFragment.setFilter(typeFilter);
autocompleteFragment.setHint(getString(R.string.default_city));
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
String s = (String) place.getName();
//Update place data.
previousPlace = place;
apiService.getPlaceSearch(s, getString(R.string.place_type), radius, maxPrice, isOpenOnly);
}
#Override
public void onError(Status status) {
}
});
bottomSheetDialog = new BottomSheetDialog(MapsFragment.this);
dialogView = getLayoutInflater().inflate(R.layout.bottom_sheet, null);
bottomSheetDialog.setContentView(dialogView);
FloatingActionButton floatingActionButton = findViewById(R.id.fab_filter);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogView.setVisibility(View.VISIBLE);
bottomSheetDialog.show();
}
});
final Switch swOpenOnly = dialogView.findViewById(R.id.openCloseSwitch);
final SeekBar skRadius = dialogView.findViewById(R.id.seekbar_radius);
final SeekBar skPrice = dialogView.findViewById(R.id.seekbar_price);
dialogView.findViewById(R.id.bt_submit_filter).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
radius = skRadius.getProgress();
maxPrice = skPrice.getProgress();
isOpenOnly = swOpenOnly.isChecked();
bottomSheetDialog.dismiss();
//Get places using filter.
if (previousPlace == null) {
apiService.getPlaceSearch(getString(R.string.default_city), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
} else {
apiService.getPlaceSearch(previousPlace.getName().toString(), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
}
}
});
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
public void parseResults(Result result) {
mMap.clear();
if (result != null && result.getStatus() != null && result.getStatus().equals("OK")) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Restaurant restaurant : result.getRestaurants()) {
Location pastLocation = restaurant.getGeometry().getLocation();
LatLng latLng = new LatLng(pastLocation.getLatitude(), pastLocation.getLongitude());
MarkerOptions markerOptions = new MarkerOptions()
.position(latLng)
.title(restaurant.getName())
.snippet(restaurant.getFormattedAddress());
Marker m = mMap.addMarker(markerOptions);
m.setTag(restaurant.getResID());
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
builder.include(m.getPosition());
}
try {
LatLngBounds latLngBounds = builder.build();
int padding = 10;
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(latLngBounds, padding);
mMap.animateCamera(cu);
} catch (IllegalStateException | ParseException | NullPointerException e) {
//Don't move
}
} else {
Snackbar.make(findViewById(R.id.main_map), getString(R.string.error_message), Snackbar.LENGTH_SHORT).show();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (!NetworkChecker.getInstance().isNetworkAvailable(this))
Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_active_connection), Snackbar.LENGTH_SHORT).show();
else
apiService.getPlaceSearch(getString(R.string.default_city), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
mMap.setOnInfoWindowClickListener(marker -> {
Intent i = new Intent(MapsFragment.this, DetailActivity.class);
i.putExtra(getString(R.string.intent_key_id_tag), marker.getTag().toString());
if (NetworkChecker.getInstance().isNetworkAvailable(MapsFragment.this))
startActivity(i);
});
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, connectivityIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
I don't know does it make sense but ok. How to solve this problem?
Screenshot 2
You might be using android.app.FragmentTransaction. Try using androidx.fragment.app.FragmentTransaction and getSupportFragmentManager().beginTransaction().
Like:
androidx.fragment.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
MapsFragment gMaps = new MapsFragment();
assert getFragmentManager() != null;
transaction.replace(R.id.mainlayout, gMaps).commit();
I started my first experience in coding a few days ago. Didn't find an answer for my question, so I hope someone could help me.
In my project, I have a MainActivity with a BottomNavigationView using Fragments. I added a map as one of the fragments and it works fine.
But I changed and add some methods in the MapsActivity, things like device location and ask for permission. But when I run the app it doesn't call these methods, so I think it is because the MapFragment needs to get the methods of the MapsActivity but I don't know how to solve the problem and didn't find an answer for my question.
My MapFragment
public class Map_Fragment extends Fragment implements OnMapReadyCallback {
SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_, container, false);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment == null) {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
mapFragment = SupportMapFragment.newInstance();
ft.replace(R.id.map, mapFragment).commit();
}
mapFragment.getMapAsync(this);
// Inflate the layout for this fragment
return v;
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
}
My MapActivity:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
private GoogleMap mMap;
private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
private static final float DEFAULT_ZOOM = 150f;
// vars
private Boolean mLocationPermissionGranted = false;
private FusedLocationProviderClient mFusedLocationProviderClient;
protected void createLocationRequest() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d(TAG, "onMapReady: Map is ready");
if (mLocationPermissionGranted) {
getDeviceLocation();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
Log.d(TAG, "onCreate: Map started");
getLocationPermission();
}
private void getDeviceLocation() {
Log.d(TAG, "getDeviceLocation : get the Devices current location");
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (mLocationPermissionGranted) {
Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
Log.d(TAG, "onComplete: found location");
Location currentlocation = (Location) task.getResult();
moveCamera(new LatLng(currentlocation.getLatitude(), currentlocation.getLongitude()), DEFAULT_ZOOM);
} else {
Log.d(TAG, "onComplete: current Location is null");
Toast.makeText(MapsActivity.this, "unable to find location", Toast.LENGTH_SHORT);
}
}
});
}
} catch (SecurityException e) {
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
}
}
private void moveCamera(LatLng latLng, float zoom) {
Log.d(TAG, "moveCamera: move the Camera to lat: " + latLng.latitude + ", lng" + latLng.longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
private void initMap() {
Log.d(TAG, "Init Map");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
});
}
private void getLocationPermission() {
Log.d(TAG, "getLocationPermission");
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(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = true;
initMap();
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
} else {
ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
}
}
public void onRequestPermissionResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grandResults) {
Log.d(TAG, " onRequestPermissionResult: called");
mLocationPermissionGranted = false;
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE: {
if (grandResults.length > 0) {
for (int i = 0; i < grandResults.length; i++) {
if (grandResults[i] == PackageManager.PERMISSION_GRANTED) {
mLocationPermissionGranted = false;
Log.d(TAG, "onRequestPermissionResult: failed");
return;
}
}
Log.d(TAG, "onRequestPermissionResult: Permission granted");
mLocationPermissionGranted = true;
//initialize our Map
initMap();
}
}
}
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
}
How I connect these two with each other that the MapFragment uses the methods of MapActivity?
If I understand your problems correctly, you want to run OnMapReadyCallback related methods from activity instead of the fragment. If this is a case, you should fix your fragment like this:
public class Map_Fragment extends Fragment {
SupportMapFragment mapFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map_,container, false);
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
if (mapFragment==null){
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
mapFragment=SupportMapFragment.newInstance();
ft.replace(R.id.map, mapFragment).commit();
}
Activity activity = getActivity();
if (activity != null && activity instanceof MainActivity) {
mapFragment.getMapAsync((MainActivity) activity);
}
// Inflate the layout for this fragment
return v;
}
}
I am having a problem with my application when trying to take my location in the onMapReady method.
I tried to take the latitude and longitude in different variables but it still comes to the onMapReady method as null.
In the Toast within the getLastLocation method it shows me my real location but when I use myLocation outside the resulting coordinates are 0.0 -0.0
public class MapFragment extends Fragment implements OnMapReadyCallback {
Location myLocation = null;
FusedLocationProviderClient fusedLocation;
private static final int Request_Code = 101;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void getLastLocation() {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
}
Task<Location> task = fusedLocation.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
myLocation = location;
Toast.makeText(getContext(), myLocation.getLatitude() + "" + myLocation.getLongitude(), Toast.LENGTH_SHORT).show(); // This correctly shows me my true location
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.map_fragment, container, false);
fusedLocation = LocationServices.getFusedLocationProviderClient(getActivity());
getLastLocation();
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync( this);
return v;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Request_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
break;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).title("Estas aquí");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
googleMap.addMarker(marker);
}
}
}
ERROR LOG:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mint, PID: 11019
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.example.mint.MapFragment.onMapReady(MapFragment.java:81)
at com.google.android.gms.maps.zzak.zza(Unknown Source:2)
at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source:12)
at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source:12)
at android.os.Binder.transact(Binder.java:667)
at ck.b(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):14)
at com.google.android.gms.maps.internal.bb.a(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):4)
at com.google.maps.api.android.lib6.impl.bi.run(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):2)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at ln.dispatchMessage(:com.google.android.gms.dynamite_mapsdynamite#19629065#19.6.29 (100400-0):5)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6672)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:860)
I/Process: Sending signal. PID: 11019 SIG: 9
Process 11019 terminated.
your code is throwing nullPointerException because myLocation is still null so try to use below code
public class MapFragment extends Fragment implements OnMapReadyCallback {
Location myLocation = null;
FusedLocationProviderClient fusedLocation;
private static final int Request_Code = 101;
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void getLastLocation() {
if(ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, Request_Code);
}
Task<Location> task = fusedLocation.getLastLocation();
task.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
myLocation = location;
//change was made here
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync( this);
Toast.makeText(getContext(), myLocation.getLatitude() + "" + myLocation.getLongitude(), Toast.LENGTH_SHORT).show(); // This correctly shows me my true location
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.map_fragment, container, false);
fusedLocation = LocationServices.getFusedLocationProviderClient(getActivity());
getLastLocation();
return v;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Request_Code:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
getLastLocation();
}
break;
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
LatLng latLng = new LatLng(myLocation.getLatitude(), myLocation.getLongitude());
MarkerOptions marker = new MarkerOptions().position(latLng).title("Estas aquí");
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
googleMap.addMarker(marker);
}
}
}
Hey guys I am creating an app which gets the current co-ordinates of the user and then show them on the map which is implemented on the activity.
But my problem is that the map is not movable. I have tried getUiSettings().setScrollGesturesEnabled(true); but its not working.
The Code is given below:
public class Page1 extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String em,n;
private DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
TextView tv1;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 2;
protected LocationManager locationManager;
Location location;
private ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
nvDrawer = (NavigationView) findViewById(R.id.nvView);
setupDrawerContent(nvDrawer);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu_option, menu);
tv1= (TextView) nvDrawer.findViewById(R.id.textView5);
Intent i=getIntent();
em=i.getStringExtra("k");
tv1.setText(em);
return true;
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
LatLng location = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(location).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
float zoomLevel = 16; //This goes up to 21
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, zoomLevel));
googleMap.getUiSettings().setScrollGesturesEnabled(true);
}
else {
showSettingsAlert("Network");
}
}
public Location getLocation(String provider) {
if (locationManager.isProviderEnabled(provider)) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
}
else {
if (locationManager != null) {
location = locationManager.getLastKnownLocation(provider);
return location;
}
}
}
return null;
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 ) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else if(grantResults[0]==PackageManager.PERMISSION_DENIED) {
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "Never Ask Again", Toast.LENGTH_SHORT).show();
}
}
return;
}
}
}
public void showSettingsAlert(String provider) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
Page1.this);
alertDialog.setTitle(provider + " Settings");
alertDialog.setMessage(provider + " is not enabled! Want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
Page1.this.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
private ActionBarDrawerToggle setupDrawerToggle() {
return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.m1:
onMapReady(mMap);
return true;
case R.id.m2:
Intent i=new Intent(this,AboutUs.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupDrawerContent(final NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
selectDrawerItem(menuItem);
View headerLayout = navigationView.getHeaderView(0);
return true;
}
});
}
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the fragment to show based on nav item clicked
switch(menuItem.getItemId()) {
case R.id.nav_first_fragment:
mFirst(menuItem);
mDrawer.closeDrawers();
break;
case R.id.nav_second_fragment:
/*Intent i = new Intent(Page1.this, ShowInfo.class);
i.putExtra("j", em);
startActivity(i);*/
Toast.makeText(this, "Location Updated", Toast.LENGTH_SHORT).show();
int a=0;
Intent i=getIntent();
a=i.getIntExtra("u",0);
Location nwLocation =getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
updateLocation(a,latitude,longitude);
}
else {
showSettingsAlert("Network");
}
break;
case R.id.sub1:
startActivity(new Intent(this, ShowInfo.class));
break;
case R.id.sub2:
startActivity(new Intent(this, LoginPage.class));
finish();
break;
default:
mFirst(menuItem);
mDrawer.closeDrawers();
}
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
public void updateLocation(int userid,double xCoordinate,double yCoordinate){
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("userId", userid);
jsonObject.put("deviceName", "Mi4i");
jsonObject.put("xCoordinate",xCoordinate);
jsonObject.put("yCoordinate",yCoordinate);
jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
final OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, String.valueOf(jsonObject));
final Request request = new Request.Builder()
.url("http://172.31.4.91:8090/rest/saveLocation")
.post(body)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} /*else {
}*/
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
}
The UI for this activity is :-
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.pb.larcenytest.Page1" >
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
android:background="#android:color/white"
app:menu="#menu/drawer_view" />
</android.support.v4.widget.DrawerLayout>
</fragment>
you are getting location from Network provider , this takes time
what about add location.LocationListener
public class Page1 extends AppCompatActivity implements OnMapReadyCallback,location.LocationListener {
#Override
public void onLocationChanged(Location location)
{
CameraPosition position = new CameraPosition.Builder()
.target(new LatLng(Location.getLatitude, Location.getLongitude))
.zoom(17).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position));
}
}