Getting Empty fragment after popbackstack - android

When I am pressing back button getting the fragment as empty. Not getting the previous fragment poped back. Tried many solutions but didn't work. What is the solution for this ? I have no idea how to solve this.
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = mHomeFragmentInstance;
break;
case 1:
fragment = mOrderFragmentInstance;
break;
case 2:
fragment = mOrdersheetFragmentInstance;
break;
case 3:
fragment = mMyorderwidgetFragmentInstance;
break;
case 4:
Intent intent=new Intent(this,LoginActivity.class);
startActivity(intent);
clearValues();
finish();
return;
default:
fragment = mHomeFragmentInstance;
break;
}
if (fragment != null) {
replaceFragment(fragment, position);
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void replaceFragment(Fragment fragment){
if (fragment != null) {
Fragment currentFragment = this.getSupportFragmentManager().findFragmentById(R.id.frame_container);
if(null != currentFragment ){
if(currentFragment.equals(fragment)){
return;
}else{
getSupportFragmentManager().beginTransaction().remove(currentFragment).commit();
}
}
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
public void replaceFragment(Fragment fragment, int position){
adapter.selectItem(position);
Log.i("TAG", "replaceFragment:"+fragment.getClass().getName()+":"+position);
replaceFragment(fragment);
Log.i("TAG", "Add"+fragment.getClass().getName()+"backStackFragment");
if(fragment.equals(mHomeFragmentInstance)){
Log.i("TAG", "clear backStackFragment");
backStackFragment.clear();
backStackFragment.add(mHomeFragmentInstance);
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(drawerContainer);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
//getActionBar().setTitle(Html.fromHtml("<font color='#983A1B'>" + title + "</font>"));
View view = getActionBar().getCustomView();
//((TextView)view.findViewById(R.id.title)).setText(Html.fromHtml("<font color='#983A1B'>" + title + "</font>"));
((TextView)view.findViewById(R.id.title)).setText(Html.fromHtml("<font color='"+ ApplicationInfo.getPlfColor(this)+"'>" + title + "</font>"));
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if(fm.getBackStackEntryCount() > 1) {
fm.popBackStack();
}else {
//super.onBackPressed();
finish();
}
}
}

Just add addToBackStack while you are transitioning between your fragments like below:
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();
if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.

Related

Save state of fragment when using bottom navigation

I am using bottom navigation drawer to switch between fragments, the problem is that every time I switch back to a fragment it gets recreated.
How can I save the state of fragment and resume it when switched back to it?
bottomNavigationBar.setTabSelectedListener(new BottomNavigationBar.OnTabSelectedListener(){
#Override
public void onTabSelected(int position) {
if (position==0){
loadFragment(new Daily());
}
if (position==1){
loadFragment(new Trending());
}
if (position==2){
loadFragment(new Random());
}
}
#Override
public void onTabUnselected(int position) {
}
#Override
public void onTabReselected(int position) {
}
});
private void loadFragment(Fragment fragment) {
// load fragment
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
transaction.attach( fragment);
transaction.addToBackStack(null);
transaction.commit();
}
The issue is that you are always creating a new Fragment on any onTabSelected. So in order to fix it, you need to work with your FragmentManager.
Possible solution: use the add and show/hide methods.
Example:
private static final String DAILY_TAG = BuildConfig.APPLICATION_ID + ".DAILY_TAG";
private static final String TRENDING_TAG = BuildConfig.APPLICATION_ID + ".TRENDING_TAG";
private static final String RANDOM_TAG = BuildConfig.APPLICATION_ID + ".RANDOM_TAG";
public void onTabSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
hideFragment(TRENDING_TAG)
hideFragment(RANDOM_TAG)
Fragment fragment = fragmentManager.findFragmentByTag(DAILY_TAG);
FragmentTransaction transaction = fragmentManager.beginTransaction()
if (fragment != null) {
transaction.show(fragment)
} else {
transaction.add(content.id, new Daily(), DAILY_TAG)
}
transaction.commitNow()
} else if (position == 1) {
hideFragment(DAILY_TAG)
hideFragment(RANDOM_TAG)
Fragment fragment = fragmentManager.findFragmentByTag(TRENDING_TAG);
FragmentTransaction transaction = fragmentManager.beginTransaction()
if (fragment != null) {
transaction.show(fragment)
} else {
transaction.add(content.id, new Trending(), TRENDING_TAG)
}
transaction.commitNow()
} else {
hideFragment(TRENDING_TAG)
hideFragment(DAILY_TAG)
Fragment fragment = fragmentManager.findFragmentByTag(RANDOM_TAG);
FragmentTransaction transaction = fragmentManager.beginTransaction()
if (fragment != null) {
transaction.show(fragment)
} else {
transaction.add(content.id, new Random(), RANDOM_TAG)
}
transaction.commitNow()
}
fragments.put(position, fragment);
loadFragment(fragment);
}
private void hideFragment(String tag) {
FragmentManager fragmentManager = getSupportFragmentManager()
Fragment currentFragment = fragmentManager.findFragmentByTag(tag)
if (currentFragment != null) {
fragmentManager.beginTransaction().hide(currentFragment).commitNow()
}
}
PS - The code can be optimized.

How to handle onBackPressed() in multiple fragment

I am Android beginner, I am developing an app in which I have used multiple fragments through an activity.
private void displaySelectedScreen(int itemId) {
Fragment fragment = null;
switch (itemId) {
case R.id.nav_home:
fragment = new HomeFragment();
break;
case R.id.nav_attendance:
fragment = new AttendanceFragment();
break;
case R.id.nav_notification:
fragment = new NotificationFragment();
break;
case R.id.nav_event:
fragment = new EventFragment();
break;
case R.id.nav_fee:
fragment = new FeesFragment();
break;
case R.id.nav_news:
fragment = new NewsFragment();
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frame_container, fragment);
ft.addToBackStack(null);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
and use an onBackPressed() method to close an app if the drawer is already close. Now I want to close an app if current fragment is HomeFragment and if current fragment is not HomeFragment then replace by HomeFragment. I don't know, how it does?
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
closeApp();
}
}
You can add tag to your fragment. in this way you will only have to check the tag name.
Fragment fragment = new Fragment();
getFragmentManager().beginTransaction()
.replace(R.id.FrameLayoutId,fragment,"TAG_NAME")
.addToBackStack("SOURCE_TAG_NAME").commit();
This is how to check your fragment tag, put this checking on your backpress method on the activity or in your closeApp() method
function void closeApp(){
Fragment fragment = getFragmentManager().findFragmentByTag("HomeActivity");
if (fragment != null) {
if(fragment.isVisible()){
HomeActivity.this.finish();
}
}
}
Use this code onBackPressed() method in NavigationActivity. I hope that can solve you.
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
Fragment f = getVisibleFragment();// to get which fragment now
if (f.getClass() != MainFragment.class) {
Fragment fragment = null;
try {
fragment = (Fragment) MainFragment.class.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit(); // this is your framelayout
}else {
super.onBackPressed();
}
}
}
getVisibleFragment() function
public Fragment getVisibleFragment() {
FragmentManager fragmentManager = NavigationActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if (fragments != null) {
for (Fragment fragment : fragments) {
if (fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
For simple, just go to your HomeFragment.java and edit the method onBackPressed() to exit the application using finish().
And for others Fragment.java, just use popBackStack() function, you can search for it here :
https://developer.android.com/reference/android/app/FragmentManager.html#popBackStack()
In your MainActivity class override onBackPressed and display dialogbox there like this:
#Override
public void onBackPressed() {
//show dialog box here
}
In each Fragment implement onResume() method with following code:
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
//homefragment class name
Class fragmentClass = HomeFragment.class;
try {
Fragment fragment = (Fragment) fragmentClass.newInstance();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
return false;
}
});
}

problems with Fragment onBackPress

in my navigation drawer there are 5 menu items.one of them is about us item.when I click on this item, I call AboutUsFragment and show it(its content is just a text).but when I click onBackPress, fragment is gone but its texts remains on my activity.how can I solve this problem?what`s it related to?!
select item of navigation drawer in my activity:
public void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
if (!Constants.login_state) {
fragment = new LoginFragment();
} else {
Logout();
}
break;
case 1:
Constants.filter = false;
Constants.gender = "-1";
fragment = new HomeFragment();
break;
case 2:
Constants.filter = false;
Constants.gender = "2";
StyleFragment.SortingMode = 1;
fragment = new StyleFragment();
break;
case 3:
Constants.filter = false;
Constants.gender = "1";
StyleFragment.SortingMode = 1;
fragment = new StyleFragment();
break;
case 4:
fragment = new AboutUsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentTransaction fragmentManager = getSupportFragmentManager().beginTransaction();
fragmentManager.replace(R.id.rl_container, fragment);
fragmentManager.addToBackStack(null);
fragmentManager.commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(Gravity.END);
} else {
Log.e("HomeActivity", "Error in creating fragment");
}
}
and AboutUsFragment:
public class AboutUsFragment extends android.support.v4.app.Fragment{
private View view;
private TextView about_us_fragment_text_view;
public static AboutUsFragment newInstance() {
AboutUsFragment fragment = new AboutUsFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view=inflater.inflate(R.layout.fragment_about_us, container, false);
Casting(view);
about_us_fragment_text_view.setText(getResources().getString(R.string.about_us));
ChangeUIFont.ChangeFont((ViewGroup) view, getContext());
return view;
}
//casting parameters
public void Casting(View v){
about_us_fragment_text_view= (TextView) v.findViewById(R.id.about_us_fragment_text_view);
}}
onBackPress in my activity:
#Override
public void onBackPressed() {
if (SearchOpened) {
lv_searchResult.setVisibility(View.GONE);
SearchOpened = false;
} else
super.onBackPressed();
}
---------------------------------------AfterSearching-------------------------------------------
Finally I found the solution!
in my fragment I added below code:
public static final String FRAGMENT_NAME = AboutUsFragment.class.getName();
and in my activity,I set the tag of fragment when I call it,instead of null!
fragmentManager.replace(R.id.rl_container, fragment,fragmentName);
used this method instead of onBackPressed
if you have toolbar then here is my solution,
type under the oncreate method below toolbar,
assert getSupportActionBar() != null;
// getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
and set this code in your manifest file for your fragment
<activity android:name=".yourCurrentFragment">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".whichActivityYouWantToGo" />
</activity>
Try this:
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}

onBackPressed closing app in fragments using NavigationDrawer

I'm using NavigationDrawer with some fragments, the problem is when I'm in a fragment and hit the back button, it makes the app close, then I have to open it again, put my username and password all over again to use the app, how can I prevent that from happen?
public class NavigationMain extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
}
public void setFragmentList(int posicao) {
Fragment fragment = null;
switch (posicao) {
case 0:
fragment = new MainFragment();
break;
case 1:
fragment = new MensagensFragment();
break;
case 2:
fragment = new EscolasFragment();
break;
case 3:
fragment = new AutorizadasFragment();
break;
case 4:
fragment = new CadastroFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
navigationAdapter.resetarCheck();
navigationAdapter.setChecked(posicao, true);
layoutDrawer.closeDrawer(linearDrawer);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
}
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
I think you missed to add the fragment transaction in your back stack. Try the following:
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();

Navigation drawer highlighting

I have a navigation drawer and i use selector to get the highligghted item of the list
<item
android:state_activated="true"
android:drawable="#color/pressed_color"/>
<item
android:drawable="#color/default_color" />
The problem is that i Override the backpressed to change my fragment to my main element like this:
#Override
public void onBackPressed()
{
onNavigationDrawerItemSelected(0);
onSectionAttached(1);
restoreActionBar();
now when i press back it changes the fragment but the highlighted item stays where I clicked last time.How can I achive to change the highlights postion too? with somethig like change the texts state somehow from code,but i create the navigation drawer elements with an adapter ...(i use the Android Studio sample )
#Override
public void onNavigationDrawerItemSelected(final int position) {
// update the main content by replacing fragments
final FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, KedvencekFragment.newInstance(position + 1))
// .addToBackStack(null)
.commit();
if(position==0)
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
fragmentManager.beginTransaction()
.replace(R.id.container, KedvencekFragment.newInstance(position + 1))
// .addToBackStack(null)
.commit();
}
}, 250);
}
and ` public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
case 5:
// mTitle = getString(R.string.title_section5);
break;
case 6:
mTitle = getString(R.string.title_section6);
break;
}
}`
EDIT:
You can access you NavigationDrawerFragment in your activity, you just need to make your selectItem(int position) method of the NavigationDrawerFragment public, like this:
...
publicvoid selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
...
And then in your onNavigationDrawerItemSelected method:
#Override
public void onNavigationDrawerItemSelected(final int position) {
// update the main content by replacing fragments
final FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, KedvencekFragment.newInstance(position + 1))
// .addToBackStack(null)
.commit();
if(position==0)
{
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
fragmentManager.beginTransaction()
.replace(R.id.container, KedvencekFragment.newInstance(position + 1))
// .addToBackStack(null)
.commit();
}
}, 250);
}
navigationDrawerFragment.selectItem(position);
}
i found it!!! had to change the selectItem() to public then call it in the onBackPressed like this!
#Override
public void onBackPressed()
{
if(mTitle!=getString(R.string.title_section1)) {
onNavigationDrawerItemSelected(0);
onSectionAttached(1);
mNavigationDrawerFragment.selectItem(0);
restoreActionBar();
}
else{
super.onBackPressed();
}
}

Categories

Resources