嗨,我正在玩片段和谷歌地图,由于某种原因我的地图不会显示,我正在使用带有标签的片段,我想以编程方式将地图添加到其中一个标签中。
请问我做错了什么:
主要活动
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener, OnClickListener {
/**
* The serialization (saved instance state) Bundle key representing the
* current tab position.
*/
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
private SlidingMenu menu;
private double latitude;
private double longitude;
private static int lng = 0;
private static int lat = 0;
String display = "";
ProgressDialog pDialog;
ProgressDialog pDialog2;
GooglePlaces googlePlaces;
Foursquare foursquare;
PlacesList nearPlaces;
ArrayList<FsqVenue> nearbylist;
String types;
String Message;
Foursquare fsq;
Boolean isInternetPresent = false;
ConnectionDetector cd;
GPSTracker gps;
AlertDialogManager alert = new AlertDialogManager();
LayoutInflater inflater;
RelativeLayout rlayout;
ListView listview;
Location location;
TextView myTitleText;
ImageView myTitleImage;
// static Context context;
public static Context appContext;
String catId = null;
int minlat = Integer.MAX_VALUE;
int minlong = Integer.MAX_VALUE;
int maxlat = Integer.MIN_VALUE;
int maxlong = Integer.MIN_VALUE;
public static String KEY_REFRENCE = "refrence";
public static String KEY_NAME = "name";
public static String KEY_VICINITY = "vivinity";
public static String KEY_CATEGORY = "category";
Foursquare NearbyList = new Foursquare();
public static ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
static List<Float> myLat = new ArrayList<Float>();
static List<Float> myLng = new ArrayList<Float>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
/*getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
R.layout.window_title_single_item);*/
setContentView(R.layout.activity_main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, new SampleListFragment())
.commit();
// 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.addTab(actionBar.newTab().setText("MAP")
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("List")
.setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("AR")
.setTabListener(this));
menu = new SlidingMenu(this);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.behind_main);
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = cd.isConnectingToInternet();
if (!isInternetPresent) {
// Internet Connection is not present
alert.showAlertDialog(MainActivity.this,
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
return;
}
// creating GPS Class object
gps = new GPSTracker(this);
// check if GPS location can get
if (gps.canGetLocation()) {
Log.d("Your Location", "latitude:" + gps.getLatitude()
+ ", longitude: " + gps.getLongitude());
} else {
// Can't get user's current location
alert.showAlertDialog(MainActivity.this, "GPS Status",
"Couldn't get location information. Please enable GPS",
false);
// stop executing code by return
return;
}
latitude = gps.getLatitude();
longitude = gps.getLongitude();
lng = (int) (longitude * 1E6);
lat = (int) (latitude * 1E6);
location = gps.getLocation();
Button pointOfIntrest = (Button) findViewById(R.id.point_of_intrest);
Button cloth = (Button) findViewById(R.id.clothing);
Button sports = (Button) findViewById(R.id.atletics);
Button nightlife = (Button) findViewById(R.id.nightlifespot);
Button spirt = (Button) findViewById(R.id.spritual);
Button medic = (Button) findViewById(R.id.medic3);
Button university = (Button) findViewById(R.id.university);
Button hotel = (Button) findViewById(R.id.lodging);
Button atm = (Button) findViewById(R.id.banks);
Button eat = (Button) findViewById(R.id.food);
pointOfIntrest.setOnClickListener(this);
cloth.setOnClickListener(this);
sports.setOnClickListener(this);
nightlife.setOnClickListener(this);
spirt.setOnClickListener(this);
medic.setOnClickListener(this);
university.setOnClickListener(this);
hotel.setOnClickListener(this);
atm.setOnClickListener(this);
eat.setOnClickListener(this);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current tab position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current tab position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
.getSelectedNavigationIndex());
}
@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
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, show the tab contents in the
// container view.
if (tab.getPosition() == 0) {
Fragment mMapFragment = new MapDisplayFragment();
Bundle arguments = new Bundle();
arguments.putInt(MapDisplayFragment.ARG_SECTION_NUMBER,
89);
((Fragment) mMapFragment).setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, mMapFragment).commit();
}
if (tab.getPosition() == 1) {
Fragment mListFragment = new ListDispalyFragment();
Bundle arguments = new Bundle();
arguments.putInt(MapDisplayFragment.ARG_SECTION_NUMBER,
49);
mListFragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, mListFragment).commit();
}
if (tab.getPosition() == 2) {
Fragment mMapFragment = new MapDisplayFragment();
Bundle arguments = new Bundle();
arguments.putInt(MapDisplayFragment.ARG_SECTION_NUMBER,
59);
mMapFragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, mMapFragment).commit();
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
//fragmentTransaction.remove(fragment);
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.point_of_intrest:
catId = "4d4b7104d754a06370d81259";
if (myTitleText != null) {
myTitleText.setText("Arts & Entertainment");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.clothing:
types = "zoo|museum|amusement_park|city_hall|casino|aquarium|shopping_mall|university|spa";
catId = "4d4b7105d754a06378d81259";
if (myTitleText != null) {
myTitleText.setText("Clothing Stores");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.atletics:
types = "zoo|museum|amusement_park|city_hall|casino|aquarium|shopping_mall|university|spa";
catId = "4d4b7105d754a06377d81259";
if (myTitleText != null) {
myTitleText.setText("Recreation& Outdoors");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.nightlifespot:
catId = "4d4b7105d754a06376d81259";
if (myTitleText != null) {
myTitleText.setText("Nightlife Spots");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.spritual:
catId = "4bf58dd8d48988d131941735";
if (myTitleText != null) {
myTitleText.setText("Spiritual Centers");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.medic3:
catId = "4bf58dd8d48988d104941735";
if (myTitleText != null) {
myTitleText.setText("Medical Centers");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.university:
catId = "4d4b7105d754a06372d81259";
if (myTitleText != null) {
myTitleText.setText("College & University");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.lodging:
catId = "4bf58dd8d48988d1fa931735";
if (myTitleText != null) {
myTitleText.setText("Hotels");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.banks:
catId = "4bf58dd8d48988d10a951735";
if (myTitleText != null) {
myTitleText.setText("Banks & ATMs");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
case R.id.food:
catId = "4d4b7105d754a06374d81259";
if (myTitleText != null) {
myTitleText.setText("Food");
}
if (myTitleImage != null) {
myTitleImage.setVisibility(ImageView.INVISIBLE);
}
menu.toggle();
new LoadPlaces().execute();
break;
}
}
private void validate(int size) {
// TODO Auto-generated method stub
if (size != 0) {
for (FsqVenue item : nearbylist) {
HashMap<String, String> map = new HashMap<String, String>();
// System.out.print("match");
map.put(KEY_REFRENCE, item.id);
map.put(KEY_NAME, item.name);
map.put(KEY_CATEGORY, item.type);
myLat.add((float) item.location.getLatitude());
myLng.add((float) item.location.getLongitude());
Log.d("categories-match", String.valueOf(item.verified));
placesListItems.add(map);
}
}
}
class LoadPlaces extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(Html
.fromHtml("<b>Search</b><br/>Loading Places......"));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
// googlePlaces = new GooglePlaces();
foursquare = new Foursquare();
try {
// double radius = 10000;
// NearbyList = foursquare.getNearby(latitude, longitude);
// NearbyList.getNearby(latitude, longitude);
nearbylist = foursquare.getNearby(latitude, longitude, catId);
// int size = nearbylist.size();
// System.out.print(size);
// nearPlaces =
// googlePlaces.search((double)gps.getLatitude(),(double)gps.getLongitude(),
// radius, types);
} catch (Exception e) {
e.printStackTrace();
System.out.println("error" + e);
}
try {
validate(nearbylist.size());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
/*mapFrag = new MapDispalyFragment(location, placesListItems, myLat,
myLng);
mAdapter = new MyAdpater(getSupportFragmentManager());
mPager.setAdapter(mAdapter);
*/
runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
}
我的地图片段活动公共类 MapDisplayFragment 扩展 SupportMapFragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private static final String MAP_FRAGMENT_TAG = "map";
private GoogleMap mMap;
private SupportMapFragment mMapFragment;
/*
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapFragment == null) {
// To programmatically add the map, we first create a SupportMapFragment.
mMapFragment = SupportMapFragment.newInstance();
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.add(android.R.id.content, mMapFragment, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
}
// We can't be guaranteed that the map is available because Google Play services might
// not be available.
setUpMapIfNeeded();
}
*/
@Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
setUpMapIfNeeded();
Log.d("OnResume View" , "Sucess");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
/*TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));*/
mMapFragment = (SupportMapFragment) getFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapFragment == null) {
// To programmatically add the map, we first create a SupportMapFragment.
mMapFragment = SupportMapFragment.newInstance();
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction = getFragmentManager()
.beginTransaction();
fragmentTransaction.add(android.R.id.content, mMapFragment, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
mMapFragment.onCreate(savedInstanceState);
Log.d("OnCreate View" , "Sucess");
}
// We can't be guaranteed that the map is available because Google Play services might
// not be available.
setUpMapIfNeeded();
return null;
}
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 = mMapFragment.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
我的日志消息
01-21 21:12:38.639: E/AndroidRuntime(8924): FATAL EXCEPTION: main
01-21 21:12:38.639: E/AndroidRuntime(8924): java.lang.RuntimeException: Unable to resume activity {com.example.reddotiantired/com.example.reddotiantired.MainActivity}: java.lang.NullPointerException
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2464)
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2492)
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1997)
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.app.ActivityThread.access$600(ActivityThread.java:127)
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1158)
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.os.Handler.dispatchMessage(Handler.java:99)
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.os.Looper.loop(Looper.java:137)
01-21 21:12:38.639: E/AndroidRuntime(8924): at android.app.ActivityThread.main(ActivityThread.java:4441)
01-21 21:12:38.639: E/AndroidRuntime(8924): at java.lang.reflect.Method.invokeNative(Native Method)
01-21 21:12:38.639: E/AndroidRuntime(8924): at java.lang.reflect.Method.invoke(Method.java:511)
01-21 21:12:38.639: E/AndroidRuntime(8924): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)