Android: "Unable to instantiate Fragment" - java

Here is my Java code. The problem is whenever I return to my application from foreground, the app crashes giving the error shown in the stack trace below (unable to instantiate 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();
}
here is the 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)
      

Read the log carefully:
Caused by java.lang.InstantiationException can't instantiate class com.cabbooking.passengerapp.screens.BookACabFragment$18; no empty constructor
The android os could not instantiate the class BookACabFragment$18, not your Fragment BookACabFragment!
I do not think that it is possible to create an anonymous fragment, because of the lack of public accessability.
Update: After reading your code. I think I found your the wrong code:
mapFragment = new SupportMapFragment() {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = mapFragment.getMap();
if (googleMap != null) {
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.setOnMapClickListener(BookACabFragment.this);
googleMap.setOnMarkerDragListener(BookACabFragment.this);
googleMap.setOnMarkerClickListener(BookACabFragment.this);
//googleMap.setMyLocationEnabled(true);
pickedLocation = GeoUtils.getLocationFromPreferences(getActivity());
}
}
};
You cannot create an anonymous fragment. Either put your Fragment to a new class or create it as static-class in your BookACabFragment. I would prefer the first option:
public class MySupportMapFragment extends SupportMapFragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Your funky stuff
}
}
Additional hint: Your class has over 2000 lines of code. You should really refactor this monolith.

Try adding an empty constructor to your BookACabFragment.
public BookACabFragment() {
}

Related

Bluetooth beacon Scanning using android beacon library

