Here is the case that i would like to add a Google API into an action bar which goes to a fragment. But, it failed because the fragment class has to extends FragmentActivity while the action bar not allowed it, anyone could help to fix it? Thanks very much!
MainHome.java
package com.example.demo3;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class MainHome extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainhome);
initView();
}
private void initView() {
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
actionBar.addTab(actionBar
.newTab()
.setText("My Information")
.setTabListener(
new MyTabListener<FragmentPage1>(this,
FragmentPage1.class)));
actionBar.addTab(actionBar
.newTab()
.setText("My Location")
.setTabListener(
new MyTabListener<FragmentPage2>(this,
FragmentPage2.class)));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.prelog, menu);
return true;
}
}
Fragment2.java
package com.example.demo3;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class FragmentPage2 extends Fragment {
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
static final LatLng KIEL = new LatLng(53.551, 9.993);
private GoogleMap map;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.locationhome, null, false);
map = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Hamburg"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Kiel")
.snippet("Kiel is cool")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
return v;
}
}
It brings that I need to extend FragmentActivity to enable
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
. However, it will make
actionBar.addTab(actionBar
.newTab()
.setText("My Location")
.setTabListener(
new MyTabListener<FragmentPage2>(this,
FragmentPage2.class)));
failed. Anyone could have some suggestion?
Thanks very much!
use mapview instead of mapfragment like this
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and modify java file like this
public class MyMapFragment extends Fragment {
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_fragment, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
Related
I made a fragment to connect via Facebook, the code of which is here :
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class LoginFragment extends Fragment
{
private TextView mTextDetails;
private CallbackManager fbCallbackManager;
private AccessTokenTracker tTracker;
private ProfileTracker pTracker;
private FacebookCallback<LoginResult> fbCallback = new FacebookCallback<LoginResult>()
{
#Override
public void onSuccess(LoginResult loginResult)
{
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onCancel()
{
}
#Override
public void onError(FacebookException error)
{
}
};
public LoginFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
fbCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();
tTracker.startTracking();
pTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
setTextDetails(view);
setupFBLoginButton(view);
}
#Override
public void onResume()
{
super.onResume();
Profile profile = Profile.getCurrentProfile();
}
#Override
public void onStop()
{
super.onStop();
tTracker.stopTracking();
pTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
fbCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setupFBLoginButton(View view)
{
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(fbCallbackManager, fbCallback);
}
private void setTextDetails(View view)
{
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}
private void setupTokenTracker()
{
tTracker= new AccessTokenTracker()
{
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken)
{
//TODO
}
};
}
private void setupProfileTracker()
{
pTracker = new ProfileTracker()
{
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile)
{
//TODO
}
};
}
}
I am trying to "call" this fragment from my main activity using the following code :
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity
{
private boolean logged = false;
private LoginFragment loginFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
FragmentManager fManager = getFragmentManager();
FragmentTransaction fTransaction = fManager.beginTransaction();
LoginFragment loginFragment = new LoginFragment();
fTransaction.add(R.id.fragment_container, loginFragment, "fragment_container");
fTransaction.commit();
setContentView(R.layout.activity_main);
}
}
Yet, I have an error on the 2nd argument of this line fTransaction.add(R.id.fragment_container, loginFragment, "fragment_container");.
My IDE tells me it's expecting an android.app.Fragment object, and mine is a my.package.LoginFragment.
I don't get it, my LoginFragment extends Fragment...
I also tried to pass everything in android.support.v4.*, but then I can't do loginButton.setFragment(this);, and then I have no idea on how to set the Fragment to the loggin button.
Use getSupportFragmentManager() when working with support fragments instead of getFragmentManager().
Also, adding the fragment should happen after setContentView() so the fragment_container can be found.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginFragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, loginFragment, "fragment_container")
.commit();
}
After doing this you will have to fix a couple imports too. Make sure you use the following in MainActivity.
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
So I have searched the internet for lots of different solutions to get my android phone to show current location through the Google Maps API using play services. I believe I have the right set-up but something is just not right.
Please see below the .java and .xml code.
Java
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.location.LocationListener;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private UiSettings mUiSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment
= (SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
}
private void centerMapOnMyLocation() {
mMap.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
Location location = mMap.getMyLocation();
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
LatLng latlng;
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// public void requestPermissions(#NonNull String[] permissions, int requestCode)
// 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 Activity#requestPermissions for more details.
return;
}
Location myLocation = locationManager.getLastKnownLocation(provider);
if (location != null) {
//Create a LatLng object for the current location
latlng = new LatLng(latitude, longitude);
} else {
locationManager.requestLocationUpdates(provider, 20000, 0, (LocationListener) this);
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context="example.navigationapplication_10.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
Many thanks
Try using this class to get the Latitude and Longitude..
import android.app.AlertDialog.Builder;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private Context context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10;
private static final long MIN_TIME_BW_UPDATES=1000*60*1;
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.context=context;
getLocation();
}
public Location getLocation()
{
try{
locationManager=(LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
showSettingsAlert();
}
else{
this.canGetLocation=true;
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isGPSEnabled){
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS()
{
if(locationManager !=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location!=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location!=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingsAlert(){
Builder alertDialog=new Builder(context);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled.Do you want to go to the settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
And for marking your position in the map
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try {
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
LatLng sydney = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(sydney).title("I am here"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
for(int i=0;i<MainActivity.nameArray.length;i++)
{
latitude=Double.parseDouble(MainActivity.latArray[i]);
longitude=Double.parseDouble(MainActivity.lonArray[i]);
LatLng shops = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(shops).title(MainActivity.nameArray[i]));
}
} else {
gps.showSettingsAlert();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope this Helps
I have two fragments and one activity.
DataFragment passes info succesfuly to MainActivity and that's why there is no point providing you the code of it. My issue is , that bundle isn't effective on MyMapFragment which extends SupportMapFragment when I am trying to pass data from MainActivity. Of course I've searched a lot for many days but the only solutions given are for a fragment and not for SupportMapFragment which I think it's different.
MainActivity
package com.manuelpap.mapapp;
import android.app.Fragment;
import android.content.Intent;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.os.Handler;
import com.google.android.gms.maps.SupportMapFragment;
import com.parse.Parse;
public class MainActivity extends AppCompatActivity {
public String mapLocation="EMPTY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
Intent intent = getIntent();
if (getIntent().getExtras() != null) {
mapLocation = intent.getExtras().getString("mapLocation");
Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
MyMapFragment fragobj=new MyMapFragment();
fragobj.setArguments(bundle);
Log.d("MAPLOCATION", "----MainActivity---- " + mapLocation);
finish(); //I am using this because on DataFragment it's starting again , so I don't need multiple instances of MainActivity
}
}
public class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int i){
if(i==0){
return new DataFragment();
}
else {
return new MyMapFragment();
}
}
#Override
public int getCount(){
return 2; //posa scrolls dexia (pages) theloume
}
#Override
public CharSequence getPageTitle(int position) {
if(position==0){
return "DATA";
}
else {
return "MAP";
}
}
}
}
MyMapFragment
package com.manuelpap.mapapp;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.os.Handler;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MyMapFragment extends SupportMapFragment { //kanei extend thn hdh uparxousa class gia to maps ths google alla den mpoorume na thn doume giati einai kleidomenh
public String location="EMPTY";
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final Handler handler=new Handler();
handler.post(new Runnable() {
#Override
public void run() {
if (getArguments() == null)
location = "------NOTHING RECIEVED------";
else
location =getArguments().getString("message");
Log.d("MAPFRAGMENTLOCATION", location);
handler.postDelayed(this, 200); // set time here to refresh textView
}
});
GoogleMap googleMap = getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(new LatLng(40.416775, -3.70379));
googleMap.addMarker(markerOptions);
}
}
It looks like you are finishing your main activity
//I am using this because on DataFragment it's starting again , so I don't need multiple instances of MainActivity
Your DataFragment is in the viewpager so it is supposed to start along with your map fragment. You are not starting multiple instances of main activity that I can see here.
When you call finish() on your main activity that means that the map and pager and everything goes away. Not sure what exactly your looking for but I assume you are trying to pass the location string to the map so I have tailored my answer to fit that use case.
The problem is that you are using new MyMapFragment() without the bundle in the view pager. The other logic that you have in MainActivity pertaining to the Map fragment is not going anything to the one that is displayed with the view pager. Essentially you are just creating another instance of the map fragment that is not displayed anywhere. The view pager is the class that needs the data passed to it.
I thought this link might be helpful here to explain the newInstance Method.
Creating a Fragment: constructor vs newInstance()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (getIntent().getExtras() != null) {
mapLocation = intent.getExtras().getString("mapLocation");
}
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(), mapLocation));
}
public class MyAdapter extends FragmentPagerAdapter{
private String mMapLocation;
public MyAdapter(FragmentManager fm, String mapLocation) {
super(fm);
mMapLoaction = mapLocation;
}
#Override
public android.support.v4.app.Fragment getItem(int i){
if(i==0){
return new DataFragment();
}
else {
Bundle bndl = new Bundle();
if(!TextUtils.isEmpty(mapLocation))
bndl.putString("message", mapLocation);
return new MyMapFragment.newInstance(bndl);
}
}
public class MyMapFragment extends SupportMapFragment { //kanei extend thn hdh uparxousa class gia to maps ths google alla den mpoorume na thn doume giati einai kleidomenh
public String location="EMPTY";
public static MyMapFragment newInstance(Bundle bundle) {
MyMapFragment myMapFragment= new MyMapFragment ();
if (bundle != null) {
myMapFragment.setArguments(bundle);
}
return myMapFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(getArguments()!=null)
location =getArguments().getString("message");
}
I am trying to get current location in map fragment but the crashes with an error in line googleMap.setMyLocationEnabled(true);
I used Location and Latlang to detect current location.
mapFragment.java
public class mapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
Location location;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_map, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setMyLocationEnabled(true);
googleMap = mMapView.getMap();
// latitude and longitude
LatLng lat = new LatLng(location.getLatitude(), location.getLongitude());
/*double latitude = 17.385044;
double longitude = 78.486671;*/
// create marker
MarkerOptions marker = new MarkerOptions().position(
lat).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lat).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Looks like you have a few issues, but the crash is happening because you need to call getMap() before you call setMyLocationEnabled().
Change this:
googleMap.setMyLocationEnabled(true);
googleMap = mMapView.getMap();
...to this:
googleMap = mMapView.getMap();
googleMap.setMyLocationEnabled(true);
Updated: I was able to get this code working.
Getting the current location should be done with the Fused Location Provider API, but that is beyond the scope of this question.
The method in this sample code might work on older devices, but on 4.4.4 it's returning a null location due to getMyLocation() being depricated.
However, with the null check in place the map displays correctly, and you can click on the location button to have the map move to your current location.
MapView mMapView;
private GoogleMap googleMap;
Location location;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_main, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
googleMap.setMyLocationEnabled(true);
location = googleMap.getMyLocation();
if (location != null) {
// latitude and longitude
LatLng lat = new LatLng(location.getLatitude(), location.getLongitude());
//double latitude = 17.385044;
//double longitude = 78.486671;
//LatLng lat = new LatLng(latitude,longitude);
// create marker
MarkerOptions marker = new MarkerOptions().position(
lat).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(lat).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
// Perform any camera updates here
return v;
}
You can use the setOnMyLocationChangeListener method to get the current location. Download the source here(Show Google Map In Android)
MainActivity.Java
package deepshikha.googlemap;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity {
public GoogleMap googleMap;
private static final int REQUEST_PERMISSIONS = 100;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btn);
fn_permission();
fn_currentlocation ();
}
public void fn_currentlocation (){
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
try {
googleMap.setMyLocationEnabled(true);
} catch (Exception e) {
}
if (googleMap != null) {
googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location arg0) {
// TODO Auto-generated method stub
double current_latitude = arg0.getLatitude();
double currrent_longitude = arg0.getLongitude();
LatLng current_latLng = new LatLng(current_latitude, currrent_longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(current_latLng));
Log.e("CURRENT LONGITUDE", currrent_longitude + "");
Log.e("CURRENT LATITUDE", current_latitude + "");
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
googleMap.addMarker(new MarkerOptions().position(current_latLng).title("Marker"));
}
});
}
}
}
private void fn_permission(){
if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) ||
(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) &&
(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_PERMISSIONS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(MainActivity.this, "The app was not allowed to read or write to your storage. Hence, it cannot function properly. Please consider granting it this permission", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
I've been trying to get a Location Manager to work for a few hours now inside my Fragment.
I found a StackOverflow question about a similar problem, and tried to implement the solution.
The answer is located here: https://stackoverflow.com/a/18533440/3035598
So i almost literally copied everything the answer said, but it is not working for me.
When the map opens I get the error "Google Play Services Missing". This is caused by a NullPointerException as you can read in the answer.
I have no idea why it is not working, since I did everything he said.
Does anyone know what's going wrong?
If I have to provide my code, let me know and I will do that, but it is almost the same as in the link I provided.
EDIT:
The Code I use:
package com.example.bt6_aedapp;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
public class fragmentB extends Fragment implements GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,
LocationListener {
private GoogleMap map;
private LatLng latlng;
private LocationRequest lr;
private LocationClient lc;
MapFragment mapFragment;
ImageView iv;
private static View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if(parent != null) {
parent.removeView(view);
}
}
try {
view = inflater.inflate(R.layout.fragment_b, container, false);
mapFragment = ((MapFragment) this.getActivity().getFragmentManager().findFragmentById(R.id.map));
iv = (ImageView) view.findViewById(R.id.iv);
map = mapFragment.getMap();
map.getUiSettings().setAllGesturesEnabled(false);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(false);
MapsInitializer.initialize(this.getActivity());
}
catch (InflateException e) {
Toast.makeText(getActivity(), "Problems inflating the view !", Toast.LENGTH_LONG).show();
}
catch (NullPointerException e) {
Toast.makeText(getActivity(), "Google Play Services missing !", Toast.LENGTH_LONG).show();
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lr = LocationRequest.create();
lr.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
lc = new LocationClient(this.getActivity().getApplicationContext(),
this, this);
lc.connect();
}
#Override
public void onLocationChanged(Location location) {
latlng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latlng, 10);
map.animateCamera(cameraUpdate);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
}
#Override
public void onConnected(Bundle connectionHint) {
lc.requestLocationUpdates(lr, this);
}
#Override
public void onDisconnected() {
}
}
The error I'm getting now is located at row 115:
java.lang.NullPointerException
at com.example.bt6_aedapp.fragmentB.onLocationChanged(fragmentB.java:155)
I checked the location.getLatitude() and location.getLongitude() and both of them are NOT empty, they return a correct value.
Alright, so after a lot of debugging and research, I've found the solution.
All I had to do was replace
`mapFragment = ((MapFragment) this.getActivity().getFragmentManager().findFragmentById(R.id.map));`
with:
mapFragment = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map));