I'm using google maps with navigation drawer. Everything works fine on first load but when i switch the item, the application crashes. don't know why...Here is my log cat.
02-22 15:00:19.847: E/AndroidRuntime(30597): FATAL EXCEPTION: main
02-22 15:00:19.847: E/AndroidRuntime(30597): java.lang.NullPointerException
02-22 15:00:19.847: E/AndroidRuntime(30597): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:651)
02-22 15:00:19.847: E/AndroidRuntime(30597): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
02-22 15:00:19.847: E/AndroidRuntime(30597): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
02-22 15:00:19.847: E/AndroidRuntime(30597): at android.os.Handler.handleCallback(Handler.java:725)
02-22 15:00:19.847: E/AndroidRuntime(30597): at android.os.Handler.dispatchMessage(Handler.java:92)
02-22 15:00:19.847: E/AndroidRuntime(30597): at android.os.Looper.loop(Looper.java:153)
02-22 15:00:19.847: E/AndroidRuntime(30597): at android.app.ActivityThread.main(ActivityThread.java:5299)
02-22 15:00:19.847: E/AndroidRuntime(30597): at java.lang.reflect.Method.invokeNative(Native Method)
02-22 15:00:19.847: E/AndroidRuntime(30597): at java.lang.reflect.Method.invoke(Method.java:511)
02-22 15:00:19.847: E/AndroidRuntime(30597): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-22 15:00:19.847: E/AndroidRuntime(30597): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-22 15:00:19.847: E/AndroidRuntime(30597): at dalvik.system.NativeStart.main(Native Method)
MapFragment :
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.gol.apps.pickmedriver.classes.HttpClassHandler;
import com.gol.apps.pickmedriver.classes.Session;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends Fragment implements LocationListener {
private GoogleMap googleMap;
private Location location;
private LocationManager locationManager;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 5 meters
private static final long MIN_TIME_BW_UPDATES = 2000 * 60 * 1; // 2 minute
private double latitude;
private double longitude;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private SharedPreferences sp;
boolean canGetLocation = false;
private View view;
private LatLng center;
private HttpClassHandler handler;
private Session session;
private JSONObject jObj;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null) {
return null;
}
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater
.inflate(R.layout.activity_mapview, container, false);
setUpMapIfNeeded();
} catch (InflateException e) {
// Log.wtf("S*****", e.getMessage());
}
initialize(view);
return view;
}
public void setUpMapIfNeeded() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getActivity()
.getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
fragment = null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
isGPSAvailable();
location = getLocation();
// Creating a LatLng object for the current location
center = new LatLng(location.getLatitude(), location.getLongitude());
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(center));
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
mp.icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
googleMap.addMarker(mp);
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
updateCurrentLocationInDatabase(location);
}
private void initialize(View view) {
handler = new HttpClassHandler();
session = new Session(getActivity());
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
/** this criteria will settle for less accuracy, high power, and cost */
public static Criteria createCoarseCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
/** this criteria needs high accuracy, high power, and cost */
public static Criteria createFineCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
public Location getLocation() {
try {
getActivity();
locationManager = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
Toast.makeText(getActivity(), "No Provider is enabled",
Toast.LENGTH_LONG).show();
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
LocationProvider high = locationManager
.getProvider(locationManager.getBestProvider(
createFineCriteria(), isNetworkEnabled));
locationManager.requestLocationUpdates(high.getName(),
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.e("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
LocationProvider high = locationManager
.getProvider(locationManager.getBestProvider(
createFineCriteria(), isGPSEnabled));
locationManager.requestLocationUpdates(high.getName(),
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void isGPSAvailable() {
LocationManager manager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
boolean statusOfGPS = manager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!statusOfGPS) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
getActivity());
alertDialogBuilder.setTitle("No GPS");
alertDialogBuilder
.setMessage(
"Your GPS does not seem to be active.Please check your Settings.")
.setIcon(R.drawable.bullet_error)
.setCancelable(false)
.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
@Override
public void onLocationChanged(Location arg0) {
googleMap.clear();
// Getting latitude of the current location
latitude = location.getLatitude();
// Getting longitude of the current location
longitude = location.getLongitude();
// Creating a LatLng object for the current location
center = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(center));
MarkerOptions mp = new MarkerOptions();
mp.position(new LatLng(location.getLatitude(), location.getLongitude()));
mp.title("my position");
googleMap.addMarker(mp);
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(16));
updateCurrentLocationInDatabase(location);
}
// Updating current location in the database
public void updateCurrentLocationInDatabase(Location loc) {
if (location != null) {
jObj = handler.insertLocation(Double.toString(loc.getLatitude()),
Double.toString(loc.getLongitude()), session.getUserId());
try {
String msg = jObj.getString("success").toString();
if (msg.equals("1")) {
// Toast.makeText(getActivity(),
// jObj.getString("msg").toString(),
// Toast.LENGTH_LONG).show();
} else if (msg.equals("0")) {
Toast.makeText(getActivity(), jObj.getString("msg"),
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onProviderDisabled(String arg0) {
Toast.makeText(getActivity(), "Providers Disabled!", Toast.LENGTH_LONG)
.show();
}
@Override
public void onProviderEnabled(String arg0) {
Toast.makeText(getActivity(), "Providers Enabled!", Toast.LENGTH_LONG)
.show();
}
@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
NavigationDrawer:
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.text.SpannableString;
import android.text.util.Linkify;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.gol.apps.pickmedriver.adapters.NavDrawerListAdapter;
import com.gol.apps.pickmedriver.classes.NavDrawerItem;
import com.gol.apps.pickmedriver.classes.Session;
public class NavigationDrawerActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ListView mDrawerList;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private Fragment content;
private Session session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer);
strickMode();
initialize();
clicklistners();
if (savedInstanceState == null) {
selectItem(0);
}
}
@SuppressLint("NewApi")
private void initialize() {
session = new Session(NavigationDrawerActivity.this);
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
View headerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE))
.inflate(R.layout.nav_drawer_list_header, null, false);
mDrawerList.addHeaderView(headerView);
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(4, -1)));
// Recycle the typed array
navMenuIcons.recycle();
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setItemChecked(0, true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.navigation_drawer, R.string.app_name,
R.string.app_name) {
/** Called when a drawer has settled in a completely closed state. */
@SuppressLint("NewApi")
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void clicklistners() {
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (position) {
case 0:
content = new TabsMainActivity();
ft.replace(R.id.content_frame, content).commit();
break;
case 1:
content = new BookingTabsActivity();
ft.replace(R.id.content_frame, content).commit();
break;
case 2:
content = new MapFragment();
ft.replace(R.id.content_frame, content).commit();
break;
case 3:
content = new UserLocationHistoryActivity();
ft.replace(R.id.content_frame, content).commit();
break;
case 4:
content = new MapFragment();
ft.replace(R.id.content_frame, content).commit();
break;
case 5:
shareIt();
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
public void onDestroy() {
super.onDestroy();
Log.d("DEBUG", "In Method: onDestroy()");
}
@Override
public void onResume() {
super.onResume();
}
private void shareIt() {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Hey! I start using PickMeDriver";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"PickMeDriver");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share PickMeDriver"));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(
com.actionbarsherlock.view.MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
switch (item.getItemId()) {
case R.id.about:
final SpannableString s = new SpannableString(
NavigationDrawerActivity.this
.getText(R.string.dialogue_message));
Linkify.addLinks(s, Linkify.WEB_URLS);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
NavigationDrawerActivity.this);
alertDialogBuilder.setTitle("About");
alertDialogBuilder
.setMessage(s)
.setCancelable(false)
.setNegativeButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return true;
case R.id.sign_out:
session.distroySession();
Intent i = new Intent(NavigationDrawerActivity.this,
MainActivity.class);
startActivity(i);
finish();
return true;
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList))
mDrawerLayout.closeDrawer(mDrawerList);
else {
mDrawerLayout.openDrawer(mDrawerList);
mDrawerLayout.openDrawer(Gravity.LEFT);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
private void strickMode() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}