I have a problem every time i open an activity (blueToothSearch.java) the following error occurs in my logcat.
12-04 18:57:52.317 5354-5354/com.example.admin.paniccenter E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.paniccenter, PID: 5354
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.admin.paniccenter/com.example.admin.paniccenter.blueToothSearch}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2327)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
at org.altbeacon.beacon.BeaconManager.<init>(BeaconManager.java:323)
at org.altbeacon.beacon.BeaconManager.getInstanceForApplication(BeaconManager.java:315)
at com.example.admin.paniccenter.blueToothSearch.<init>(blueToothSearch.java:65)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2317)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Below is my blueToothSearch activity which i want to use to display a list of beacons in my region.
public class blueToothSearch extends AppCompatActivity implements BeaconConsumer {
private static final String TAG = "blueToothSearch";
private ViewPagerAdapter viewadapter;
private ViewPager myViewPager;
private TabLayout tabLayout;
public Toolbar toolbar;
//public static Handler UIHandler;
private static final int REQUEST_ENABLE_BT = 1234;
//public static final String EXTRAS_TARGET_ACTIVITY = "extrasTargetActivity";
//private static final String JAALEE_BEACON_PROXIMITY_UUID = "EBEFD083-70A2-47C8-9837-E7B5634DF524";//Jaalee BEACON Default UUID
// private static final Region ALL_BEACONS_REGION = new Region("rid", null, null, null);
//public static final String EXTRAS_BEACON = "extrasBeacon";
public BeaconManager beaconManager = BeaconManager.getInstanceForApplication(getBaseContext());
private ArrayList<Beacon> arrayL = new ArrayList<Beacon>();
private BeaconServiceUtility beaconUtill = null;
private BeaconAdapter adapterr;
public ListView list;
private LayoutInflater inflater;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
viewadapter = new ViewPagerAdapter(getSupportFragmentManager());
toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitle("Bluetooth Devices");
//Set up the View Pager with the View page adapter
myViewPager = (ViewPager)findViewById(R.id.viewpager);
tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(myViewPager);
//tabLayout.setVisibility(View.GONE);
final FloatingActionButton fab = (FloatingActionButton)findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_popup_sync_24);
setupViewPager(myViewPager);
setSupportActionBar(toolbar);
//viewPager.setAdapter(adapter);
myViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
switch (position){
case 0: fab.show();
break;
case 1: fab.hide();
break;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
drawer.closeDrawer(Gravity.LEFT);
}
});
adapterr = new BeaconAdapter();
list = findViewById(R.id.beaconlist);
list.setAdapter(adapterr);
//list.setOnItemClickListener(createOnItemClickListener());
inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
private void setupViewPager(ViewPager viewPager){
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new blueToothSearch.bluetooth(), "Available Devices");
adapter.addFragment(new bluetoothProperties(), "Device Properties");
viewPager.setAdapter(adapter);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_ENABLE_BT){
if (resultCode == Activity.RESULT_OK){
connectToService();
}else {
Toast.makeText(this, "Bluetooth not enabled", Toast.LENGTH_LONG).show();
getSupportActionBar().setSubtitle("Bluetooth not enabled");
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private void connectToService(){
try {
beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null));
}catch (RemoteException e){
e.printStackTrace();
}
try {
beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
}catch (RemoteException e){
e.printStackTrace();
}
}
/**
private AdapterView.OnItemClickListener createOnItemClickListener(){
return new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
if (getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY) != null){
try {
Class<?> clazz = Class.forName(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY));
Intent intent = new Intent(blueToothSearch.this, clazz );
Beacon temp = adapterr.getItem(pos);
intent.putExtra(EXTRAS_BEACON, temp);
if(getIntent().getStringExtra(EXTRAS_TARGET_ACTIVITY).contains("com.example.admin.paniccenter.CharacteristicsDemoActivity"))
{
startActivity(intent);
// if (temp.getProximityUUID().equalsIgnoreCase(JAALEE_BEACON_PROXIMITY_UUID)) {
// startActivity(intent);
// }
// else
// {
// ListBeaconsActivity.this.runOnUiThread(new Runnable()
//{
// public void run()
// {
//Toast.makeText(ListBeaconsActivity.this, "Current Beacon is in Non-Connectable mode", Toast.LENGTH_LONG).show();
// }
// });
// }
}
else
{
startActivity(intent);
}
}catch (ClassNotFoundException e){
Log.e(TAG, "Finding class by name failed", e);
}
}
}
};
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.scan_menu, menu);
MenuItem refreshItem = menu.findItem(R.id.refresh);
refreshItem.setActionView(R.layout.actionbar_indeterminate_progress);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onStart() {
super.onStart();
beaconUtill.onStart(beaconManager, this);
}
#Override
public void onStop() {
beaconUtill.onStop(beaconManager, this);
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onBeaconServiceConnect() {
getSupportActionBar().setSubtitle("Scanning...");
Toast.makeText(this, "Scanning for devices", Toast.LENGTH_LONG).show();
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
arrayL.clear();
arrayL.addAll((ArrayList<Beacon>) beacons);
adapterr.notifyDataSetChanged();
}
});
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
Log.e("BeaconDetactorService", "didEnterRegion");
}
#Override
public void didExitRegion(Region region) {
Log.e("BeaconDetactorService", "didExitRegion");
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
Log.e("BeaconDetactorService", "didDetermineStateForRegion");
}
});
connectToService();
}
public static class bluetooth extends Fragment {
private static final String TAG = "bluetooth";
private int position;
private TextView textv;
private ViewPagerAdapter viewadapter;
private ViewPager myViewPager;
private TabLayout tabLayout;
private FragmentActivity myContext;
#Override
public void onAttach(Context context) {
super.onAttach(context);
//hideAction = (HideActionBar)getContext();
myContext = (FragmentActivity)getContext();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//position = getArguments().getInt("pos");
//toolbar.getMenu().clear();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//return inflater.inflate(R.layout.fragment_bluetooth_search, container, false);
View view = inflater.inflate(R.layout.fragment_bluetooth_search, container, false);
//TextView text = (TextView)getActivity().findViewById(R.id.view);
//text.setText("i am the real text ");
//hideAction.customBlueToothToolbar();
//FloatingActionButton fl = (FloatingActionButton)getActivity().findViewById(R.id.fab);
//fl.setImageResource(R.drawable.ic_popup_sync_24);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
public class BeaconAdapter extends BaseAdapter {
private ArrayList<Beacon> beacons;
#Override
public int getCount() {
return arrayL.size();
}
#Override
public Beacon getItem(int arg0) {
return arrayL.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
try {
ViewHolder holder;
if (convertView != null) {
holder = (ViewHolder) convertView.getTag();
} else {
holder = new ViewHolder(convertView = inflater.inflate(R.layout.tupple_monitoring, null));
}
if (beacons.get(position).getParserIdentifier() != null)
holder.beacon_uuid.setText("UUID: " + arrayL.get(position).getParserIdentifier());
holder.beacon_major.setText("Major: " + arrayL.get(position).getBeaconTypeCode());
holder.beacon_minor.setText(", Minor: " + arrayL.get(position).getBluetoothName());
holder.beacon_proximity.setText("Proximity: " + arrayL.get(position).getDistance());
holder.beacon_rssi.setText(", Rssi: " + arrayL.get(position).getRssi());
holder.beacon_txpower.setText(", TxPower: " + arrayL.get(position).getTxPower());
holder.beacon_range.setText("" + arrayL.get(position).getExtraDataFields());
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
private class ViewHolder {
private TextView beacon_uuid;
private TextView beacon_major;
private TextView beacon_minor;
private TextView beacon_proximity;
private TextView beacon_rssi;
private TextView beacon_txpower;
private TextView beacon_range;
public ViewHolder(View view) {
beacon_uuid = (TextView) view.findViewById(R.id.BEACON_uuid);
beacon_major = (TextView) view.findViewById(R.id.BEACON_major);
beacon_minor = (TextView) view.findViewById(R.id.BEACON_minor);
beacon_proximity = (TextView) view.findViewById(R.id.BEACON_proximity);
beacon_rssi = (TextView) view.findViewById(R.id.BEACON_rssi);
beacon_txpower = (TextView) view.findViewById(R.id.BEACON_txpower);
beacon_range = (TextView) view.findViewById(R.id.BEACON_range);
view.setTag(this);
}
}
}
I am using a BeaconManager class to range and scan my beacons, the library is from package org.altbeacon.beacon

Beginner, Maintaining Fragment State When switching using Navigation Drawer

I'm a beginner with java and android development but managed to create a navigation drawer activity which switches between five fragment with ListViews using AsycTask. The AsycTask starts again when ever I switch between the fragments. I have gone through many of the post here but none seems to work. Any help.
Here is My Navigation Drawer Activity
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static String website = "https://www.website.com", fbPage = "https://www.facebook.com",
twitter = "https://twitter.com",
private android.support.v4.app.FragmentManager fragmentManager;
private android.support.v4.app.FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_holder, new HomeFragment(), "Home Fragment")
.commit();
fragmentManager = getSupportFragmentManager();
}
private void customNavgation() {
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.getMenu().getItem(0).setChecked(true);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
HomeFragment homeFragment = new HomeFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, homeFragment, "HomeFragment");
fragmentTransaction.commit();
} else if (id == R.id.nav_message) {
MessageFragment messageFragment = new MessageFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, messageFragment, "MessageFragment");
fragmentTransaction.commit();
} else if (id == R.id.nav_word) {
WordFragment wordFragment = new WordFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, wordFragment, "WordFragment");
fragmentTransaction.commit();
} else if (id == R.id.nav_events) {
EventsFragment eventsFragment = new EventsFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, eventsFragment, "EventsFrangment");
fragmentTransaction.commit();
} else if (id == R.id.nav_service) {
ServiceFragment serviceFragment = new ServiceFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_holder, serviceFragment, "Service Fragment");
fragmentTransaction.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
And here is one of my Fragment class
public class EventsFragment extends Fragment {
ArrayList<EventsFields> eventsFieldsList;
private ListView eventlist;
static final String EVENT_LINK = "http:www.website.com";
private ProgressBar pb;
private View view;
public EventsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_events, container, false);
eventlist = (ListView) view.findViewById(R.id.event_frag_listView);
pb = (ProgressBar) view.findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
if (isOnline()) {
requestData(EVENT_LINK);
} else {
Toast.makeText(EventsFragment.this.getActivity(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
return view;
}
protected void updateDisplay() {
EventsListAdapter adapter = new EventsListAdapter(EventsFragment.this.getActivity(), R.layout.event_list_layout, eventsFieldsList);
eventlist.setAdapter(adapter);
eventlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventsFragment.this.getActivity(), EventDetail.class);
EventsFields selectedEvent = eventsFieldsList.get(position);
intent.putExtra("selectedEvent", selectedEvent);
startActivity(intent);
}
});
}
private void requestData(String uri) {
MyTask task = new MyTask();
task.execute(uri);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public class MyTask extends AsyncTask<String, String, ArrayList<EventsFields>> {
#Override
protected void onPreExecute() {
pb.setVisibility(View.VISIBLE);
}
#Override
protected ArrayList<EventsFields> doInBackground(String... params) {
String data = HttpManager.getData(params[0]);
eventsFieldsList = EventsJsonParser.parseFeed(data);
return eventsFieldsList;
}
#Override
protected void onPostExecute(ArrayList<EventsFields> results) {
pb.setVisibility(View.INVISIBLE);
if (results == null) {
Toast.makeText(EventsFragment.this.getActivity(), "Web service not available", Toast.LENGTH_LONG).show();
return;
}
eventsFieldsList = results;
updateDisplay();
}
}
JsonPaser Class
public class EventsJsonParser {
public static ArrayList<EventsFields> parseFeed(String content) {
try {
JSONArray ar = new JSONArray(content);
ArrayList<EventsFields> eventList = new ArrayList<>();
for (int i = 0; i < ar.length(); i++) {
JSONObject obj = ar.getJSONObject(i);
EventsFields events = new EventsFields(null);
events.setId(obj.getInt("id"));
events.setEventName(obj.getString("EventName"));
events.setStartDate(obj.getString("StartDate"));
events.setEventDesc(obj.getString("EventDesc"));
events.setTime(obj.getString("Time"));
events.setVenue(obj.getString("Venue"));
eventList.add(events);
}
return eventList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Thanks
One approach is to persist the data and then don't call the AsyncTask if you've already received the data.
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("eventsFieldsList", eventsFieldsList);
super.onSaveInstanceState(outState);
}
then in onCreateView():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_events, container, false);
eventlist = (ListView) view.findViewById(R.id.event_frag_listView);
pb = (ProgressBar) view.findViewById(R.id.progressBar);
pb.setVisibility(View.INVISIBLE);
if (savedInstanceState != null) {
eventsFieldsList = savedInstanceState.getParcelableArrayList("eventsFieldsList");
}
if (eventsFieldList == null) {
if (isOnline()) {
requestData(EVENT_LINK);
} else {
Toast.makeText(EventsFragment.this.getActivity(), "No Internet Connection", Toast.LENGTH_LONG).show();
}
}
return view;
}
You would need to make your EventsFields class implement Parcelable. There are lots of online tutorials and SO answers on this. If you have problems with implementing Parcelable, post a new question.

Navigation Drawer not opening when using android support library v23.4.0

Hello everyone I'm developing an app that uses old navigation drawer approach. When I update 'com.android.support:appcompat-v7:23.1.1' to 'com.android.support:appcompat-v7:23.4.0' my navigation drawer not opening.
I debugged code and look for deprecated items but could not find any error code or message. Everything works perfectly but navigation drawer is not opening. Here is my code. Thanks in advance.
MainActivity.class
public class MainActivity extends AppCompatActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, TapuInterface.IAuthorization {
TapuUtils tapuUtils = new TapuUtils();
String userMail, userPassword;
SharedPreferences.Editor editor;
SharedPreferences preferences;
Tracker mTracker;
Bundle bundle;
String tapuAuth = "false";
private NavigationDrawerFragment mNavigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleAnalytics.getInstance(this).setLocalDispatchPeriod(15);
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
Countly.sharedInstance().init(this, getString(R.string.countly_server), getString(R.string.countly_key));
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,(DrawerLayout) findViewById(R.id.drawer_layout));
ActionBar mActionBar = getSupportActionBar();
assert mActionBar != null;
mActionBar.setBackgroundDrawable(new ColorDrawable(0xFF297AA6));
if (savedInstanceState == null) {
bundle = getIntent().getExtras();
userMail = bundle.getString("personname");
userPassword = bundle.getString("personpassword");
tapuAuth = bundle.getString("tapu");
}
TapuCredentials.setUserMail(userMail);
TapuCredentials.setUserPassword(userPassword);
TapuCredentials.setTapuAuth(tapuAuth);
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, MainMapFragment.newInstance(position + 1), "MapFragment")
.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.exit_alert))
.setCancelable(true)
.setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
LoginActivity.fa.finish();
}
})
.setNegativeButton(getString(R.string.no), null)
.show();
}
#Override
public void onStart() {
super.onStart();
Countly.sharedInstance().onStart();
}
#Override
public void onStop() {
super.onStop();
Countly.sharedInstance().onStop();
}
#Override
protected void onResume() {
super.onResume();
mTracker.setScreenName(getResources().getString(R.string.main_screen));
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
Here is my NavigationDrawer.class
public class NavigationDrawerFragment extends Fragment {
private static NavigationDrawerAdapter myAdapter;
public static ArrayList<ListItem> myItems = new ArrayList<>();
public static UserCredentials mUserCredentials = new UserCredentials();
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private NavigationDrawerCallbacks mCallbacks;
private android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private DynamicListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
static LegendFragment frLegend = new LegendFragment();
Button mEditLayers, mShowLegend;
String personName,userType,tapucontrol;
TextView mLayersText;
static FragmentManager fragmentManager;
Bundle extras;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
if (savedInstanceState == null) {
extras = getActivity().getIntent().getExtras();
if(mUserCredentials.getUserName()==null || mUserCredentials.getPassword()==null){
mUserCredentials.setUserAccount(extras.getString("username"), extras.getString("password"));
}
personName = extras.getString("personname");
userType = extras.getString("usertype");
tapucontrol = extras.getString("tapu");
}
mDrawerListView = (DynamicListView) rootView.findViewById(R.id.dynamiclistivew);
mLayersText = (TextView) rootView.findViewById(R.id.textview_layers);
myAdapter = new NavigationDrawerAdapter(getActivity(), myItems);
mDrawerListView.setAdapter(myAdapter);
fragmentManager = getFragmentManager();
mDrawerListView.setCheeseList(myItems);
mDrawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
mEditLayers = (Button) rootView.findViewById(R.id.button);
mShowLegend = (Button) rootView.findViewById(R.id.legendbutton);
mEditLayers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mEditLayers.getText().equals("Düzenle")) {
myAdapter.setEditMode(true);
mEditLayers.setText(getActivity().getString(R.string.ok));
} else {
myAdapter.setEditMode(false);
mEditLayers.setText(getActivity().getString(R.string.editlayers));
}
}
});
return rootView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowTitleEnabled(false);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
null, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
FragmentTransaction ft = fragmentManager.beginTransaction();
if (frLegend.isAdded()) {
ft.remove(frLegend);
ft.commitAllowingStateLoss();
mEditLayers.setVisibility(View.VISIBLE);
mLayersText.setText("Katmanlar");
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.main, menu);
// showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_search:
Intent s = new Intent(getActivity(), SearchMainActivity.class);
s.putExtra("username", mUserCredentials.getUserName());
s.putExtra("password", mUserCredentials.getPassword());
s.putExtra("tapu",tapucontrol);
startActivity(s);
break;
case R.id.action_basemaps:
Intent cb = new Intent(getActivity(), BaseMapsActivity.class);
startActivity(cb);
break;
case R.id.action_addlayer:
if (isNetworkAvailable(getActivity())) {
Intent al = new Intent(getActivity(), AddLayerActivity.class);
al.putExtra("usertype", userType);
startActivity(al);
} else {
Toast.makeText(getActivity(), "Lütfen internet bağlantınızı kontrol ediniz.", Toast.LENGTH_SHORT).show();
}
break;
case R.id.action_about:
Intent au = new Intent(getActivity(), AboutActivity.class);
au.putExtras(extras);
startActivity(au);
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
}
private ActionBar getActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
public class ListItem {
String textdata;
Integer progress;
public ListItem(String textdata, int progress) {
this.textdata = textdata;
this.progress = progress;
}
public boolean equals(Object o) {
ListItem ndListItemObject = (ListItem) o;
return this.textdata.equalsIgnoreCase(ndListItemObject.textdata);
}
}
public void addLayersection(String name, int progress) {
ListItem listItem = new ListItem(name, progress);
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.size() == 0) {
myItems.add(0, listItem);
} else {
if (myItems.contains(listItem)) {
myItems.remove(listItem);
} else {
myItems.add(0, listItem);
}
}
}
myAdapter.notifyDataSetChanged();
}
public int getListSizee() {
return myItems.size();
}
public static boolean isNetworkAvailable(Context context) {
return ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo() != null;
}
The Drawer is locked.
Change
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
to
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
Here is the late solution that I find with myself. drawerOpenCloseControl is boolean flag. I am controlling true or false. And then open and close manually.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(drawerOpenCloseControl){
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_OPEN);
drawerOpenCloseControl = false;
}
else{
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
drawerOpenCloseControl = true;
}
break;
}
return super.onOptionsItemSelected(item);
}

java.lang.NullPointerException when resume activity in viewpager

I would like to resume activity which i have stored in share preferences in viewpager. I have stored the activity details in onSaveState and retrieve the activity getpreferences in onResume. But somehow, it returns error that the key is in null value in onSaveState. How to save the preferences in viewpager ?
Here is the code
public class FullScreenImageActivity extends AppCompatActivity {
ViewPager viewPager;
ImageView favBtn;
private SharedPreference sharedPreference;
Activity context = this;
private Fragment contentFragment;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen_image); //TBS
FragmentManager fragmentManager = getSupportFragmentManager();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavouriteListFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID) != null) {
contentFragment = fragmentManager
.findFragmentByTag(FavouriteListFragment.ARG_ITEM_ID);
}
}
}
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
String[] arr=i.getStringArrayExtra("array");
String url = i.getStringExtra("url");
sharedPreference = new SharedPreference();
viewPager = (ViewPager) findViewById(R.id.slider);
viewPager.setAdapter(new GalleryViewPagerAdapter(this, arr, position, url));
viewPager.setCurrentItem(position);
}
class GalleryViewPagerAdapter extends PagerAdapter {
private Context context;
LayoutInflater inflater;
private String[] imageArrayList;
private String mUrl;
private int mPosition;
private ProgressDialog mProgress;
public GalleryViewPagerAdapter(Context _context, String[] imageArrayList, int position, String url) {
context = _context;
this.imageArrayList = imageArrayList; //null;
this.mPosition=position;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mUrl=url;
}
#Override
public int getCount() {
return imageArrayList.length;
}
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
showProgress();
favBtn = (ImageView) findViewById(R.id.btn_favourite);
String favoriteUrl=sharedPreference.getPrefsFavUrl(context);
//Boolean stateBtnNow=sharedPreference.getBtnState(context,mUrl);//why mUrl change to same url with favourite
Boolean stateBtnNow=false;
if(stateBtnNow) {
favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
}
else
{
favBtn.setColorFilter(Color.argb(255, 192, 192, 192));
}
favBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Boolean stateBtn = sharedPreference.getBtnState(context, mUrl);
Boolean stateBtn=false;
if (!stateBtn) {
sharedPreference.save(context, mUrl);
//edit to save url in array
//sharepreference.add(context, product);
sharedPreference.saveBtnState(context, stateBtn);
Toast.makeText(context,
"Added to Favourite!",
Toast.LENGTH_SHORT).show();
favBtn.setColorFilter(Color.argb(255, 249, 0, 0));//red
Toast.makeText(context,
"Button state is " + stateBtn,
Toast.LENGTH_SHORT).show();
} else {
sharedPreference.saveBtnState(context, stateBtn);
favBtn.setColorFilter(Color.argb(255, 192, 192, 192));//grey
}
}
});
View photoRow = inflater.inflate(R.layout.item_fullscreen_image, container,
false);
TouchImageView fullScreenImg;
fullScreenImg =(TouchImageView)photoRow.findViewById(R.id.img_flickr);
// added imageloader for better performance
StaggeredDemoApplication.getImageLoader().get(imageArrayList[position],
ImageLoader.getImageListener(fullScreenImg, R.drawable.bg_no_image, android.R.drawable.ic_dialog_alert), container.getWidth(), 0);
((ViewPager) container).addView(photoRow);
stopProgress();
return photoRow;
}
private void stopProgress() {
mProgress.cancel();
}
private void showProgress() {
mProgress = ProgressDialog.show(FullScreenImageActivity.this, "", "Loading...");
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((RelativeLayout) object);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("content", FavouriteListFragment.ARG_ITEM_ID);
super.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
}
}
Here is the code in sharepreferences
public class SharedPreference {
public static final String PREFS_NAME = "AOP_PREFS";
public static final String PREFS_STATE="AOP_BTN";
public static final String PREFS_FAV_URL="AOP_FAV_URL";
public static final String PREFS_KEY = "AOP_PREFS_String";
public static final String PREF_BTN_KEY = "AOP_PREF_BTN";
public static final String PREF_URL_KEY = "AOP_PREF_URL";
public SharedPreference() {
super();
}
public void save(Context context, String text) {
SharedPreferences settings;
Editor editor;
//edit here to add image array list
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREFS_KEY, text); //3
editor.commit(); //4
}
public String getValue(Context context) {
SharedPreferences settings;
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
text = settings.getString(PREFS_KEY, null);
return text;
}
public String getPrefsFavUrl(Context context){
SharedPreferences settings;
String favUrl;
settings = context.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE);
favUrl = settings.getString(PREF_URL_KEY, null);
return favUrl;
}
public void clearSharedPreference(Context context) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.clear();
editor.commit();
}
public void removeValue(Context context) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.remove(PREFS_KEY);
editor.commit();
}
public void saveBtnState(Context context, Boolean stateBtn) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putBoolean(PREF_BTN_KEY, stateBtn);//added state for button
editor.commit(); //4
}
public boolean getBtnState(Context context,String text)//edit to store url here and check the boolean here
{
SharedPreferences prefs;
prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String favUrl = getPrefsFavUrl(context);
boolean switchState = false;
if(favUrl.equals(text)) {
switchState=true;
}
return switchState;
}
public void saveFavourite(FragmentActivity activity, String favouriteUrl) {
SharedPreferences settings;
Editor editor;
settings = activity.getSharedPreferences(PREFS_FAV_URL, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREF_URL_KEY, favouriteUrl); //3
editor.commit(); //4
}
}
Here is the error log file
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.lang.Class.newInstance()' on a null object reference
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at com.example.myapp.MainActivity.displayView(MainActivity.java:141)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at com.example.myapp.MainActivity.onCreate(MainActivity.java:41)
02-03 09:48:57.928 15368-15368/com.example.myapp W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
Here is my MainActivity program
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, FragmentFlickrGridImage.OnFragmentInteractionListener, ShareActionProvider.OnShareTargetSelectedListener {
private int backstack_count;
private boolean viewIsAtHome;
private Fragment contentFragment;
private ShareActionProvider share;
private Intent shareIntent=new Intent(Intent.ACTION_SEND);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (savedInstanceState == null) {
displayView(R.id.recent_picture);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
navigationView.setNavigationItemSelectedListener(this);
shareIntent.setType("text/plain");
}
private void replaceFragment(Fragment fragment, boolean isAddToBackStack) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.flContent, fragment);
if (isAddToBackStack) {
transaction.addToBackStack(fragment.getClass().toString());
backstack_count ++;
}
transaction.commit();
}
#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, menu);
MenuItem item = menu.findItem(R.id.share);
share = new ShareActionProvider(this);
MenuItemCompat.setActionProvider(item, share);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.share) {
onShareAction();
return true;
}
return super.onOptionsItemSelected(item);
}
private void onShareAction() {
String yourShareText = "test";
Intent shareIntent = ShareCompat.IntentBuilder.from(this).setType("text/plain").setText(yourShareText).getIntent();
// Set the share Intent
if (share != null) {
share.setShareIntent(shareIntent);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
displayView(item.getItemId());
return true;
}
private void displayView(int itemId) {
Fragment fragment = null;
Class fragmentClass = null;
String title="";
switch (itemId){
case R.id.one:
fragment = new FragmentFlickrGridImage("one");
title="one";
viewIsAtHome=true;
break;
case R.id.two:
fragment = new FragmentFlickrGridImage(" two");
title ="two";
viewIsAtHome=false;
break;
case R.id.three:
fragment = new FragmentFlickrGridImage("three");
title="three";
viewIsAtHome=false;
break;
case R.id.four:
fragment=new FavouriteListFragment();
title="Favourite";
viewIsAtHome=false;
break;
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
getSupportActionBar().setTitle(title);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
if (!viewIsAtHome) { //if the current view is not the Recent Hot Girl fragment
displayView(R.id.recent_picture);
} else {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
finish();
break;
case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setMessage("Are you sure?")
.setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener)
.setCancelable(false)
.setTitle("Exit");
builder.show();
}
}
#Override
public boolean onShareTargetSelected(ShareActionProvider source,
Intent intent) {
Toast.makeText(this, intent.getComponent().toString(),
Toast.LENGTH_LONG).show();
return(false);
}
}
The error line is:
fragment = (Fragment) fragmentClass.newInstance();
fragmentClass is always assigned with null object when you use it in fragmentClass.newInstance(), and it always have null value because you never assign it with other value. Try to remove these lines:
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Anyway, using non-empty constructor for the fragments is not a good practice. You should use this pattern instead.
EDIT
Check whether fragment is empty or not:
if (fragment != null){
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
}

Android fragments getArguments returns null

I'm getting null from the args in MyListFragment,
cant figure out why.
Basically what I'm trying to do is get a location from a Map
and replace the old fragment with a new one which has updated location,
MyListFragmnet is a "default" fragment in the NavigationDrawerActivity
//MyListFragment.java
public static MyListFragment newInstance() {
Bundle args = new Bundle();
return newInstance(args);
}
public static MyListFragment newInstance(Bundle args) {
MyListFragment fragment = new MyListFragment();
fragment.setArguments(args);
return fragment;
}
public MyListFragment() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.setHasOptionsMenu(true);
Bundle args = getArguments();
searchQuery = args.getString(SEARCH_QUERY_ARG, ""); //NULL ERROR!!
final MyLocation checkLocation = (MyLocation) args.getSerializable(LOCATION_ARG);
if (!searchQuery.isEmpty()) {
activity.setTitle("\""+searchQuery+"\"");
}
setLocation(checkLocation);
............
private void setLocation(final MyLocation checkLocation) {
if (checkLocation != null) {
// If no location is set and there is a check
location = new Location("");
location.setLatitude(checkLocation.latitude);
location.setLongitude(checkLocation.longitude);
} else {
// If no location was provided, get the current one
location = LocationHelper.getInstance().getLocation(context);
}
}
//NavigationDrawerActivity.java
public class NavigationDrawerActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle toggle;
private NavigationView navLayout;
//Location
private MyLocation checkLocation;
private boolean active;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_navigation);
setupReferences();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
toolbar.setTitleTextColor(Color.WHITE);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
try {
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setSubtitle(getString(R.string.subtitle));
actionBar.setDisplayShowTitleEnabled(true);
} catch (Exception ignored) {
}
drawerLayout = (DrawerLayout)findViewById(R.id.drawerLayout);
toggle = new ActionBarDrawerToggle(this,
drawerLayout,
toolbar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
navLayout= (NavigationView)findViewById(R.id.navLayout);
navLayout.setNavigationItemSelectedListener(this);
active = false;
checkLocation = (MyLocation) getIntent().getSerializableExtra(MyListFragment.LOCATION_ARG);
handleIntent(getIntent());
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.frameLayout, new MyListFragment());
tx.commit();
}
#Override
public boolean onNavigationItemSelected(MenuItem menuItem){
switch (menuItem.getItemId()){
case R.id.navigation_item_1:
break;
case R.id.navigation_item_2:
break;
case R.id.navigation_item_3:
break;
}
return false;
}
#Override
protected void onNewIntent(Intent intent) {
if (active) {
// Only handles the Intent again if the Activity was already active
handleIntent(intent);
}
}
#Override
public void startActivity(Intent intent) {
super.startActivity(intent);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
intent.putExtra(MyListFragment.LOCATION_ARG, checkLocation);
}
active = true;
}
private void handleIntent(Intent intent) {
Bundle args = new Bundle();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String searchQuery = intent.getStringExtra(SearchManager.QUERY);
args.putString(MyListFragment.SEARCH_QUERY_ARG, searchQuery);
args.putSerializable(MyListFragment.LOCATION_ARG, checkLocation);
} else if (MyListFragment.ACTION_CHECK.equals(intent.getAction())) {
checkLocation = (MyLocation) intent.getSerializableExtra(LocationActivity.EXTRA_LOCATION);
args.putSerializable(MyListFragment.LOCATION_ARG, checkLocation);
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout, MyListFragment.newInstance(args)).commit();
}
}
Please Help! Thanks.
You are not using MyListFragment.newInstance() but simply calling new MyListFragment()
this line
tx.replace(R.id.frameLayout, new MyListFragment());
should be
tx.replace(R.id.frameLayout, MyListFragment.newInstance());
Here:
...
tx.replace(R.id.frameLayout, new MyListFragment());
...
Not passing any bundle when creating object of MyListFragment Fragment.
Do it by calling newInstance(Bundle args) static method for getting Fragment object.
Bundle bundle = new Bundle();
bundle.putString(SEARCH_QUERY_ARG, "data_here");
...
tx.replace(R.id.frameLayout, new MyListFragment.newInstance(bundle));
...

Categories