Save the LatLng values of Marker into your database - java

I'm new to coding and I'm currently stuck with how to save my map markers to my SQLite database. I have an existing database for my users and passwords. I'll attach my maps activity and database helper and my edit activity which creates the markers. Any help will be appreciated.
public class MapActivity2 extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private static final int EDIT_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map2);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
this.mMap = map;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(final LatLng latLng) {
Intent edit = new Intent(MapActivity2.this, EditActivity.class);
edit.putExtra("location", latLng);
MapActivity2.this.startActivityForResult(edit, EDIT_REQUEST);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (EDIT_REQUEST) : {
if (resultCode == Activity.RESULT_OK) {
MarkerOptions markerOptions = data.getParcelableExtra("marker");
mMap.addMarker(markerOptions);
}
break;
}
}
}}
This is the EditActivity which adds the marker to the map.
public class EditActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit);
final LatLng latlng = (LatLng) getIntent().getParcelableExtra("location");
final EditText title = (EditText) findViewById(R.id.title);
Button boton = (Button) findViewById(R.id.save);
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
MarkerOptions marker = new MarkerOptions().position(latlng);
if (title.getText() != null) {
marker.title(title.getText().toString());
}
Intent resultIntent = new Intent();
resultIntent.putExtra("marker", marker);
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
});
}

Related

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.clear()' on a null object reference

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(...);
...
}

Method call expected in fragment

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();

How to pass Latitude and Longitude from database to Google Maps Activity

I've set up a database which through a textview displays the latitude and longitude of a specific building. There is a "go" button underneath which loads up my mapsActivity. However, I can't seem to get the lat and long to be placed on the map.
Maps Activity
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker, map1, map2, map3, map4, map5, map6, map7;
ZoomControls zoom;
// public static String TAG1;
// public static String TAG2;
public static String TAG_LAT = "lat";
public static String TAG_LNG = "lng";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
ToggleButton b1 = (ToggleButton) findViewById(R.id.button3);
getSupportActionBar().setTitle("Queen's Building Search");
Intent intent = getIntent();
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
zoom = (ZoomControls) findViewById(R.id.zcZoom);
zoom.setOnZoomOutClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGoogleMap.animateCamera(CameraUpdateFactory.zoomOut());
}
});
zoom.setOnZoomInClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mGoogleMap.animateCamera(CameraUpdateFactory.zoomIn());
}
});
Bundle extras = getIntent().getExtras();
if(extras != null){
double value = extras.getDouble("Latitude");
double value1 = extras.getDouble("Longitude");
// TAG_LAT = extras.getString("Latitude");
// TAG_LNG = extras.getString("Longitude");
goToLocation(value, value1);
}
Go to location Method being called
public void goToLocation(double lat, double lng) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mGoogleMap.moveCamera(update);
// btnGo();
}
building activity
btnGoLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Double lat = selectedBuilding.getLatitude();
Double lng = selectedBuilding.getLongitude();
Bundle bundle = new Bundle();
// Intent intent = new Intent(BuildingActivity.this, MapsActivity.class);
//Bundle extras = getIntent().getExtras();
Intent intent = new Intent(BuildingActivity.this, MapsActivity.class);
bundle.putDouble(MapsActivity.TAG_LNG,lat);
bundle.putDouble(MapsActivity.TAG_LNG, lng);
// Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
// intent.putExtra("Latitude", +lat);
// intent.putExtra("Longitude", ""+lng);
// intent.putExtra("latitude", lat);
// intent.putExtra("longitude", lng);
intent.putExtras(bundle);
startActivity(intent);
// Double latt=extras.getDouble(lat);
//Double loNg=extras.getDouble(lng)
}
});
As you can see my code is pretty messy trying to get this to work. If anyone could teamview with me it'd be a lot easier to show what i'm trying to do. I feel like i'm close.
Did you try in your MapActivity:
intent.getDoubleExtra("Latitude", 0);
?
Edit: and by the way, it isn't a database... just intent between 2 activities. No persistence here.
Use this in BuildingActivity
Intent intent = new Intent(getApplicationContext(), MapsActivity.class);
intent.putExtra("Latitude", ""+lat);
intent.putExtra("Longitude", ""+lng);
In MapsActivity get this value in onCreate() callback using this way...
Intent intent = getIntent();
If your extra data is represented as strings, then you can use intent.getStringExtra(String name) method. In your case:
String lat = intent.getStringExtra("Latitude");
String lng = intent.getStringExtra("Longitude");
Now you have both lat and lng value in your MapsActivity.
Hope this will help you :)

