I'm new in android programming;
I have that small app with 3 pages (fragments), swiping between them using pageradapter and viewpager;
one of these pages contains checkbox [and other controls] and a map;
my problem is that the program is crashing on start.
Fragment_compass.java
package com.ibdiab.emadaldien;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Fragment_Compass extends Fragment {
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.activity_compass, container, false);
// Gets the MapView from the XML layout and creates it
mapView = (MapView) v.findViewById(R.id.eamap);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
map = mapView.getMap();
//map.getUiSettings().setMyLocationButtonEnabled(false);
//map.setMyLocationEnabled(true);
map.addMarker(new MarkerOptions().position(new LatLng(50.167003,19.383262)));
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
try {
MapsInitializer.initialize(this.getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
// Updates the location and zoom of the MapView
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
activity_compass.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/autolocate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="view live map" />
<fragment
android:id="#+id/eamap"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
MainScr.java
public class MainScr extends FragmentActivity {
private PagerAdapter el_pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlayout);
initialisePaging();
}
private void initialisePaging() {
// TODO Auto-generated method stub
List<Fragment> eafragments = new Vector<Fragment>();
eafragments.add(Fragment.instantiate(this, Fragment_PraysTable.class.getName()));
eafragments.add(Fragment.instantiate(this, Fragment_Main.class.getName()));
eafragments.add(Fragment.instantiate(this, Fragment_Compass.class.getName()));
el_pagerAdapter = new PagerAdapter(this.getSupportFragmentManager() , eafragments);
ViewPager pager = (ViewPager) findViewById(R.id.mainviewpager);
pager.setAdapter(el_pagerAdapter);
pager.setCurrentItem(1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_scr, menu);
return true;
}
}
Related
I have a problem integrating google map in fragment in android. I know how to do it in activity but fragment reference on this site are very old and not working in 2018. I don't have any error.below is fragment file. Any help will be highly appreciated. I have added API key and proper manifest file.
package com.example.narmail.truck30mint.Api.Fragments;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.narmail.truck30mint.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class ViewTrucksFragment extends Fragment {
TextView pageTitle;
MapView mMapView;
private GoogleMap googleMap;
public ViewTrucksFragment() {
// 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_view_trucks, container, false);
pageTitle = rootView.findViewById(R.id.view_trucks_title);
String load_id = getArguments().getString("load_id");
String load_from = getArguments().getString("load_from");
String load_to = getArguments().getString("load_to");
if (load_id != null && load_from != null && load_to != null) {
pageTitle.setText("Matching Trucks for "+load_from+" to "+load_to);
}
mMapView= rootView.findViewById(R.id.view_trucks_map);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(30.374219,76.782055);
googleMap.addMarker(new MarkerOptions().position(sydney).
title("Title").snippet("TitleName"));
// 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;
}
}
and below is my layout file
<?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:background="#color/colorWhite"
tools:context=".Api.Fragments.ViewTrucksFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/view_trucks_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:padding="10dp"
android:textColor="#color/colorPrimary"
android:textSize="15sp"
android:text="#string/hello_blank_fragment" />
<com.google.android.gms.maps.MapView
android:id="#+id/view_trucks_map"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.gms.maps.MapView>
</LinearLayout>
</FrameLayout>
Please follow below step to finish your task. Just need to create 3 files
(1) Create XML layout for map inside your fragment layout fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
(2) Create Fragment to load MAP MapFragment.Java
public class MapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
if(getActivity()!=null) {
SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
.findFragmentById(R.id.map);
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Do your stuff here
}
}
(3) Create Activity to load MAP fragment MapsActivity.java
public class MapsActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content,new MapFragment());
fragmentTransaction.commit();
}
}
For MAP key you need to follow same step you have done in your project. Hope this step will help you.
Inside Gradle please use below gradle
implementation 'com.google.android.gms:play-services-maps:15.0.1'
AndroidManifest.xml define below things.
<uses-permission android:name="android.permission.INTERNET"/>
Inside Application Tag.
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR MAP KEY" />
please help.
I am trying to display a google map in a scroll tab, but I am getting a blank google map.
Since I am using the scroll tab, I use android.support.v4.app.Fragment in the PagerAdapter class and the fragment class which should display the map.
The following is fragment class to display a google map
package ui;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bdushimi.bjhangout.R;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapTab extends Fragment implements OnMapReadyCallback {
public static View view;
private GoogleMap mGoogleMap;
private MapView mapView;
private FusedLocationProviderClient mFusedLocationProviderClient;
private SupportMapFragment mapFragment;
public MapTab() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_map, container, false);
return view;
}
#Override
public void onViewCreated(View v, #Nullable Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
mapView = (MapView) this.view.findViewById(R.id.map);
if (mapView != null) {
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(this.getActivity());
mGoogleMap = googleMap;
googleMap.addMarker(new MarkerOptions().position(new LatLng(40.689247, -74.044502))
.title("You're here"));
}
}
The following is the 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="ui.MapTab">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.google.android.gms.maps.MapView>
</RelativeLayout>
I would like to know where I am getting wrong or possibly another approach I should consider. Thanks
I have a google map app that is using a mapview in a fragment to display maps. This is working perfectly except that it doesn't display indoor maps.
I decided to create a stripped down version of my code to find the problem. It still exists :-(
In the documentation for indoor maps it says the following
SetIndoorEnabled
Sets whether indoor maps should be enabled. Currently, indoor maps can
only be shown on one map at a time and by default, this is the first map
added to your application. To enable indoor maps on another map, you
must first disable indoor maps on the original map. If you try to enable
indoor maps when it is enabled on another map, nothing will happen and
this will return false. When Indoor is not enabled for a map, all
methods related to indoor will return null, or false.
I can't see that I've enabled multiple maps but I'm wondering if somehow the use of a fragment confuses it.
Any help/advice would be greatly appeciated.
My MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
Fragment map_fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_2);
showTheMap();
}
public void showTheMap() {
map_fragment = new MapFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.map, map_fragment);
ft.commit();
}
}
The MapFrament.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
public class MapFragment extends Fragment {
private MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final FrameLayout parent = (FrameLayout) inflater.inflate(R.layout.fragment_map, container, false);
mapView = (MapView) parent.findViewById(R.id.mapfragment);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(-35.0176402, 138.5459909), 17);
googleMap.animateCamera(cameraUpdate);
}
}
);
mapView.onCreate(savedInstanceState);
return parent;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
activity_main_2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
</android.support.design.widget.AppBarLayout>
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
class="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</android.support.design.widget.CoordinatorLayout>
The fragment_map.xml
<FrameLayout 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/mapfragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
</FrameLayout>
If you move the code to MainActivity it works perfectly. See code below
MainActivity.Java
public class MainActivity extends AppCompatActivity {
MapView mapView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_1);
mapView = (MapView) findViewById(R.id.map);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(-35.0176402, 138.5459909), 17);
googleMap.animateCamera(cameraUpdate);
}
}
);
mapView.onCreate(savedInstanceState);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
The activity_main_1 xml for this is ....
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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:fitsSystemWindows="true"
tools:context="com.example.program.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
</android.support.design.widget.AppBarLayout>
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
</android.support.design.widget.CoordinatorLayout>
The following is a solution for my problem.
Declare myGoogleMap in the MainActivity
public static GoogleMap myGoogleMap = null;
In onMapReady add these lines as the first action to do
if (MainActivity.myGoogleMap != null) {
MainActivity.myGoogleMap.setIndoorEnabled(false);
googleMap.setIndoorEnabled(true);
MainActivity.myGoogleMap = googleMap;
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(-35.0176402, 138.5459909), 17);
MainActivity.myGoogleMap.animateCamera(cameraUpdate);
}
It seems as though getMapAsync is called twice and therefore 2 google maps are created, the second one is being displayed.
As indoor maps only appear on the first map you have to setIndoorEnabled to false for the first map and then setIndoorEnabled to true for the second one.
This seems dodgy to me.
Not sure if its a bug or my lack of understanding.
I'm trying to show list view on the bottom side of the google maps activity (only when the button is clicked), but it doesn't work, just showing app stop message. How can I show listview on google maps activity?
Here is my java and xml code
package com.example.dong_gyo.project;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapFind extends ActionBarActivity {
GoogleMap mMap; // Might be null if Google Play services APK is not available.
LocationManager lm;
String locationProvider;
Location location;
Button mapListbut;
ListView mapList;
ArrayList list;
ButtonListener listener;
ArrayAdapter mapadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_find);
setUpMapIfNeeded();
mapListbut = (Button)findViewById(R.id.showMapList);
mapadapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
mapList = (ListView)findViewById(R.id.mapList);
mapList.setAdapter(mapadapter);
mapList.setVisibility(View.INVISIBLE);
mapListbut.setOnClickListener(listener);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private 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) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationProvider = lm.getBestProvider(new Criteria(), true);
location = lm.getLastKnownLocation(locationProvider);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
final LatLng LOC = new LatLng(latitude, longitude);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(LOC, 16));
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap(LOC);
}
}
}
private void setUpMap(LatLng LOC) {
mMap.addMarker(new MarkerOptions().position(LOC));
}
class ButtonListener implements View.OnClickListener {
#Override
public void onClick(View v) { // 목록 토글 버튼 리스너
// TODO Auto-generated method stub
switch (v.getId()) { //
case R.id.showMapList:
if (!mapList.isShown()) {
mapList.setVisibility(View.VISIBLE);
mapadapter.notifyDataSetChanged();
mapListbut.setSelected(true);
} else {
mapList.setVisibility(View.INVISIBLE);
mapListbut.setSelected(false);
}
break;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
startActivity(new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
XML :
<?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:weightSum="1">
<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"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
<Button
android:id="#+id/showMapList"
android:text = "목록보기"
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"/>
<ListView
android:id="#+id/mapList"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#eeeeee" >
</ListView>
</RelativeLayout>
I ran your code and it said it gets a null pointer. Looking at your code, location = lm.getLastKnownLocation(locationProvider); makes location to be null. So, instead of the getBestProvider, try:
location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
I tried it and the maps load.
I have the following situation:
I have a simple app with 3 tabs using the android actionbar
The first tab (not the tab but the GUI below) should contain a map
I'm not really sure how the setup with Activities, Fragments (Java) and Fragments (xml) should look like. The map examples you get from the google playservices all just use an Activity.
When working with the actionbar (tab navigation), fragments should be used. Is that right?
So i have the following components implemented which do not work propely.
package ch.bfh.femtho.skiguide;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
public static Context appContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
// Set up the action bar to show tabs.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// For each of the sections in the app, add a tab to the action bar.
ActionBar.Tab mapTab = actionBar.newTab().setText(R.string.tab_title_map);
ActionBar.Tab poiListeTab = actionBar.newTab().setText(R.string.tab_title_poiliste);
ActionBar.Tab meetingpointTab = actionBar.newTab().setText(R.string.tab_title_meetingpoint);
mapTab.setTabListener(new TabListener<MyMapFragment>(
this, "map", MyMapFragment.class));
poiListeTab.setTabListener(new TabListener<PoiListeFragment>(
this, "poiliste", PoiListeFragment.class));
meetingpointTab.setTabListener(new TabListener<MeetingpointFragment>(
this, "meetingpoint", MeetingpointFragment.class));
actionBar.addTab(mapTab);
actionBar.addTab(poiListeTab);
actionBar.addTab(meetingpointTab);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
}
TabListener:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
public class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}
Fragment:
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MyMapFragment extends Fragment {
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private UiSettings mUiSettings;
int mCurCheckPosition = 0;
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.map_fragment, container, false);
try {
MapsInitializer.initialize(getActivity());
} catch (GooglePlayServicesNotAvailableException e) {
// TODO handle this situation
}
mMapView = (MapView) inflatedView.findViewById(R.id.map);
mMapView.onCreate(mBundle);
setUpMapIfNeeded(inflatedView);
return inflatedView;
}
#Override
public void onDestroyView() {
super.onDestroyView();
MyMapFragment f = (MyMapFragment) getFragmentManager().findFragmentById(R.id.map);
if (f != null) {
getFragmentManager().beginTransaction().remove(f).commit();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBundle = savedInstanceState;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
mMap.setOnMapClickListener(this);
mMap.setOnMapLongClickListener(this);
mMap.setMyLocationEnabled(true);
mUiSettings = mMap.getUiSettings();
mUiSettings.setMyLocationButtonEnabled(true);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
}
Fragment (xml):
<?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"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
</RelativeLayout>
The problem appears when navigating to another tab and then come back to the map. Added markers disappear, camera position is lost, ...
can someone help me with this?
thanks
I guess what you should do is override the onSaveInstanceState method in the mapFragment and to save all your desired data in the savedInstantState object (including your location and markers location you created and not only the int you are saving), and in the onCreate method you should reuse all this data.
more information on saving states can be found here:
http://www.eigo.co.uk/labs/managing-state-in-an-android-activity/