In my application I am using navigation drawer to move from one fragment to another.
If I move from about_us fragment to another then if I again comeback to same the activity is not getting resumed, instead the application is getting closed unfortunately.
Can anyone tell me what is the problem in my code, pls tell me the solution to fix this.
public class AboutUsFragment extends Fragment {
public AboutUsFragment(){}
private GoogleMap gmap;
static final double latitude = 33.12615;
static final double longitude = 80.21932;
TextView aboutUs;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_about_us, container, false);
initilizeMap();
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
View aboutUs = getActivity().findViewById(R.id.about_us_content_view);
try {
// Loading map
initilizeMap();
//To enable compass
gmap.getUiSettings().setCompassEnabled(true);
//To locate the school - Creating Marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("School Location");
// adding marker
gmap.addMarker(marker);
//We assigned latitude and longitude in Coordinate
LatLng coordinate = new LatLng(latitude, longitude);
CameraUpdate schoolLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
gmap.animateCamera(schoolLocation);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(coordinate) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
gmap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} catch (Exception e) {
e.printStackTrace();
}
}
private void initilizeMap()
{
if (gmap == null) {
gmap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (gmap == null) {
Toast.makeText(getActivity(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onResume() {
super.onResume();
initilizeMap();
}
}
And my about_us.xml is
<?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">
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="220dp" />
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/map"
android:layout_centerHorizontal="true" >
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/about_us_heading_View"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/about_us"
android:paddingTop="5dp"
android:paddingLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/about_us_content_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/abouts_us_content"
android:paddingTop="55dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
As I am completely new to Fragment. Someone pls tell me a noob way to fix it. Thanks a lot in advance.
add fragment to backstack before committing fragmnetTransaction
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.addToBackStack(null);
ft.replace(R.id.content_frame, fragment).commit();
Fragment with mapFragment in layout crashes when you resume cause for a fragment onCreateView is called every time you visit it every time.
Try to make your rootView static like below,
public static View mRootView;
public static boolean mOnRangeChange= false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(mRootView==null){
mRootView = inflater.inflate(R.layout.fragment_map, container, false);
}else{
ViewGroup parent = (ViewGroup) mRootView.getParent();
if (parent != null)
parent.removeView(mRootView);
}
map_layout = (FrameLayout) mRootView.findViewById(R.id.map_layout);
mcategory = (Button) mRootView.findViewById(R.id.contact_categories);
mSharedpreferenceUtility = SharedpreferenceUtility.getInstance(getActivity());
mcategory.setOnClickListener(this);
try {
initializeMap(mRootView);
} catch (Exception e) {
e.printStackTrace();
}
return mRootView;
}
Related
I have a Fragment that contains a map, this map is loaded up on the callback and OnMapReady which pulls in a map at my location successfully.
However I am trying to add in a feature whereby the user selects a location from a Spinner and the selection then draws the relevant Polygon on my map, however I keep getting an error 'Attempting to invoke virtual method Polygon'
I am by no means a talented Android developer, trying to learn and play about somewhat.
public class FindCarpark extends Fragment {
private SupportMapFragment mapFragment;
private UserLocation.OnFragmentInteractionListener mListener;
Spinner spinCar;
String selectedItem;
GoogleMap mMap;
private static final ArrayList<LatLng> cpB = new ArrayList<>();
public FindCarpark() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_find_carpark, container, false);
Context context = getActivity().getApplicationContext();
spinCar = rootView.findViewById(R.id.car_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),R.array.car_parks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinCar.setAdapter(adapter);
spinCar.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (i > 0) {
selectedItem = spinCar.getSelectedItem().toString().trim();
addCoords(selectedItem.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
new googleMap().makeMap(mMap);
}
});
}
getChildFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();
return rootView;
}
public void addCoords(String coords){
Log.i("coords", coords);
switch (coords){
case "B":
cpB.add(new LatLng(53.797731, -1.546351));
cpB.add(new LatLng(53.797551, -1.545983));
cpB.add(new LatLng(53.797447, -1.545267));
cpB.add(new LatLng(53.797731, -1.546351));
makePolygon(cpB);
Log.i("coords", cpB.toString());
break;
default:
break;
}
}
public void makePolygon(ArrayList<LatLng> coords){
mMap.addPolygon(new PolygonOptions()
.addAll(coords)
.strokeColor(Color.RED)
.fillColor(Color.BLUE));
}
XML:
<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=".FindCarpark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Spinner
android:id="#+id/car_spinner"
android:prompt="#string/app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
</Spinner>
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Polygon com.google.android.gms.maps.GoogleMap.addPolygon(com.google.android.gms.maps.model.PolygonOptions)' on a null object reference
Your mMap variable is never filled. This then later causes a null pointer exception. The problem is:
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
new googleMap().makeMap(mMap);
}
});
}
here mMap is a local variable, while the mMap you later try to access is a property of the object, thus:
if (mapFragment == null) {
mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
FindCarpark.this.mMap = mMap
new googleMap().makeMap(mMap);
}
});
}
I am working on a project in which I need to show a Map in home screen. I used fragment class.
When I first lunch my screen, it is showing map successfully. But when I again click on Home or again come back from another screen to that map screen, below error is showing and app crashes.
"android.view.InflateException: Binary XML file line #57: Error inflating class fragment"
Here is my xml class.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/homemap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
map:cameraTilt="50"
map:cameraZoom="40" />
</RelativeLayout>
And below is my Java class
public class Customer_Home_Map extends Fragment {
public Customer_Home_Map() {
}
private GoogleMap theMap;
ProgressDialog progressDialog = null;
ArrayList<SafetyResults_SearchResult> lstresult;
double lati = 0.0, longi = 0.0;
GPSTracker gps;
GoogleMap mMap;
SharedPreferences sharedPreferences;
int locationCount = 0;
API api = API.getInstance();
private HashMap<Marker, MyMarker> mMarkersHashMap;
private ArrayList<MyMarker> mMyMarkersArray = new ArrayList<MyMarker>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// View rootView = inflater.inflate(R.layout.customer_home_map,
// container,
// false);
View view = inflater.inflate(R.layout.customer_home_map,
null);
Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
up.getFont_Lato_Regular());
gps = new GPSTracker(getActivity());
showAddress();
return view;
}
private void showAddress() {
if (gps.canGetLocation()) {
lati = gps.getLatitude();
longi = gps.getLongitude();
straddress = getMyLocationAddress(lati, longi);
}
mMarkersHashMap = new HashMap<Marker, MyMarker>();
setUpMap();
plotMarkers(mMyMarkersArray);
}
private void plotMarkers(ArrayList<MyMarker> markers) {
if (markers.size() > 0) {
for (MyMarker myMarker : markers) {
// Create user marker with custom icon and other options
MarkerOptions markerOption = new MarkerOptions()
.position(new LatLng(myMarker.getmLatitude(), myMarker
.getmLongitude()));
markerOption.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker));
Marker currentMarker = mMap.addMarker(markerOption);
mMarkersHashMap.put(currentMarker, myMarker);
mMap.setInfoWindowAdapter(new MarkerInfoWindowAdapter());
}
}
}
private void setUpMap() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.homemap)).getMap();
LatLng coordinate = new LatLng(lati, longi);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(
coordinate, 15);
mMap.animateCamera(yourLocation);
// Check if we were successful in obtaining the map.
if (mMap != null) {
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(
com.google.android.gms.maps.model.Marker marker) {
marker.showInfoWindow();
return true;
}
});
} else
Toast.makeText(getActivity().getApplicationContext(),
"Unable to create Maps", Toast.LENGTH_SHORT).show();
}
}
public class MarkerInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
public MarkerInfoWindowAdapter() {
}
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getActivity().getLayoutInflater().inflate(
R.layout.infowindow_layout, null);
MyMarker myMarker = mMarkersHashMap.get(marker);
ImageView markerIcon = (ImageView) v.findViewById(R.id.marker_icon);
TextView markerLabel = (TextView) v.findViewById(R.id.marker_label);
markerIcon.setImageResource(manageMarkerIcon(myMarker.getmIcon()));
markerLabel.setText(myMarker.getmLabel());
TextView anotherLabel = (TextView) v
.findViewById(R.id.another_label);
// anotherLabel.setText("A custom text");
return v;
}
}
private int manageMarkerIcon(String markerIcon) {
if (markerIcon.equalsIgnoreCase("3"))
return R.drawable.ambulance;
else if (markerIcon.equalsIgnoreCase("4"))
return R.drawable.doctor;
else if (markerIcon.equalsIgnoreCase("me"))
return R.drawable.marker;
else
return R.drawable.marker;
}
}
I am attaching my logcat error snap below
this is xml code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="16dp"
tools:context=".Googlemap.Googlemap">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"/>
</RelativeLayout>
and code should be something like this
private GoogleMap googleMap;
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.setMyLocationEnabled(true);
}
hopefully this will work.
I searched a lot and now I found solutions of my problem.
I write below code in my activity.
#Override
public void onDestroyView() {
try {
MapFragment f = (MapFragment) getFragmentManager()
.findFragmentById(R.id.homemap);
if (getActivity().isFinishing()) {
}
else if (f != null)
getActivity().getFragmentManager().beginTransaction().remove(f)
.commit();
} catch (Exception e) {
}
super.onDestroyView();
}
Thanks All for giving you valuable time and suggestions.
I am fairly new at Android dev, so bear with me. I am having some problems with instance state saving for my google maps api implementation i believe. I am using Android Studio. I am implementing AppCompactActivity to setup a tab view. I am changing fragments in my pager view using a FragmentStatePagerAdapter. My problem is that My google maps api will not save state in very certain circumstances. If i am clicking a tab that is >1 index away from my MapFragment index, the state of the map fragment will not be retained and i cannot add markers or a Go Home button to the map, but the map is present.
My initial marker and home location button works, it just won't show back up/allow me to add more markers after i switch to my last tab and switch back to the map tab.
As i said, i am new at android dev, so any advice is appreciative.
This is my main activity
public class MainActivity extends AppCompatActivity{
public static FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Map"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
with main activity xml as this
<RelativeLayout
android:id="#+id/main_layout"
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">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
This is my PagerAdapter class
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TabFragment1();
case 1:
return new MapViewFragment();
case 2:
return new TabFragment2();
case 3:
return new TabFragment3();
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
this is my MapFragment class
public class MapViewFragment extends Fragment {
private static View view;
/**
* Note that this may be null if the Google Play services APK is not
* available.
*/
private static GoogleMap mMap;
private static Double latitude, longitude;
private static String quickFilterText="";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
view = inflater.inflate(R.layout.activity_maps, container, false);
// Passing harcoded values for latitude & longitude. Please change as per your need. This is just used to drop a Marker on the Map
latitude = 26.78;
longitude = 72.56;
ImageButton arrowButton = (ImageButton) view.findViewById(R.id.arrowButton);
arrowButton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View newView) {
RelativeLayout relLayout = (RelativeLayout) view.findViewById(R.id.filterDropDown);
EditText text = (EditText) view.findViewById(R.id.quickFilter);
try
{
quickFilterText = text.getText().toString();
}
catch(Exception err)
{
}
if(relLayout.getHeight()>0)
{
relLayout.setLayoutParams(new RelativeLayout.LayoutParams(relLayout.getWidth(),0));
}
else
{
relLayout.setLayoutParams(new RelativeLayout.LayoutParams(relLayout.getWidth(),180));
}
}
});
return view;
}
/***** Sets up the map if it is possible to do so *****/
public void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
setUpMap();
}
}
/**
* This is where we can add markers or lines, add listeners or move the
* camera.
* <p>
* This should only be called once and when we are sure that {#link #mMap}
* is not null.
*/
private static void setUpMap() {
// For showing a move to my loction button
mMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("My Home").snippet("Home Address"));
// For zooming automatically to the Dropped PIN Location
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,
longitude), 12.0f));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
setUpMapIfNeeded();
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(map)).getMap(); // getMap is deprecated
// Check if we were successful in obtaining the map.
if (mMap != null)
setUpMap();
}
setRetainInstance(true);
}
/**** The mapfragment's id must be removed from the FragmentManager
**** or else if the same it is passed on the next time then
**** app will crash ****/
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
}
and this is my activity_maps.xml
<RelativeLayout 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=".MapActivity">
<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" />
<RelativeLayout
android:id="#+id/filterDropDown"
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:background="#80000000"
android:gravity="top|center"
android:padding="4dp"
android:weightSum="1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:text="Filter"
android:id="#+id/filterTextBox"
android:gravity="center_vertical" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/quickFilter"
android:paddingRight="8dp"
android:paddingLeft="8dp"
android:layout_toRightOf="#+id/filterTextBox" />
</RelativeLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/arrow"
android:layout_width="70dp"
android:layout_height="23dp"
android:orientation="horizontal"
android:background="#drawable/shape"
android:gravity="center"
android:padding="4dp"
android:layout_gravity="center_horizontal|top"
android:weightSum="1"
android:layout_centerHorizontal="true"
android:layout_below="#+id/filterDropDown">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Filter"
android:id="#+id/arrowButton"
android:background="#drawable/down_arrow"
android:clickable="true" />
</RelativeLayout>
</RelativeLayout>
my other 3 tabs are just simple fragments with a text view inside of them
public class TabFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_fragment_1, container, false);
}
}
with layout
<?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"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Tab 1"
android:textAppearance="?android:attr/textAppearanceLarge"/>
</RelativeLayout>
By default the view pager keeps the current fragment, and one fragment to the left and right of it alive. In your pager adapter you are telling it the create a brand new fragment, instead of using the existing one.
List<Fragment> myPages; // populate this in the constructor
#Override
public Fragment getItem(int position) {
return myPages.get(position);
}
#Override
public int getCount() {
return myPages.size();
}
You should also increase the off screen page limit if you know you will only ever have those four fragments.
viewPager.setOffscreenPageLimit(3);
If you run into more problems with the map after doing these two things you may want to set the map fragment to retain its instance state. Override the fragments onCreate() method.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
I have a dialog fragment where i want to show my map and mark the lat and log which i have with with me.
But i am getting my getMap() as NULL. This is what i did
public class EventDetailsDialogFragment extends DialogFragment{
TextView title, desc, sdate, edate, room, loctn;
FeedObjModel selectedFeedObject;
Date netDate;
SimpleDateFormat sdf;
GoogleMap theMap;
MarkerOptions markerOptions;
FragmentActivity myContext;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.event_details_dialog_layout, container);
title = (TextView) view.findViewById(R.id.title_event_details_TV);
desc = (TextView) view.findViewById(R.id.description_event_details_TV);
sdate = (TextView) view.findViewById(R.id.start_date_event_details_TV);
edate = (TextView) view.findViewById(R.id.end_date_event_details_TV);
loctn = (TextView) view.findViewById(R.id.locEdTV);
long timestamp1 = Long.parseLong(selectedFeedObject.eventstartDate);
long timestamp2 = Long.parseLong(selectedFeedObject.eventendDate);
try{
sdf = new SimpleDateFormat("MMM dd, yyyy");
netDate = (new Date(timestamp1*1000));
sdate.setText(sdf.format(netDate));
netDate = (new Date(timestamp2*1000));
edate.setText(sdf.format(netDate));
} catch(Exception ex){
}
getDialog().setTitle(""+selectedFeedObject.subject);
title.setText(selectedFeedObject.subject);
desc.setText(selectedFeedObject.eventDescription);
loctn.setText(selectedFeedObject.eventLocation);
/* theMap = ((SupportMapFragment) getActivity().getSupportFragmentManager()
.findFragmentById(R.id.mapED))
.getMap();*/
SupportMapFragment fragment = new SupportMapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.mapED, fragment).commit();
theMap = fragment.getMap();
Log.v("theMap1", ""+theMap);
Double lng = Double.parseDouble(selectedFeedObject.eventlongitude);
Double lat = Double.parseDouble(selectedFeedObject.eventlatitude);
LatLng latLng = new LatLng(lng, lat);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(selectedFeedObject.eventLocation);
Log.v("markerOptions", ""+markerOptions);
theMap.addMarker(markerOptions);
theMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate center = CameraUpdateFactory
.newLatLng(new LatLng(lat, lng));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
theMap.moveCamera(center);
theMap.animateCamera(zoom);
return view;
}
public void setEventDetails(FeedObjModel _selectedFeedObject) {
// TODO Auto-generated method stub
selectedFeedObject = _selectedFeedObject;
}
}
i am getting 'themap' as NULL
.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="5dp"
android:paddingTop="5dp" >
<TextView
android:id="#+id/title_event_details_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Description"
android:textSize="16sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/description_event_details_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Date and Time"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/start_date_event_details_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="End Date and Time"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/end_date_event_details_TV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Location"
android:textSize="16sp"
android:textStyle="bold"/>
<TextView
android:id="#+id/locEdTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<FrameLayout
android:id="#+id/mapED"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
</LinearLayout>
I wrote the following code in onResume() now this is working...i don't know is this the right way.
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
theMap = mapView.getMap();
Log.v("theMap1", ""+theMap);
Log.v("lng", ""+lng);
Log.v("lat", ""+lat);
latLng = new LatLng(lng, lat);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title(locString);
Log.v("markerOptions", ""+markerOptions);
theMap.addMarker(markerOptions);
theMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate center=
CameraUpdateFactory.newLatLngZoom(new LatLng(lat,
lng),16);
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
theMap.moveCamera(center);
theMap.animateCamera(zoom);
}
in oncreateview
mapView = CustomMapFragmentForEventDetails.newInstance();
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.mapED, mapView);
fragmentTransaction.commit();
lng = Double.parseDouble(selectedFeedObject.eventlongitude);
lat = Double.parseDouble(selectedFeedObject.eventlatitude);
and in CustomMapFragmentForEventDetails
public class CustomMapFragmentForEventDetails extends SupportMapFragment {
SupportMapFragment mSupportMapFragment;
GoogleMap googleMap;
OnMapReadyListener mOnMapReadyListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
Log.v("Inside CustomMapFrag", "Success");
View root = inflater.inflate(R.layout.event_details_dialog_layout, null, false);
initilizeMap();
return root;
}
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
mOnMapReadyListener = (OnMapReadyListener) activity;
}
private void initilizeMap()
{
mSupportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.mapED);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.mapED, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null)
{
googleMap = mSupportMapFragment.getMap();
if (googleMap != null)
{
Log.v("MAP GOOGLE in CustomMApfragment", ":: "+googleMap);
mOnMapReadyListener.onMapReady(googleMap);
}
}
}
public static interface OnMapReadyListener {
void onMapReady(GoogleMap googleMap);
}
}
I guess this is because even thought the Transaction of the map fragment is committed it does not execute immediately. You have to use : FragmentManager.executePendingTransactions() this way :
SupportMapFragment fragment = new SupportMapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.mapED, fragment).commit();
getFragmentManager().executePendingTransactions();
theMap = fragment.getMap();
Good night,
I have an application with a map in a swipe tab, but I want that map select a point and start at that point.
Thank you in advance.
Enclose JAVA:
public class Mapa extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View android = inflater.inflate(R.layout.mapa_3, container, false);
return android;
}
#Override
public void onDestroyView() {
super.onDestroyView();
Fragment f = getFragmentManager().findFragmentById(R.id.mapFragment);
if (f != null)
getFragmentManager().beginTransaction().remove(f).commit();
}
}
the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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_container"
tools:context=".Mapa" >
<fragment
android:id="#+id/mapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
I guess you want to add a marker to a map and set camera to look at it. Here is how you can achieve it(more info here and here):
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View android = inflater.inflate(R.layout.mapa_3, container, false);
final LatLng position = new LatLng(MARKER_LATITUDE, MARKER_LONGITUDE);
// marker
map = ((MapFragment) getSupportFragmentManager().findFragmentById(R.id.mapFragment)).getMap();
map.addMarker(new MarkerOptions()
.position(position)
.title("Hello world"));
// camera position
map.setOnCameraChangeListener(new OnCameraChangeListener()
{
#Override
public void onCameraChange(CameraPosition arg0)
{
CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(position, 14);
map.animateCamera(cu);
map.setOnCameraChangeListener(null);
}
});
return android;
}