gpt4 book ai didi

android - 在 Fragment 中加载 map

转载 作者:行者123 更新时间:2023-11-30 02:05:09 29 4
gpt4 key购买 nike

我正在开发一个应用程序,在滑动时有 2 个选项卡,每个选项卡都加载其 fragment 。第一个是 ListFragment(没关系),第二个应该加载 map ,但是当我尝试将 Google Map 插入此 fragment 时,它使应用程序崩溃并显示错误:

06-11 18:11:52.973  32676-32676/br.com.toyansk.swipeabletabs E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: br.com.toyansk.swipeabletabs, PID: 32676
java.lang.NullPointerException
at br.com.toyansk.swipeabletabs.MapaFragment$HttpGetTask.onPostExecute(MapaFragment.java:100)
at br.com.toyansk.swipeabletabs.MapaFragment$HttpGetTask.onPostExecute(MapaFragment.java:69)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
06-11 18:11:52.980 1037-3188/? W/ActivityManager﹕ Force finishing activity br.com.toyansk.swipeabletabs/.MainActivity

MainActivity.java 是:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {

private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
List<Fragment> mFragments;

// Tab titles
private String[] tabs = { "Lista", "Mapa" };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), mFragments);
//mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

mFragments = new ArrayList<Fragment>();
mFragments.add(new List_Fragment());

viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);


final int[] ICON = new int[] {
R.drawable.ic1,
R.drawable.ic2
};
// Adding Tabs
for (int i=0; i < tabs.length; i++) {
actionBar.addTab(actionBar.newTab()
.setIcon(getResources().getDrawable(ICON[i]))
.setTabListener(this));
}

/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

@Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}

@Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}

@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}

加载 map 的MapaFragment.java,它还有使用JSON数据在 map 上插入标记的功能,如下所示:

public class MapaFragment extends Fragment {

Context mContext;
private GoogleMap mMap;
private Location location;

private final static String URL = "api that returns maps data in JSON";
public static final String TAG = "MapaFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_mapa, container, false);

new HttpGetTask().execute(URL);

return rootView;
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}

private class HttpGetTask extends AsyncTask<String, Void, List<PDVRec>> {

AndroidHttpClient mClient = AndroidHttpClient.newInstance("");

@Override
protected List<PDVRec> doInBackground(String... params) {

HttpGet request = new HttpGet(params[0]);
JSONResponseHandler responseHandler = new JSONResponseHandler();

try {

// Get data in JSON format

return mClient.execute(request, responseHandler);

} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException");
} catch (IOException e) {
Log.i(TAG, "IOException");
}

return null;

}

@Override
protected void onPostExecute(List<PDVRec> result) {

// Get Map Object
mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map)).getMap();


if (null != mMap) {
// Add a marker for every earthquake
for (PDVRec rec : result) {
// Add a new marker for this earthquake
mMap.addMarker(new MarkerOptions()
// Set the Marker's position
.position(new LatLng(rec.getLat(), rec.getLng()))
// Set the title of the Marker's information window
.title(String.valueOf(rec.getNome_PDV()))
// Set the icon for the Marker
.icon(BitmapDescriptorFactory.fromResource(R.drawable.currentlocation_icon)));

}

LocationManager locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);
Criteria criteria = new Criteria();

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 17));

CameraPosition cameraPosition = new CameraPosition.Builder()
// Sets the center of the map to location user
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(17) // Sets the zoom
//.bearing(90) // Sets the orientation of the camera to east
//.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

}

mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);

}

if (null != mClient)
mClient.close();
}
}
}

map 的布局 (fragment_mapa.xml) 是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:orientation="vertical"
android:id="@+id/container">
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>

有什么问题吗?提前致谢!

最佳答案

基于帖子How to put Google Maps V2 on a Fragment Using ViewPager (参见 Brandon Yang 的回答),我使用 MapView 更改了 MapaFragment.java 代码,并且成功了。像这样:

public class MapaFragment extends Fragment {

Context mContext;
private GoogleMap mMap;
MapView mMapView;
private Location location;

private final static String URL = "api que retorna JSON";

public static final String TAG = "MapaFragment";

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.fragment_mapa, container, false);

mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);

mMapView.onResume();// needed to get the map to display immediately

try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}

mMap = mMapView.getMap();

new HttpGetTask().execute(URL);

return rootView;
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}

@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}

@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}

@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}

@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}

private class HttpGetTask extends AsyncTask<String, Void, List<PDVRec>> {

AndroidHttpClient mClient = AndroidHttpClient.newInstance("");

@Override
protected List<PDVRec> doInBackground(String... params) {

HttpGet request = new HttpGet(params[0]);
JSONResponseHandler responseHandler = new JSONResponseHandler();

try {

// Get data in JSON format
// Parse data into a list

return mClient.execute(request, responseHandler);

} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException");
} catch (IOException e) {
Log.i(TAG, "IOException");
}

return null;
}

@Override
protected void onPostExecute(List<PDVRec> result) {

if (null != mMap) {
for (PDVRec rec : result) {
mMap.addMarker(new MarkerOptions()
// Set the Marker's position
.position(new LatLng(rec.getLat(), rec.getLng()))
// Set the title of the Marker's information window
.title(String.valueOf(rec.getNome_PDV()))
// Set the icon for the Marker
.icon(BitmapDescriptorFactory.fromResource(R.drawable.currentlocation_icon)));

}

LocationManager locationManager = (LocationManager) mContext.getSystemService(mContext.LOCATION_SERVICE);
Criteria criteria = new Criteria();

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 17));

CameraPosition cameraPosition = new CameraPosition.Builder()
// Sets the center of the map to location user
.target(new LatLng(location.getLatitude(), location.getLongitude()))
.zoom(17) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

}

mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);

}

if (null != mClient)
mClient.close();
}

}
}

还有 fragment_mapa.xml:

<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

也许需要更好地组织代码,但这样 map 就可以完美地加载到 Fragment 中。

关于android - 在 Fragment 中加载 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30792481/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com