这是我的Java代码。问题是每当我从后台返回我的应用程序时,应用程序崩溃都会给出下面的堆栈跟踪中显示的错误(无法实例化framgent)。
MainActivity.java
public class MainActivity extends BaseActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
public static final String KEY_CURRENT_OPTION = "currentOption";
public static final String KEY_SELECT_OPTION = "selectOption";
ProgressDialog dialog = null;
View drawerView;
//ImageView updown;
DrawerLayout mDrawerLayout;
ListView optionsListView;
ActionBarDrawerToggle mDrawerToggle;
private int currentOption = -1;
private boolean isRegistered = false;
BookACabFragment bookNowFragment;
BookACabFragment preBookFragment;
BookingsListFragment bookingsListFragment;
AccountFragment accountFragment;
CouponsFragment couponsFragment;
FavouriteAddressFragment favAddressFragment;
private FavDriversFragment favDriversFragment;
private TypedArray navMenuIcons;
public static SmoothProgressBar mGoogleNow;
//LocationReceiver receiver;
private NavDrawerListAdapter adapterrr;
static int saveInstance = 0;
private ArrayList<NavDrawerItem> navDrawerItems;
String[] optionTitles;
SharedPreferences prefs;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Log.d(TAG, "before content view");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_main);
// Log.d(TAG, "after content view");
ActionBar actionBar = getActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
// actionBar.setBackgroundDrawable;
actionBar.setHomeButtonEnabled(true);
actionBar.setTitle(Html.fromHtml("<font color='#000000'></font>"));
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout_main);
optionsListView = (ListView) findViewById(R.id.listview_options_drawer);
mGoogleNow = (SmoothProgressBar) findViewById(R.id.google_now);
drawerView = findViewById(R.id.left_drawer);
optionsListView.setAdapter(new MainDrawerListAdapter(this));
optionsListView.setOnItemClickListener(new DrawerItemClickListener());
optionTitles = getResources().getStringArray(R.array.main_drawer_options);
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
navDrawerItems = new ArrayList<NavDrawerItem>();
navDrawerItems.add(new NavDrawerItem(optionTitles[0], navMenuIcons.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(optionTitles[1], navMenuIcons.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(optionTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(optionTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(optionTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(optionTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// navDrawerItems.add(new NavDrawerItem(optionTitles[6], navMenuIcons.getResourceId(6, -1), true, "50+"));
navMenuIcons.recycle();
adapterrr = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
editor = prefs.edit();
optionsListView.setAdapter(adapterrr);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.navopener, R.string.app_name, R.string.app_name) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey(KEY_CURRENT_OPTION)) {
currentOption = extras.getInt(KEY_CURRENT_OPTION);
}
if (savedInstanceState != null) {
currentOption = savedInstanceState.getInt(KEY_CURRENT_OPTION);
}
selectDrawerItem(currentOption);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(KEY_CURRENT_OPTION, currentOption);
super.onSaveInstanceState(outState);
}
@Override
public void onClick(View v) {
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(drawerView)) {
mDrawerLayout.closeDrawer(drawerView);
} else {
mDrawerLayout.openDrawer(drawerView);
}
break;
}
return super.onOptionsItemSelected(item);
}
public void GotoTab(int i) {
if (bookingsListFragment == null)
bookingsListFragment = BookingsListFragment.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, BookingsListFragment.newInstance());
ft.commit();
}
/* @Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
//setTitle("REPORT AN ISSUE");
setTitle("Booking Detail" );
ActionBar actionbar = getActionBar();
//actionbar.setIcon(R.drawable.icon);
actionbar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff00000")));
actionbar.setDisplayHomeAsUpEnabled(true);
MenuInflater menuinflater = getMenuInflater();
menuinflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}*/
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectDrawerItem(position);
mDrawerLayout.closeDrawer(drawerView);
}
}
private void selectDrawerItem(int position) {
if (position == -1) {
position = 0;
}
setTitle(optionTitles[position]);
currentOption = position;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (position) {
case 0:
saveInstance = 1;
Log.e(TAG, "selecting the map fragment");
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
break;
// case 1:
//
// ft.replace(R.id.content_frame, BookACabFragment.newInstance(false));
// ft.commit();
// break;
case 1:
saveInstance = 2;
if (bookingsListFragment == null)
bookingsListFragment = BookingsListFragment.newInstance();
ft.replace(R.id.content_frame, BookingsListFragment.newInstance());
ft.commit();
break;
case 2:
saveInstance = 3;
if (accountFragment == null) {
accountFragment = AccountFragment.newInstance();
}
ft.replace(R.id.content_frame, accountFragment);
ft.commit();
break;
case 3:
saveInstance = 4;
if (favAddressFragment == null) {
favAddressFragment = favAddressFragment.newInstance();
}
ft.replace(R.id.content_frame, favAddressFragment);
ft.commit();
break;
case 4:
saveInstance = 5;
if (couponsFragment == null) {
couponsFragment = CouponsFragment.newInstance();
}
ft.replace(R.id.content_frame, couponsFragment);
ft.commit();
break;
case 5:
saveInstance = 6;
logout();
break;
}
}
/*
@Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(), "In resume "+saveInstance, Toast.LENGTH_SHORT).show();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(saveInstance==0){
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
}else if(saveInstance==1){
Log.e(TAG, "selecting the map fragment");
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
saveInstance=-1;
}
else if(saveInstance==2){
if(bookingsListFragment == null)
bookingsListFragment = BookingsListFragment.newInstance();
ft.replace(R.id.content_frame, BookingsListFragment.newInstance());
ft.commit();
saveInstance=-1;
}else if(saveInstance==3){
if(accountFragment == null) {
accountFragment = AccountFragment.newInstance();
}
ft.replace(R.id.content_frame, accountFragment);
ft.commit();
saveInstance=-1;
}else if(saveInstance==4){
if (favAddressFragment == null) {
favAddressFragment = favAddressFragment.newInstance();
}
ft.replace(R.id.content_frame, favAddressFragment);
ft.commit();
saveInstance=-1;
}else if(saveInstance==5){
if (couponsFragment == null) {
couponsFragment = CouponsFragment.newInstance();
}
ft.replace(R.id.content_frame, couponsFragment);
ft.commit();
saveInstance=-1;
}
else if(saveInstance==6){
logout();
saveInstance=-1;
}
}
/**4444
* Broadcast receiver for changing the fragment
*/
class FragmentChangeRequestReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(KEY_SELECT_OPTION)) {
selectDrawerItem(extras.getInt(KEY_SELECT_OPTION));
}
}
}
private void logout() {
final Token token = IoUtils.getTokenFromPrefs(this);
if (token != null) {
String regId = GcmUtils.getRegistrationId(this);
mGoogleNow.setVisibility(View.VISIBLE);
// dialog = ProgressDialog.show(MainActivity.this, "",
// "Loading...", true);
// dialog.setCanceledOnTouchOutside(false);
AuthAPI.unregisterGCM(token.token, regId, new AuthAPI.OnGcmRegListener() {
@Override
public void onRegistered() {
}
@Override
public void onUnregistered() {
AuthAPI.logout(token, new AuthAPI.OnAuthResultListener() {
@Override
public void onSuccess(Token token) {
Passenger.invalidate();
mGoogleNow.setVisibility(View.GONE);
// dialog.dismiss();
showLogin();
}
@Override
public void onFailure(Exception e) {
}
});
}
@Override
public void onError(Exception e) {
}
});
}
}
private void showLogin() {
IoUtils.deleteTokenFromPrefs(this);
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
MainActivity.this.finish();
}
@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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
BookACabFragment.java
public class BookACabFragment extends Fragment implements
GoogleMap.OnMapClickListener, GoogleMap.OnMarkerDragListener,
GoogleMap.OnMarkerClickListener, ViewPager.OnPageChangeListener,LocationListener,GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,View.OnClickListener {
String driverLongitude, driverlatitude, text;
String rotation;
float rotationF;
TextView tvdisTime;
ImageView taxiicon,ivCenterMaker;
HttpPost httppost;
StringBuffer buffer;
HttpResponse httpresponse;
InputStream content;
JSONArray daArray = null;
HttpClient httpclient;
JSONArray data = null;
String jsonString;
// HttpClient httpclient;
List<NameValuePair> nameValuePairs;
private ProgressDialog pDialog;
private static final String TAG = "BookACabFragment";
private static final float MAP_SCROLL_FACTOR = 3.33f;
private static final float MAP_SINGLE_MARKER_ZOOM = 14;
GoogleMap googleMap;
SupportMapFragment mapFragment;
SharedPreferences prefs;
SharedPreferences.Editor editor;
SlidingUpPanelLayout slidingLayout;
boolean isPanelExpanded = false;
boolean isConfirmedFragment = false;
SessionManager s;
SessionManager session;
NonSwipeableViewPager viewPager;
LinearLayout slidePanel;
BroadcastReceiver receiver;
boolean isRegistered = false;
String[] ss;
ArrayList<Marker> cabMarkers;
private ArrayList<Cab> mCabs;
public boolean showCabPicker;
LatLng ll;
TextView handleText;
String RDD = "0";
ImageView updown;
int panelHeight;
int activityHeight;
boolean panelFullScreen = false;
public static boolean openSlidingPanel = false;
View NavView1,NavView2,NavView3,NavView4;
LinearLayout NavViewMain;
BasePickerFragment currentPickerFragment;
PickSourceFragment pickSourceFragment;
PickCabTypeFragment pickCabTypeFragment;
PickCabFragment pickCabFragment;
PickDestinationFragment pickDestinationFragment;
PickDestinationFragmentPrebook pickDestinationFragmentPrebook;
ReviewFragment reviewFragment;
int currentPagerItem = 0;
String cabDistance="";
private LocationRequest mLocationRequest;
public static String ShopLat;
public static String ShopPlaceId;
public static String ShopLong;
// Stores the current instantiation of the location client in this object
private LocationClient mLocationClient;
boolean mUpdatesRequested = false;
private Geocoder geocoder;
private List<Address> addresses;
private LatLng latlngcenter;
String duration = "";
String distance = "";
Cab cAutoassign;
List<Marker> markerList;
ArrayList<LatLng> locations;
int viewCount=0;
private ScheduledExecutorService scheduler;
private ScheduledFuture<?> scheduledFuture;
LinearLayout ll_Rn_Rl;
Button Rn,RL;
static int vps=0;
public BookACabFragment(){}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onConnected(Bundle bundle) {
}
@Override
public void onDisconnected() {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onClick(View v) {
int id = v.getId();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
switch (id) {
case R.id.bt_Rn:
// Toast.makeText(getActivity(),openSlidingPanel+"clickqwal",Toast.LENGTH_SHORT).show();
openSlidingPanel=true;
ft.replace(R.id.content_frame, BookACabFragment.newInstance(true));
ft.commit();
/
break;
case R.id.bt_RL:
openSlidingPanel=true;
ft.replace(R.id.content_frame, BookACabFragment.newInstance(false));
ft.commit();
// ll_Rn_Rl.setVisibility(View.GONE);
//Your Operation
break;
}
}
public enum Fragments {
SOURCE_PICKER,
CABTYPE_PICKER,
CAB_PICKER,
DESTINATION_PICKER;
}
Fragments currentFrag;
String[] handleTitlesRideNow, handleTitlesPreBook;
public interface NavigationListener {
public void goBack();
public void goForward();
public void goForwardWithoutDestination();
}
public static BookACabFragment newInstance(boolean showCabPicker) {
BookACabFragment fragment = new BookACabFragment();
Bundle args = new Bundle(1);
args.putBoolean("showCabPicker", showCabPicker);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
showCabPicker = args.getBoolean("showCabPicker");
prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
editor = prefs.edit();
handleTitlesRideNow = getResources().getStringArray(R.array.handle_titles_ride_now);
handleTitlesPreBook = getResources().getStringArray(R.array.handle_titles_prebook);
ActionBar actionBar = getActivity().getActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
currentFrag = Fragments.SOURCE_PICKER;
pickSourceFragment = PickSourceFragment.newInstance(!showCabPicker);
pickSourceFragment.setOnAttachListener(new PickSourceFragment.OnAttachListener() {
@Override
public void onAttach() {
initMarker();
}
});
if (showCabPicker)
pickCabFragment = PickCabFragment.newInstance();
pickDestinationFragment = PickDestinationFragment.newInstance();
pickDestinationFragmentPrebook = PickDestinationFragmentPrebook.newInstance();
pickCabTypeFragment = PickCabTypeFragment.newInstance();
currentPickerFragment = pickSourceFragment;
reviewFragment = ReviewFragment.newInstance();
// initReceivers();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ActionBar actionBar = getActivity().getActionBar();
assert actionBar != null;
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
actionBar.setHomeButtonEnabled(true);
actionBar.setIcon(android.R.color.transparent);
String fontPath = "fonts/RobotoCondensed-Regular.ttf";
Typeface font2 = Typeface.createFromAsset(getActivity().getAssets(), fontPath);
SpannableStringBuilder SS = new SpannableStringBuilder(" Book Taxi");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, SS.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
actionBar.setTitle(SS);
int ActionBarTitleID = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView)getActivity().findViewById(ActionBarTitleID);
yourTextView.setTextAppearance(getActivity(), android.R.style.TextAppearance_Large);
actionBar.setDisplayHomeAsUpEnabled(true);
return inflater.inflate(R.layout.fragment_bookacab, container, false);
}
@Override
public void onResume() {
super.onResume();
vps= viewPager.getCurrentItem();
viewPager.setCurrentItem(vps);
startTimeScheduledExecutorService();
}
这是Stack Strace
6428-6428com.cabbooking.passenger EAndroidRuntime﹕ FATAL EXCEPTION main
java.lang.RuntimeException Unable to start activity ComponentInfo{com.cabbooking.passengercom.cabbooking.passengerapp.screens.MainActivity} android.support.v4.app.Fragment$InstantiationException Unable to instantiate fragment com.cabbooking.passengerapp.screens.BookACabFragment$18 make sure class name exists, is public, and has an empty constructor that is public
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2391)
at android.app.ActivityThread.access$600(ActivityThread.java151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java1335)
at android.os.Handler.dispatchMessage(Handler.java99)
at android.os.Looper.loop(Looper.java155)
at android.app.ActivityThread.main(ActivityThread.java5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java796)
at dalvik.system.NativeStart.main(Native Method)
Caused by android.support.v4.app.Fragment$InstantiationException Unable to instantiate fragment com.cabbooking.passengerapp.screens.BookACabFragment$18 make sure class name exists, is public, and has an empty constructor that is public
at android.support.v4.app.Fragment.instantiate(Fragment.java415)
at android.support.v4.app.FragmentState.instantiate(Fragment.java99)
at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java1807)
at android.support.v4.app.Fragment.performCreate(Fragment.java1493)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java908)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1121)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1103)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java1896)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java216)
at com.cabbooking.passengerapp.screens.MainActivity.onCreate(MainActivity.java75)
at android.app.Activity.performCreate(Activity.java5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2391)
at android.app.ActivityThread.access$600(ActivityThread.java151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java1335)
at android.os.Handler.dispatchMessage(Handler.java99)
at android.os.Looper.loop(Looper.java155)
at android.app.ActivityThread.main(ActivityThread.java5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java796)
at dalvik.system.NativeStart.main(Native Method)
Caused by java.lang.InstantiationException can't instantiate class com.cabbooking.passengerapp.screens.BookACabFragment$18; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java1319)
at android.support.v4.app.Fragment.instantiate(Fragment.java404)
at android.support.v4.app.FragmentState.instantiate(Fragment.java99)
at android.support.v4.app.FragmentManagerImpl.restoreAllState(FragmentManager.java1807)
at android.support.v4.app.Fragment.performCreate(Fragment.java1493)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java908)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1121)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java1103)
at android.support.v4.app.FragmentManagerImpl.dispatchCreate(FragmentManager.java1896)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java216)
at com.cabbooking.passengerapp.screens.MainActivity.onCreate(MainActivity.java75)
at android.app.Activity.performCreate(Activity.java5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java1101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java2391)
at android.app.ActivityThread.access$600(ActivityThread.java151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java1335)
at android.os.Handler.dispatchMessage(Handler.java99)
at android.os.Looper.loop(Looper.java155)
at android.app.ActivityThread.main(ActivityThread.java5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java511)
答案 0 :(得分:1)
从BookACabFragment
中删除此构造函数public BookACabFragment(){}