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();
Related
I want to set the mapview to full screen, I had done every necessary things like setting both the framelayout and the mapview to matchparent but still when i run the app on my phone only a portion(maybe 60dp is the height but the width is fullscreen) of map was visible.
Here are some of my layout xml file.
//// for the fragment map ///////////
<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=".MapFragment">
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/frg"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
//// for the fragment map ///////////
//// for the java fragment map code //////
public class MapFragment extends Fragment {
public MapFragment() {
// 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
final View rootView = inflater.inflate(R.layout.fragment_map, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.frg); //use SuppoprtMapFragment for using in fragment instead of activity MapFragment = activity SupportMapFragment = fragment
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
LatLng customMarkerLocationOne = new LatLng(15.492554, 120.972169);
LatLng customMarkerLocationTwo = new LatLng(15.483516, 120.962996);
LatLng customMarkerLocationThree = new LatLng(15.486315, 120.973318);
LatLng customMarkerLocationFour = new LatLng(15.485838, 120.972290);
mMap.addMarker(new MarkerOptions().position(customMarkerLocationOne).
icon(BitmapDescriptorFactory.fromBitmap(
createCustomMarker(rootView.getContext(),R.drawable.yumin,"Yumin")))).setTitle("Korean Food House");
mMap.addMarker(new MarkerOptions().position(customMarkerLocationTwo).
icon(BitmapDescriptorFactory.fromBitmap(
createCustomMarker(rootView.getContext(),R.drawable.puregold,"Puregold")))).setTitle("Grocery Store");
mMap.addMarker(new MarkerOptions().position(customMarkerLocationThree).
icon(BitmapDescriptorFactory.fromBitmap(
createCustomMarker(rootView.getContext(),R.drawable.mrsg,"Mrs. G")))).setTitle("Cake Shop");
mMap.addMarker(new MarkerOptions().position(customMarkerLocationFour).
icon(BitmapDescriptorFactory.fromBitmap(
createCustomMarker(rootView.getContext(),R.drawable.actron,"Actron")))).setTitle("Electronic Shop");
//LatLngBound will cover all your marker on Google Maps
LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(customMarkerLocationOne); //Taking Point A (First LatLng)
builder.include(customMarkerLocationThree); //Taking Point B (Second LatLng)
LatLngBounds bounds = builder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 200);
mMap.moveCamera(cu);
mMap.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
}
});
return rootView;
}
public static Bitmap createCustomMarker(Context context, #DrawableRes int resource, String _name) {
View marker = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.bitmap_google_marker_layout_item, null);
CircleImageView markerImage = (CircleImageView) marker.findViewById(R.id.user_dp);
markerImage.setImageResource(resource);
TextView txt_name = (TextView)marker.findViewById(R.id.name);
txt_name.setText(_name);
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
marker.setLayoutParams(new ViewGroup.LayoutParams(52, ViewGroup.LayoutParams.WRAP_CONTENT));
marker.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
marker.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
marker.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(marker.getMeasuredWidth(), marker.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
marker.draw(canvas);
return bitmap;
}
}
//// for the java fragment map code ///////////
//// for the Home Activity ///////////
<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:id="#+id/container"
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".HomeBuyersActivity">
<EditText
android:id="#+id/search_bar_home"
android:layout_width="0dp"
android:layout_height="30dp"
android:layout_marginStart="32dp"
android:layout_marginEnd="8dp"
android:background="#drawable/search_card"
android:elevation="3dp"
android:ems="10"
android:textSize="12sp"
android:inputType="textPersonName"
android:padding="4dp"
android:textColor="#333333"
app:layout_constraintBottom_toBottomOf="#+id/search_icon_home"
app:layout_constraintEnd_toStartOf="#+id/search_icon_home"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/search_icon_home" />
<ImageView
android:id="#+id/search_icon_home"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginEnd="50dp"
android:background="#drawable/searchhh"
android:elevation="3dp"
android:tint="#333333"
app:layout_constraintBottom_toBottomOf="#+id/cart_icon_home"
app:layout_constraintEnd_toStartOf="#+id/cart_icon_home"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<ImageView
android:id="#+id/cart_icon_home"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:background="#drawable/icon_for_cart"
android:elevation="3dp"
android:textAlignment="textEnd"
android:tint="#333333"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ScrollView
android:id="#+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0px"
app:layout_constraintBottom_toTopOf="#+id/nav_view"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/nav_view"
android:layout_width="0dp"
android:layout_height="60dp"
android:layout_marginStart="0dp"
android:layout_marginEnd="0dp"
android:background="#drawable/card_white_sharp_edges"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:menu="#menu/bottom_nav_menu" />
</androidx.constraintlayout.widget.ConstraintLayout>
//// for the Home Activity ///////////
//// for the Home Activity Java ///////////
public class HomeBuyersActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private CallbackManager callbackManager;
private String TAG = "";
private EditText search_bar_home;
private ImageView search_icon_home, cart_icon_home;
private Toolbar toolbar;
private boolean mLocationPermissionGranted = false;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
mAuth = FirebaseAuth.getInstance();
callbackManager = CallbackManager.Factory.create();
search_bar_home = findViewById(R.id.search_bar_home);
search_icon_home = findViewById(R.id.search_icon_home);
cart_icon_home = findViewById(R.id.cart_icon_home);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
final Intent intent = getIntent();
final String UserID = intent.getStringExtra("userid");
final String Firstname = intent.getStringExtra("firstname");
final String Lastname = intent.getStringExtra("lastname");
final String Email = intent.getStringExtra("email");
final String Image = intent.getStringExtra("imageurl");
final String ReferralCOde = intent.getStringExtra("refer");
Paper.init(HomeBuyersActivity.this);
final String UserEmailKey = Paper.book().read(Prevalent.UserEmailKey);
final String UserPasswordKey = Paper.book().read(Prevalent.UserPasswordKey);
switch (item.getItemId()) {
case R.id.navigation_home:
HomeFragment fragment = new HomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransaction.commit();
search_bar_home.setVisibility(View.VISIBLE);
search_icon_home.setVisibility(View.VISIBLE);
cart_icon_home.setVisibility(View.VISIBLE);
return true;
case R.id.navigation_map:
MapFragment map = new MapFragment();
Bundle bundlem = new Bundle();
bundlem.putString("firstname", Firstname);
bundlem.putString("lastname", Lastname);
bundlem.putString("imageurl", Image);
bundlem.putString("userid", UserID);
bundlem.putString("email", Email);
bundlem.putString("refer", ReferralCOde);
map.setArguments(bundlem);
FragmentTransaction fragmentTransactionm = getSupportFragmentManager().beginTransaction();
fragmentTransactionm.replace(R.id.fragment_container, map);
fragmentTransactionm.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransactionm.commit();
search_bar_home.setVisibility(View.INVISIBLE);
search_icon_home.setVisibility(View.INVISIBLE);
cart_icon_home.setVisibility(View.INVISIBLE);
return true;
case R.id.navigation_notifications:
search_bar_home.setVisibility(View.INVISIBLE);
search_icon_home.setVisibility(View.INVISIBLE);
cart_icon_home.setVisibility(View.INVISIBLE);
NotificationFragment nf = new NotificationFragment();
Bundle bundlen = new Bundle();
bundlen.putString("firstname", Firstname);
bundlen.putString("lastname", Lastname);
bundlen.putString("imageurl", Image);
bundlen.putString("userid", UserID);
bundlen.putString("email", Email);
bundlen.putString("refer", ReferralCOde);
nf.setArguments(bundlen);
FragmentTransaction fragmentTransactionn = getSupportFragmentManager().beginTransaction();
fragmentTransactionn.replace(R.id.fragment_container, nf);
fragmentTransactionn.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransactionn.commit();
return true;
case R.id.navigation_profile:
ProfileFragment fragment1 = new ProfileFragment();
Bundle bundle = new Bundle();
bundle.putString("firstname", Firstname);
bundle.putString("lastname", Lastname);
bundle.putString("imageurl", Image);
bundle.putString("userid", UserID);
bundle.putString("email", Email);
bundle.putString("refer", ReferralCOde);
fragment1.setArguments(bundle);
FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.fragment_container, fragment1);
fragmentTransaction1.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
fragmentTransaction1.commit();
search_bar_home.setVisibility(View.INVISIBLE);
search_icon_home.setVisibility(View.INVISIBLE);
cart_icon_home.setVisibility(View.INVISIBLE);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_buyers);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
cart_icon_home = findViewById(R.id.cart_icon_home);
search_bar_home = findViewById(R.id.search_bar_home);
search_icon_home = findViewById(R.id.search_icon_home);
final HomeFragment fragment = new HomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
cart_icon_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeBuyersActivity.this, MyCartFragment.class);
startActivity(intent);
}
});
}
}
Use FrameLayout Instead of Scrollview for "fragment_container"
I did a tabbed-activity with for tabs. In the fourth tab I did a map, and I added a marker but the marker is not visible and I do not undertand why. I tried many solutions for my problem, but for now I have come to this situation.
This is my Java code:
public class tab_mappa extends SupportMapFragment implements OnMapReadyCallback {
private GoogleMap googleMap;
SupportMapFragment mSupportMapFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater, container, savedInstanceState);
View root = inflater.inflate(R.layout.tabmappa, null, false);
mSupportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.map, mSupportMapFragment).commit();
}
return root;
}
#Override
public void onMapReady(final GoogleMap googleMap) {
this.googleMap = googleMap;
this.googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
this.googleMap.getUiSettings().setZoomControlsEnabled(true);
this.googleMap.getUiSettings().setCompassEnabled(true);
this.googleMap.getUiSettings().setMyLocationButtonEnabled(true);
this.googleMap.getUiSettings().setZoomGesturesEnabled(true);
this.googleMap.getUiSettings().setRotateGesturesEnabled(true);
LatLng pos1 = new LatLng(44.783878,10.879663);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(pos1);
this.googleMap.addMarker(new MarkerOptions().position(pos1));
this.googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (googleMap == null) {
getMapAsync(this);
}
}
}
This is my xml code:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:gravity="center"
android:orientation="vertical"
tools:context="esame.progetto.xhondar.github.com.info.tab_mappa">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1.03"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map" />
</LinearLayout>
And this is my final result:
Do you have any ideas?
I solved the problem, this is the solution for those who need it:
Java code:
import android.support.v4.app.Fragment;
public class tab_mappa extends Fragment implements OnMapReadyCallback {
GoogleMap map;
SupportMapFragment mapFragment;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tabmappa, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return v;
}
#Override
public void onMapReady(GoogleMap googleMap){
map = googleMap;
this.map = googleMap;
this.map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
this.map.getUiSettings().setZoomControlsEnabled(true);
this.map.getUiSettings().setCompassEnabled(true);
this.map.getUiSettings().setMyLocationButtonEnabled(true);
this.map.getUiSettings().setZoomGesturesEnabled(true);
this.map.getUiSettings().setRotateGesturesEnabled(true);
LatLng pp = new LatLng(44.783878,10.879663);
map.addMarker(new MarkerOptions().position(pp).title("Carpi"));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(pp, 8));
}
}
Xml code:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="esame.progetto.xhondar.github.com.info.tab"/>
The error was located in xml code: is Fragment and not FrameLayout, this thing brought conflict within the code.
How about use marker without the builder? you wrote the code in onMapReady()
LatLng pos1 = new LatLng(44.783878,10.879663);
final LatLngBounds.Builder builder = new LatLngBounds.Builder();
builder.include(pos1);
this.googleMap.addMarker(new MarkerOptions().position(pos1));
this.googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
}
});
it change to
LatLng pos1 = new LatLng(44.783878,10.879663);
googleMap.addMarker(new MarkerOptions().position(pos1));
this.googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 100));
}
});
this one. I removed builder and this before googleMap.
The other day I asked, as fill from a cursor. I got on top of that focus all brands with the maximum zoom.
But now I have a problem and fill in the custom view, where there is title, description, and latitude and longitude.
It takes me head, I'm trying to look as filling sight, but each does so in a way. I am not able.
Here my code
info_windows_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#ffffff" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Esto es un titulo"
android:id="#+id/tv_title"
android:textStyle="bold"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="tv_descripcion"
android:id="#+id/tv_descripcion"
android:textSize="16dp" />
<TextView
android:id="#+id/tv_lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lat" />
<TextView
android:id="#+id/tv_lng"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lang" />
</LinearLayout>
CajerosMaps
public class CajerosMaps extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Cursor cursor;
MiCajeroOperacional mb;
LatLngBounds.Builder builder;
CameraUpdate cu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cajeros_maps);
mb = MiCajeroOperacional.getInstance(getApplicationContext());
// 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) {
cursor = mb.listar();
mMap = googleMap;
LatLng mark = null;
List<Marker> markersList = new ArrayList<Marker>();
int i = 0;
while (cursor.moveToNext()) {
double lat = cursor.getDouble(cursor.getColumnIndex("lat"));
double lng = cursor.getDouble(cursor.getColumnIndex("lng"));
mark = new LatLng(lat, lng);
Marker markCajero = mMap.addMarker(new MarkerOptions().position(mark).title("Sucursal NÂș" + i).snippet(cursor.getString(cursor.getColumnIndex("direccion"))));
// mMap.moveCamera(CameraUpdateFactory.newLatLng(mark), 15);
markersList.add(markCajero);
i++;
}
cursor.close();
builder = new LatLngBounds.Builder();
for (Marker m : markersList) {
builder.include(m.getPosition());
}
int padding = 50;
LatLngBounds bounds = builder.build();
cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
mMap.moveCamera(cu);
}
}
I am able to open the map fragment for the first time when I click on the Action bar icon, search for a location, add a marker at the location and add the location name to the list view on clicking the marker. But when I click on the action bar icon again to search for another place my app crashes. Please help, I have gone through other similar questions on So but nothing worked. Thanks in advance.
Main Activity
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
public class MainActivity extends ActionBarActivity implements GoogleMap.OnMarkerClickListener{
GoogleMap mMap;
private static final float DEFAULT_ZOOM = 14;
public static ArrayList<String> myPlaces = new ArrayList<String>();
public static String location;
public ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_addPlaces:
setContentView(R.layout.map_fragment);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
default:
return super.onOptionsItemSelected(item);
}
}
public boolean initMap(){
if(mMap==null){
SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return(mMap!=null);
}
private void gotoLocation(double lat, double lng, float zoom){
LatLng ll = new LatLng(lat,lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mMap.moveCamera(update);
}
public void geoLocate(View v) throws IOException {
// hideSoftKeyboard(v);
EditText et = (EditText) findViewById(R.id.editText1);
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
location = et.getText().toString();
if (location.length() == 0) {
Toast.makeText(this, "Please enter a valid location", Toast.LENGTH_LONG).show();
return;
}
Geocoder gc = new Geocoder(this);
List<Address> list = gc.getFromLocationName(location, 1);
Address add = list.get(0);
String locality = add.getLocality();
Toast.makeText(this, locality, Toast.LENGTH_LONG).show();
double lat = add.getLatitude();
double lng = add.getLongitude();
gotoLocation(lat, lng, DEFAULT_ZOOM);
MarkerOptions options = new MarkerOptions()
.title(location)
.position(new LatLng(lat, lng));
mMap.addMarker(options);
mMap.setOnMarkerClickListener(this);
}
public boolean onMarkerClick (Marker marker){
PlaceholderFragment list1 = new PlaceholderFragment();
myPlaces.add(location);
setContentView(R.layout.activity_main);
getSupportFragmentManager().beginTransaction()
.add(R.id.container,list1)
.commit();
return false;
}
public static class PlaceholderFragment extends Fragment {
ArrayAdapter<String> mPlacesAdapter;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ArrayAdapter mPlacesAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_places,
R.id.list_item_places_textview,
MainActivity.myPlaces);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listView_Places);
listView.setAdapter(mPlacesAdapter);
return rootView;
}
}
}
Map fragment layout
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="#dimen/abc_action_bar_subtitle_bottom_margin_material"
android:paddingBottom="#dimen/abc_action_bar_subtitle_bottom_margin_material">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_gravity="left|center_vertical"
android:text="Location:"
android:textSize="20sp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:layout_gravity="left|bottom"
android:ems="10">
<requestFocus/>
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:id="#+id/button1"
android:text="GO"
android:onClick="geoLocate"/>
</LinearLayout>
<fragment
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:value="#integer/google_play_services_version"
map:cameraTargetLat="17.422245"
map:cameraTargetLng="78.382000"
map:cameraZoom="10"/>
ListView 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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView_Places"
android:layout_gravity="left|center_horizontal" />
</FrameLayout>
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;
}