Multiple startActivityForResult()

I need to call this function twice in my application pointing to two different activities. I have a unique request code for each call, however my app seems to crash everytime it launches the second activity.
Here is my code (only relevant parts):
MainActivity:
//Request Info vars
static final int GET_DETAILS = 1;
static final int EDIT_DETAILS = 2;
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng latLng) {
lat = latLng.latitude;
lon = latLng.longitude;
startActivityForResult(new Intent(MapsActivity.this,NewMarkerActivity.class), GET_DETAILS);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
current_marker = marker;
startActivityForResult(new Intent(MapsActivity.this,EditMarkerActivity.class), EDIT_DETAILS);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == GET_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
addMarker(lat, lon, marker_title, marker_snippet);
mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lon)));
}
} if (requestCode == EDIT_DETAILS) {
if (resultCode == RESULT_OK) {
String marker_title=data.getStringExtra("title");
String marker_snippet = data.getStringExtra("snippet");
current_marker.setTitle(marker_title);
current_marker.setSnippet(marker_snippet);
}
}
}
EditMarkerActivity:
public class EditMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
NewMarkerActivity:
public class NewMarkerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_marker_activity);
Button save_btn = (Button)findViewById(R.id.btn_save);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText editName = (EditText)findViewById(R.id.editName);
String marker_title = editName.getText().toString();
EditText editSnippet = (EditText)findViewById(R.id.editSnippet);
String marker_snippet = editSnippet.getText().toString();
Intent _result = new Intent();
_result.putExtra("title", marker_title);
_result.putExtra("snippet", marker_snippet);
setResult(Activity.RESULT_OK, _result);
finish();
}
});
}
}
Any obvious issues? Help or insight to this problem will be greatly appreciated :)
Here is my output from Logcat:
android.content.ActivityNotFoundException: Unable to find explicit activity class {com.geekybrackets.virtualtourguide/com.geekybrackets.virtualtourguide.EditMarkerActivity}; have you declared this activity in your AndroidManifest.xml?
Turns out the issue was that I hadn't defined the activity in the manifest file.
Dear old me, now i know to check my errors !
Thanks again guys, case closed.

Get longitude and latitude

Hey guys I'm building an app and I need to get my longitude and latitude for some features I manage to get it but I can't pass it's values to my OnViewCreated method in my fragment. You can see those 2 simple toast messages in OnviewCreated they return null each time
LocatorFragment
public class LocatorFragment extends Fragment implements OnMapReadyCallback , GoogleApiClient.ConnectionCallbacks {
private MapView mapView;
private GoogleMap map;
private GoogleApiClient mGoogleApiClient;
private Double Latitude;
private Double Longitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Intent intent = new Intent(getContext(), GPSTrackerActivity.class);
startActivityForResult(intent,1);
View v = inflater.inflate(R.layout.locator_fragment, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
Location mLastLocation;
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.getUiSettings().setMyLocationButtonEnabled(false);
if (ActivityCompat.checkSelfPermission(getContext(), M anifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), 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 v;
}
map.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this.getActivity());
// Updates the location and zoom of the MapView
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void onMapReady(GoogleMap googleMap) {
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Double longitude;
Double latitude;
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
Bundle extras = data.getExtras();
longitude = extras.getDouble("Longitude");
latitude = extras.getDouble("Latitude");
Latitude=latitude;
Longitude=longitude;
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Toast.makeText(getContext(),String.valueOf(Latitude),Toast.LENGTH_SHORT).show();
Toast.makeText(getContext(),String.valueOf(Longitude),Toast.LENGTH_SHORT).show();
};
This is my GPSTracker Activity
public class GPSTrackerActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public void onConnected(Bundle bundle) {
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Intent intent = new Intent();
intent.putExtra("Longitude", mLastLocation.getLongitude());
intent.putExtra("Latitude", mLastLocation.getLatitude());
setResult(1,intent);
finish();
}
} catch (SecurityException e) {
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
I manage to do it via following function
map = mapView.getMap();
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
Latitude= location.getLatitude();
Longitude= location.getLongitude();
Location locationzoom = map.getMyLocation();
LatLng mapCenter = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = CameraPosition.builder()
.target(mapCenter)
.zoom(13)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
2000, null);

Categories