Android fragments getArguments returns null - java

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));
...

Related

Navigation Drawer Back Pressed Fragment Doesn't Load

I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.page__navigation, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}

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.

Fragment disappears from the screen

I have activity, with two fragments. FragmentSurahDetail and FragmentTafsir. FragmentTafsir is added when the event "OnOpenTafsir". If FragmentTafsir added and to change the orientation, FragmentTafsir disappears from the screen. Any idea how to fix it?
here is my code:
public class ActivitySurahDetail extends AppCompatActivity implements FragmentSurahDetail.SurahListener {
Toolbar toolbar;
final String LOG_TAG = "ASD Tag";
private static final String TAFSIR_FRAGMENT_TAG = "tafsir_fragment";
private static final String SURAH_DETAIL_TAG = "surah_fragment";
int surah_id;
FragmentTafsir fragmentTafsir;
private boolean favoriteMode;
FragmentTransaction fragmentTransaction;
FragmentSurahDetail fragmentSurahDetail;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surah_detail_activity);
Bundle extras = getIntent().getExtras();
surah_id = extras.getInt("item_id");
favoriteMode = extras.getBoolean("favoriteMode", false);
fragmentSurahDetail = new FragmentSurahDetail();
Bundle args = new Bundle();
args.putBoolean("favoriteMode", true);
args.putInt("item_id", surah_id);
fragmentSurahDetail.setArguments(args);
getSupportFragmentManager().beginTransaction().replace(R.id.surah_detail_container, fragmentSurahDetail, SURAH_DETAIL_TAG).commit();
// Show the Up button in the action bar.
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public void onOpenTafsir(int surah, int ayah) {
fragmentTafsir = new FragmentTafsir();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
Bundle extras = new Bundle();
extras.putInt("surah", surah);
extras.putInt("ayah", ayah);
fragmentTafsir.setArguments(extras);
fragmentTransaction.addToBackStack(TAFSIR_FRAGMENT_TAG);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.replace(R.id.surah_detail_container, fragmentTafsir, TAFSIR_FRAGMENT_TAG).commit();
}
}
solved. I just added the line
if (getSupportFragmentManager().findFragmentByTag(SURAH_DETAIL_TAG) == null){
getSupportFragmentManager().beginTransaction().replace(R.id.surah_detail_container, fragmentSurahDetail, SURAH_DETAIL_TAG).commit();
}
Use setRetainInstance(true) in your fragment. Here is the official doc:
http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)

Android: "Unable to instantiate Fragment"

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() {
}

SlidingMenu with ViewPager and ActionBarSherlock Tabs

In my calendar application, I am using ActionBarSherlock to display two tabs - 1) Calendar 2) Converter. On the click event of an ActionBar menu item, I'm using SlidingMenu drawer to display event summary for that month.
I want to use viewpager specifically for the Calendar tab and I have implemented it this way:
Main.java:
public class BaseActivity extends SlidingSherlockFragmentActivity
{
private ViewPager pager;
CalendarFragmentPagerAdapter mPagerAdapter;
private static final int MONTHS_LIMIT = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(R.string.app_name);
setContentView(R.layout.main);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
setBehindContentView(R.layout.content_frame);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new EventsSummary())
.commit();
setSlidingActionBarEnabled(false);
final ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setHomeButtonEnabled(true);
ActionBar.Tab calendar = bar.newTab();
ActionBar.Tab converter = bar.newTab();
calendar.setText(this.getResources().getString(R.string.calendar));
converter.setText(this.getResources().getString(R.string.converter));
calendar.setTabListener(new MyTabListener());
converter.setTabListener(new MyTabListener());
bar.addTab(calendar);
bar.addTab(converter);
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.actionbar_home_width);
sm.setSlidingEnabled(false);
mPagerAdapter = new CalendarFragmentPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) this.findViewById(R.id.viewpager);
pager.setAdapter(mPagerAdapter);
pager.setCurrentItem(MONTHS_LIMIT / 2);
}
private class MyTabListener implements ActionBar.TabListener
{
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getPosition()==0)
{
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
}
else
{
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
public boolean onOptionsItemSelected(MenuItem item) {
Intent newActivity;
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_slidingmenu:
toggle();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class CalendarFragmentPagerAdapter extends FragmentPagerAdapter {
public CalendarFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
CalendarFragment fragment = new CalendarFragment();
Bundle args = new Bundle();
args.putInt("offset", position - MONTHS_LIMIT / 2);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return MONTHS_LIMIT;
}
}
}
CalendarFragment.java:
public class CalendarFragment extends Fragment
{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
int offset = args.getInt("offset"); //throws NullPointerException
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.simple_calendar_view, container, false);
.....
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("dummy", true);
}
}
The problem is at this line in the CalendarFragment:
int offset = args.getInt("offset");
It throws the error NullPointerException and debugging shows this is because Bundle args = getArguments() is null.
I tried to put the breakpoint at this line in the PagerAdapter:
Bundle args = new Bundle();
but it never reaches here and the application crashes throwing the NullPointerException.
Where am I going wrong?
Here
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main, new CalendarFragment())
.commit();
and here
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getPosition() == 0) {
CalendarFragment frag = new CalendarFragment();
ft.replace(R.id.main, frag);
} else {
ConverterFragment frag = new ConverterFragment();
ft.replace(R.id.main, frag);
}
}
you're just creating an empty CalendarFragment instance without any arguments.
So your activity launches, creating an empty Fragment without arguments, and then crashes when trying to get those

Categories