My application shows blank google map on a fragment. I just call that fragment from MainActivity. I have searched/read on google, but none did help me at. I am not getting any error and I have used proper APIs Keys.
The following are my classes/mxls:
public class MainActivity extends AppCompatActivity {
private Button map_me;
private Button bCordinates;
public static Location mLastKnownLocation;
private FusedLocationProviderClient mFusedLocationProviderClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try {
if (true) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful()) {
//Get the Location of the current device
mLastKnownLocation = task.getResult();
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
bCordinates = (Button)findViewById(R.id.bcordinates);
bCordinates.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Toast.makeText(getApplicationContext(),""+mLastKnownLocation.getLatitude()+" , " +
" "+mLastKnownLocation.getLongitude(),Toast.LENGTH_LONG).show();
}
});
map_me = (Button)findViewById(R.id.bmap);
map_me.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyMapFragment myMapFragment = new MyMapFragment();
fragmentTransaction.add(R.id.fragment_container, myMapFragment);
fragmentTransaction.commit();
}
});
}
}
public class MyMapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap googleMap;
private MapView mapView;
private View view;
private FusedLocationProviderClient mFusedLocationProviderClient;
public MyMapFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.map_layout, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) getView().findViewById(R.id.map);
if(mapView!=null)
{
mapView.onCreate(null);
mapView.onResume();
mapView.getMapAsync(this);
}
}
#Override
public void onMapReady(final GoogleMap mGoogleMap) {
{
googleMap = mGoogleMap;
LatLng mLatLng = new LatLng(mLastKnownLocation.getLatitude(),
mLastKnownLocation.getLongitude());
googleMap.addMarker(new MarkerOptions().position(mLatLng).title("You're here"));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mLatLng,15));
mapView.onResume();
}
}
}
map fragment layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MyMapFragment">
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
/>
</FrameLayout>
main activity layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.bdushimi.android2.MainActivity"
>
<Button
android:id="#+id/bmap"
android:layout_width="88dp"
android:layout_height="wrap_content"
android:text="MAP Me!"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginStart="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintHorizontal_bias="0.067"
tools:layout_editor_absoluteY="32dp" />
<Button
android:id="#+id/btext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT ME!"
tools:layout_editor_absoluteY="32dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintHorizontal_bias="0.464" />
<Button
android:id="#+id/bcordinates"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cordinates"
android:layout_marginEnd="8dp"
tools:layout_editor_absoluteY="32dp"
android:layout_marginRight="28dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintHorizontal_bias="0.949"
app:layout_constraintLeft_toLeftOf="parent" />
<LinearLayout
android:id="#+id/fragment_container"
android:layout_width="333dp"
android:layout_height="370dp"
android:orientation="vertical"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="125dp"
app:layout_constraintHorizontal_bias="0.514"></LinearLayout>
</android.support.constraint.ConstraintLayout>
Please, help me to find out what I am doing wrong.
I think you should use MapFragment or SupportMapFragment in your map layout xml file according to your usability.
For now :
Replace :
with :
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/headerLayout"
tools:context="com.dxs.rnf.winwin.main.ui.fragments.DashboardMapFragment"
android:name="com.google.android.gms.maps.MapFragment"/>
Note : Also check your GOOGLE_API_KEY
Related
i'm using a map in a fragment but as shown on the following screenshot, the map doesn't apear. I made sure i have an internet connection and a gps signal so i don't think it's a connectivity problem.
Here is the code from my fragment:
public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_fragment, container, false);
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView = rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// For showing a move to my location button
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
#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();
}
}
And here is the xml file of the fragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I am then inserting this fragment into my main activity layout using the following procedure:
public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
if (addToBackStack) {
ft.addToBackStack(tag);
}
ft.replace(R.id.container_frame_back, fragment, tag);
ft.commitAllowingStateLoss();
}
XML file of my MainActivity
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<Button
android:id="#+id/btn1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Fragment 1 " />
</LinearLayout>
<LinearLayout
android:id="#+id/container_frame_back"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="56dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
So i don't really get why i have no map showing up, i don't think it's a permissions problem either, iv'e already worked with maps in previous projects but this time it's just not showing up for some reason... Thank you for any reply!
Problem solved, it turns out that error messages related to permissions aren't displayed in the logs when you test your app on an external device. I had problems with permissions in my maps fragment. I just added the following code and it worksjust fine:
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION};
requestPermissions(perms, 0); // Use this method in Fragment classes
After adding Google Maps into the drawer navigation, the map isn't neither zoomable nor movable. I know, there are some questions about it, but I'm using the drawer navigation as a clickable menu, which is called from a bottom navigation bar, which makes my case slightly different. Hence I need the drawer navigation in the MapsActivity class.
My Code -
MapsActivity:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,
NavigationView.OnNavigationItemSelectedListener {
private GoogleMap mMap;
public Toolbar toolbar;
public DrawerLayout drawerLayout;
public NavController navController;
public NavigationView accountNavigationView, settingsNavigationView;
private SeekBar distanceSeekbar;
private TextView distanceText;
private FusedLocationProviderClient fusedLocationProviderClient;
private static int radius;
static List<Circle> mCircleList;
#Override
protected void onCreate(Bundle savedInstanceState) {
ActivityCompat.requestPermissions(MapsActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
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);
drawerLayout = findViewById(R.id.drawer_layout);
// disable slide on drawer navigation
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_account:
Toast.makeText(MapsActivity.this, "Profile", Toast.LENGTH_SHORT).show();
drawerLayout.openDrawer(Gravity.LEFT);
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
}
break;
case R.id.action_map:
Toast.makeText(MapsActivity.this, "Map", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MapsActivity.this, MapsActivity.class));
break;
case R.id.action_settings:
Toast.makeText(MapsActivity.this, "Settings", Toast.LENGTH_SHORT).show();
drawerLayout.openDrawer(Gravity.RIGHT);
if (drawerLayout.isDrawerOpen(Gravity.LEFT)) {
drawerLayout.closeDrawer(Gravity.LEFT);
}
break;
}
return true;
}
});
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
setupNavigation();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
final LatLng current_location = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(current_location).title("Current location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(current_location));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(current_location, 14));
// set radius on user's settings
distanceSeekbar = (SeekBar) findViewById(R.id.distance_seekbar);
distanceSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// set progress as text
distanceText = (TextView) findViewById(R.id.distance_text);
distanceText.setText("Distance: " + progress);
if (mCircleList == null) {
mCircleList = new ArrayList<Circle>();
} else if (mCircleList.size() >= 1) {
deleteCircles();
}
radius = progress;
setCircle(current_location, radius);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
});
}
mMap.setOnCircleClickListener(new GoogleMap.OnCircleClickListener() {
#Override
public void onCircleClick(Circle circle) {
int strokeColor = circle.getStrokeColor() ^ 0x00ffffff;
circle.setFillColor(strokeColor);
}
});
}
// set circle
private void setCircle(LatLng currentLocation, int radius) {
CircleOptions circleOptions = new CircleOptions()
.center(currentLocation)
.radius(radius)
.strokeWidth(2)
.strokeColor(Color.GREEN)
.fillColor(Color.argb(128, 255, 0, 0))
.clickable(true);
Circle circle = mMap.addCircle(circleOptions);
mCircleList.add(circle);
}
public void deleteCircles() {
for (int i = 0; i <= mCircleList.size() - 1; i++) {
Circle mCircle = mCircleList.get(i);
mCircle.remove();
}
mCircleList.clear();
}
private void setupNavigation() {
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
drawerLayout = findViewById(R.id.drawer_layout);
accountNavigationView = findViewById(R.id.account_navigationView);
settingsNavigationView = findViewById(R.id.settings_navigationView);
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout);
NavigationUI.setupWithNavController(accountNavigationView, navController);
NavigationUI.setupWithNavController(settingsNavigationView, navController);
accountNavigationView.setNavigationItemSelectedListener(this);
settingsNavigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onSupportNavigateUp() {
return NavigationUI.navigateUp(drawerLayout, Navigation.findNavController(this, R.id.nav_host_fragment));
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
menuItem.setChecked(true);
drawerLayout.closeDrawers();
int id = menuItem.getItemId();
switch (id) {
case R.id.home:
navController.navigate(R.id.homeFragment);
break;
case R.id.locations:
navController.navigate(R.id.locationsFragment);
break;
case R.id.saved:
navController.navigate(R.id.savedFragment);
break;
}
return true;
}
}
activity_maps.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
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=".MapsActivity" />
<!--Account-->
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
tools:layout_editor_absoluteX="0dp">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/account_navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="left"
android:fitsSystemWindows="true"
app:headerLayout="#layout/header_layout"
app:menu="#menu/account_drawer_menu" />
<!--Settings-->
<com.google.android.material.navigation.NavigationView
android:id="#+id/settings_navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:fitsSystemWindows="true"
app:headerLayout="#layout/header_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/distance_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignTop="#id/distance_seekbar"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:text="Distance" />
<SeekBar
android:id="#+id/distance_seekbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:max="200"/>
</LinearLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_navigation"
app:itemBackground="#color/colorPrimary"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_nav_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>
How can I make it work again, so that the map is zoomable and movable? Thanks for reading and any help!
Maybe your DrawerLayout is overlapping your map fragment making a layer that prevents your interaction with the map.
Try add the Map Fragment inside your DrawerLayout to do a test
If necessary comment/hide your Navigation Host Fragment.
If the map work as expected you can create a new View like accountNavigationView and add your map to your Navigation Host Fragment something like this:
NavigationUI.setupWithNavController(mapView, navController);
Below the test proposal:
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity"
tools:layout_editor_absoluteX="0dp">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize" />
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
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=".MapsActivity" />
<fragment
android:id="#+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="#navigation/nav_graph" />
<com.google.android.material.navigation.NavigationView
android:id="#+id/account_navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="left"
android:fitsSystemWindows="true"
app:headerLayout="#layout/header_layout"
app:menu="#menu/account_drawer_menu" />
<!--Settings-->
<com.google.android.material.navigation.NavigationView
android:id="#+id/settings_navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:fitsSystemWindows="true"
app:headerLayout="#layout/header_layout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/distance_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignTop="#id/distance_seekbar"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:text="Distance" />
<SeekBar
android:id="#+id/distance_seekbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:max="200"/>
</LinearLayout>
</com.google.android.material.navigation.NavigationView>
</androidx.drawerlayout.widget.DrawerLayout>
I am trying to implement PlaceAutoCompleteFragment inside a fragment. I have end up with this (based on the accepted answer of this question):
public class SecondFragment extends Fragment
implements OnMapReadyCallback {
PlaceAutocompleteFragment placeAutoComplete;
.....
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_second, null, false);
// Create Map
if (savedInstanceState != null) {
mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
latlang.Lat = mLastKnownLocation.getLatitude();
latlang.Lang = mLastKnownLocation.getLongitude();
}
// Construct a FusedLocationProviderClient.
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
getLocationPermission();
getDeviceLocation();
placeAutoComplete = (PlaceAutocompleteFragment) getActivity().getFragmentManager().findFragmentById(R.id.place_autocomplete);
placeAutoComplete.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
Log.d("Maps", "Place selected: " + place.getName());
}
#Override
public void onError(Status status) {
Log.d("Maps", "An error occurred: " + status);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
//Search Place
return view;
}
and the corresponding layout is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondFragment"
android:orientation="vertical"
android:weightSum="1">
<fragment
android:id="#+id/place_autocomplete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
So, I got a searchbar which, on click opens up and keyboard flashes for a second and then crashes, before I start typing, and returns to "before click" view.
Whats going wrong here?
I'm trying to add a simple fragment and it works perfectly when I use it, until I switch rotations than it crashes.
Here is my code:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_user);
//region Fragment
if(savedInstanceState==null){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment_Titlebar fragment = new Fragment_Titlebar();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
Fragment_Titlebar header = (Fragment_Titlebar) getFragmentManager().findFragmentById(R.id.fragment);
header.initFragment(R.string.SignUp, 0, true, true);}
//endregion
voornaam = (EditText)findViewById(R.id.first_name_text);
achternaam = (EditText)findViewById(R.id.last_name_text);
profile = (CircleImageView)findViewById(R.id.profile_image);
try {
//Getting the google account
Intent intent = getIntent();
if (intent.getExtras().get("User") instanceof GoogleSignInAccount) {
GoogleSignInAccount acct = (GoogleSignInAccount) intent.getExtras().get("User");
voornaam.setText(acct.getGivenName());
achternaam.setText(acct.getFamilyName());
if (acct.getPhotoUrl() != null) {
Picasso.with(this).load(acct.getPhotoUrl()).into(profile);
}
}
}
catch (NullPointerException e)
{
}
}}
And the Fragment:
private TextView headerText;
private ImageButton backButton;
private ImageButton homeButton;
private Toolbar background;
public Fragment_Titlebar(){}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_title_bar, container, false);
backButton = (ImageButton) view.findViewById(R.id.backButton);
backButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
goBack(v);
}
});
homeButton = (ImageButton) view.findViewById(R.id.homeButton);
homeButton.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v) {
goHome(v);
}
}
);
headerText = (TextView) view.findViewById(R.id.headerText);
background = (Toolbar) view.findViewById(R.id.background);
return view;
}
finally the error message:
FATAL EXCEPTION: main
Process: rickvanfessem.carcoolandroid, PID: 18652
java.lang.RuntimeException: Unable to start activity ComponentInfo{rickvanfessem.carcoolandroid/rickvanfessem.carcoolandroid.AddUser}: android.view.InflateException: Binary XML file line #10: Binary XML file line #10: Error inflating class fragment
I already tried to do this setRetainInstance(true) but that didn't work.
Please Help
EDIT AFTER REQUEST FOR XML
XML of the Fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
xmlns:android="http://schemas.android.com/apk/res/android">
<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/background"
android:background="#color/HeaderRed"
app:theme="#style/AppTheme"
app:popupTheme="#style/ThemeOverlay.AppCompat.Dark">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/backButton"
style="#style/image_style"
android:layout_alignParentLeft="true"
android:src="#drawable/ic_arrow_back"
/>
<TextView
android:id="#+id/headerText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
style="#style/HeaderText"
tools:text="Test scherm"/>
<ImageButton
android:id="#+id/homeButton"
style="#style/image_style"
android:layout_alignParentRight="true"
android:src="#drawable/ic_home"
/>
</RelativeLayout>
</Toolbar>
</LinearLayout>
try this
Edit your Manifest
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
/>
and in MainActivity
add this Override Method
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation== Configuration.ORIENTATION_PORTRAIT)
{
}
else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
}
}
I am adding SupportMapFragment programmatically to my main activity.
I am able to add it but i need a edit text and a button also to be displayed at the top of the map.
I have created a separate layout for my map fragment which i add programmatically inside my main activity. But i get a NPE saying "Unable to resume activity"
Please help me.
Here is my code . MainActivity.java
public class MainActivity extends FragmentActivity{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
private ImageView mImage;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get an instance of FragmentTransaction from your Activity
final FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
mImage = (ImageView)findViewById(R.id.eemaView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click eema");
EnterpriseFragment entFragment = new EnterpriseFragment();
FragmentTransaction fragmentTrans = fragmentManager.beginTransaction();
fragmentTrans.replace(R.id.appfragment, entFragment);
fragmentTrans.commit();
}
});
mImage = (ImageView)findViewById(R.id.deviationView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click deviation");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
}
});
}
Here is my fragment class
public class MapFragmentActivity extends SupportMapFragment implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.mapfragmentlayout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = this.getMap();
if (googleMap != null) {
//Your initialization code goes here
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
// Getting reference to btn_find of the layout activity_main
//Button btn_find = (Button) getActivity().findViewById(R.id.btn_find);
// Defining button click event listener for the find button
View.OnClickListener findClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to EditText to get the user input location
EditText etLocation = (EditText) getActivity().findViewById(R.id.et_location);
// Getting user input location
String location = etLocation.getText().toString();
if(location!=null && !location.equals("")){
for(Marker m : markerslist) {
System.out.println("Marker size is "+markerslist.size());
System.out.println("Title is "+m.getSnippet());
System.out.println("Position is "+((LatLng)(m.getPosition())).latitude);
if(location.equals(m.getSnippet())) {
// do something with the marker
LatLng latLng = m.getPosition();
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
break; // stop the loop
}
}
}
}
};
// Setting button click event listener for the find button
//btn_find.setOnClickListener(findClickListener);
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getActivity().getLayoutInflater().inflate(R.layout.site_info_window, null);
List<String> qfList = JSONReader.readQuickFixData(getActivity());
ListView devLst = (ListView)v.findViewById(R.id.deviationList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_list_item_deviation,android.R.id.text1,qfList);
devLst.setAdapter(adapter);
return v;
}
});
}
}
This is my fragment layout 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">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find"
android:layout_alignParentRight="true" />
<EditText
android:id="#+id/et_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Enter Site ID"
android:layout_toLeftOf="#id/btn_find" />
</RelativeLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
My main layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="WEM App"
android:id="#+id/textView"
android:textStyle="bold"
android:textSize="16sp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_margin="3dp"
android:textColor="#color/abc_input_method_navigation_guard"
android:background="#android:color/holo_green_light"/>
<LinearLayout
android:id="#+id/appfragment"
android:layout_width="match_parent"
android:layout_weight="4"
android:layout_height="0dip"
android:orientation="horizontal">
</LinearLayout>
<HorizontalScrollView
android:id="#+id/hsview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="3dp"
android:background="#android:color/holo_green_light">
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/deviationView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/eemaView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
<ImageView
android:id="#+id/siteView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/alertsView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Make sure u r using import android.support.v4.app.Fragment; and import android.support.v4.app.FragmentTransaction;
Make changes as below -
change public class MapFragmentActivity extends SupportMapFragment
to public class MapFragmentActivity extends Fragment keep rest as it is.