Search result for Question Taged android-fragments
There are some results of your Tag: android-fragments
    Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

    I have an application with three tabs.

    Each tab has its own layout .xml file. The main.xml has its own map fragment. It's the one that shows up when the application first launches.

    Everything works fine except for when I change between tabs. If I try to switch back to the map fragment tab, I get this error. Switching to and between other tabs works just fine.

    What could be wrong here?

    This is my main class and my main.xml, as well as a relevant class that I use ( you will also find the error log at the bottom )

    main class

    package com.nfc.demo;
    
    import android.app.ActionBar;
    import android.app.ActionBar.Tab;
    import android.app.Activity;
    import android.app.Fragment;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    import android.widget.Toast;
    
    public class NFCDemoActivity extends Activity {
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            ActionBar bar = getActionBar();
            bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
            bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    
            bar.addTab(bar
                    .newTab()
                    .setText("Map")
                    .setTabListener(
                            new TabListener<MapFragment>(this, "map",
                                    MapFragment.class)));
            bar.addTab(bar
                    .newTab()
                    .setText("Settings")
                    .setTabListener(
                            new TabListener<SettingsFragment>(this, "settings",
                                    SettingsFragment.class)));
            bar.addTab(bar
                    .newTab()
                    .setText("About")
                    .setTabListener(
                            new TabListener<AboutFragment>(this, "about",
                                    AboutFragment.class)));
    
            if (savedInstanceState != null) {
                bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
            }
            // setContentView(R.layout.main);
    
        }
    
        @Override
        protected void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
        }
    
        public static class TabListener<T extends Fragment> implements
                ActionBar.TabListener {
            private final Activity mActivity;
            private final String mTag;
            private final Class<T> mClass;
            private final Bundle mArgs;
            private Fragment mFragment;
    
            public TabListener(Activity activity, String tag, Class<T> clz) {
                this(activity, tag, clz, null);
            }
    
            public TabListener(Activity activity, String tag, Class<T> clz,
                    Bundle args) {
                mActivity = activity;
                mTag = tag;
                mClass = clz;
                mArgs = args;
    
                // Check to see if we already have a fragment for this tab,
                // probably from a previously saved state. If so, deactivate
                // it, because our initial state is that a tab isn't shown.
                mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
                if (mFragment != null && !mFragment.isDetached()) {
                    FragmentTransaction ft = mActivity.getFragmentManager()
                            .beginTransaction();
                    ft.detach(mFragment);
                    ft.commit();
                }
            }
    
            public void onTabSelected(Tab tab, FragmentTransaction ft) {
                if (mFragment == null) {
                    mFragment = Fragment.instantiate(mActivity, mClass.getName(),
                            mArgs);
                    ft.add(android.R.id.content, mFragment, mTag);
                } else {
                    ft.attach(mFragment);
                }
            }
    
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {
                if (mFragment != null) {
                    ft.detach(mFragment);
                }
            }
    
            public void onTabReselected(Tab tab, FragmentTransaction ft) {
                Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT)
                             .show();
            }
        }
    
    }
    

    main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >
    
        <fragment
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/mapFragment"
            android:name="com.google.android.gms.maps.MapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>
    

    relevant class ( MapFragment.java )

    package com.nfc.demo;
    
    import android.app.Fragment;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    public class MapFragment extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            super.onCreateView(inflater, container, savedInstanceState);
            return inflater.inflate(R.layout.main, container, false);
        }
    
        public void onDestroy() {
            super.onDestroy();
        }
    }
    

    error

    android.view.InflateException: Binary XML file line #7: 
         Error inflating class fragment
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
       at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
       at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
       at com.nfc.demo.MapFragment.onCreateView(MapFragment.java:15)
       at android.app.Fragment.performCreateView(Fragment.java:1695)
       at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
       at android.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1255)
       at android.app.BackStackRecord.run(BackStackRecord.java:672)
       at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
       at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
       at android.os.Handler.handleCallback(Handler.java:725)
       at android.os.Handler.dispatchMessage(Handler.java:92)
       at android.os.Looper.loop(Looper.java:137)
       at android.app.ActivityThread.main(ActivityThread.java:5039)
       at java.lang.reflect.Method.invokeNative(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:511)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
       at dalvik.system.NativeStart.main(Native Method)
    
    Caused by: java.lang.IllegalArgumentException: 
         Binary XML file line #7: Duplicate id 0x7f040005, tag null, or 
         parent id 0xffffffff with another fragment for 
         com.google.android.gms.maps.MapFragment
       at android.app.Activity.onCreateView(Activity.java:4722)
       at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
       ... 19 more
    
    Shayne Misti 2022-08-14
    java - How to send data from DialogFragment to a Fragment?

    I have a fragment that opens a Dialogfragment to get user input (a string, and an integer). How do I send these two things back to the fragment?

    Here is my DialogFragment:

    public class DatePickerFragment extends DialogFragment {
        String Month;
        int Year;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            getDialog().setTitle(getString(R.string.Date_Picker));
            View v = inflater.inflate(R.layout.date_picker_dialog, container, false);
    
            Spinner months = (Spinner) v.findViewById(R.id.months_spinner);
            ArrayAdapter<CharSequence> monthadapter = ArrayAdapter.createFromResource(getActivity(),
                    R.array.Months, R.layout.picker_row);
                  months.setAdapter(monthadapter);
                  months.setOnItemSelectedListener(new OnItemSelectedListener(){
                      @Override
                      public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int monthplace, long id) {
                          Month = Integer.toString(monthplace);
                      }
                      public void onNothingSelected(AdapterView<?> parent) {
                        }
                  });
    
            Spinner years = (Spinner) v.findViewById(R.id.years_spinner);
            ArrayAdapter<CharSequence> yearadapter = ArrayAdapter.createFromResource(getActivity(),
                 R.array.Years, R.layout.picker_row);
            years.setAdapter(yearadapter);
            years.setOnItemSelectedListener(new OnItemSelectedListener(){
              @Override
              public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int yearplace, long id) {
                  if (yearplace == 0){
                      Year = 2012;
                  }if (yearplace == 1){
                      Year = 2013;
                  }if (yearplace == 2){
                      Year = 2014;
                  }
              }
              public void onNothingSelected(AdapterView<?> parent) {}
            });
    
            Button button = (Button) v.findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v) {
                   getDialog().dismiss();
                }
            });
    
            return v;
        }
    }
    

    I need to send the data after the button click and before getDialog().dismiss()

    Here is the fragment that data needs to be sent to:

    public class CalendarFragment extends Fragment {
    int Year;
    String Month;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        int position = getArguments().getInt("position");
        String[] categories = getResources().getStringArray(R.array.categories);
        getActivity().getActionBar().setTitle(categories[position]);
        View v = inflater.inflate(R.layout.calendar_fragment_layout, container, false);    
    
        final Calendar c = Calendar.getInstance();
        SimpleDateFormat month_date = new SimpleDateFormat("MMMMMMMMM");
        Month = month_date.format(c.getTime());
        Year = c.get(Calendar.YEAR);
    
        Button button = (Button) v.findViewById(R.id.button);
        button.setText(Month + " "+ Year);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
               new DatePickerFragment().show(getFragmentManager(), "MyProgressDialog");
            }
        });
       return v;
      }
    }
    

    so once the user selects a date in the Dialogfragment, it must return the month and year.

    Then, the text on the button should change to the month and year specified by user.

    Mandlenkosi Shantelle 2022-08-20
    android - How to handle button clicks using the XML onClick within Fragments

    Pre-Honeycomb (Android 3), each Activity was registered to handle button clicks via the onClick tag in a Layout's XML:

    android:onClick="myClickMethod"
    

    Within that method you can use view.getId() and a switch statement to do the button logic.

    With the introduction of Honeycomb I'm breaking these Activities into Fragments which can be reused inside many different Activities. Most of the behavior of the buttons is Activity independent, and I would like the code to reside inside the Fragments file without using the old (pre 1.6) method of registering the OnClickListener for each button.

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Perform action on click
        }
    });
    

    The problem is that when my layout's are inflated it is still the hosting Activity that is receiving the button clicks, not the individual Fragments. Is there a good approach to either

    • Register the fragment to receive the button clicks?
    • Pass the click events from the Activity to the fragment they belong to?
    Pāvils Philomena 2022-08-14
    android - How to handle Handler messages when activity/fragment is paused

    Slight variation on my other posting

    Basically I have a message Handler in my Fragment which receives a bunch of messages that can result in dialogs being dismissed or shown.

    When the app is put into the background I get an onPause but then still get my messages coming through as one would expect. However, because I'm using fragments I can't just dismiss and show dialogs as that will result in an IllegalStateException.

    I can't just dismiss or cancel allowing state loss.

    Given that I have a Handler I'm wondering whether there is a recommended approach as to how I should handle messages while in a paused state.

    One possible solution I'm considering is to record the messages coming through while paused and play them back on an onResume. This is somewhat unsatisfactory and I'm thinking that there must be something in the framework to handle this more elegantly.

    Stefana Dominik 2022-08-16
    android - In Fragment on back button pressed Activity is blank

    I have an Activity and many fragments inflated in same FrameLayout

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    example: mainActivity > any fragment (press back button) > activity is blank.

    In onCreate:

    layout = (FrameLayout)findViewById(R.id.content_frame);
    layout.setVisibility(View.GONE);
    

    When I start a fragment:

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, profileFragment);
    ft.addToBackStack(null);
    ft.commit();
    layout.setVisibility(View.VISIBLE);
    

    I suppose I need to make the frameLayout's visibility GONE again on back pressed, but how do I do this?


    I tried onBackPressed and set layout.setVisibility(View.GONE); but I cannot go back through fragments, as I go directly to main page.

    Lotta Daisy 2022-08-17
    android - How do I open a new fragment from another fragment?

    I tried making a navigation between fragments. I've got the NewFragment.java with the new fragment working. My problem is:

    How do I make this onClickListener run NewFragment.java correctly?

    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
    
            Intent i = new Intent(getActivity(), NewFragment.class);
            startActivity(i);
    
        }
    });
    

    FYI: This is from inside a fragment (I don't know if that matters).

    Gaynor Valerianus 2022-08-17
    What is the benefit of using Fragments in Android, rather than Views?

    When developing for Android, you can set your target (or minimum) sdk to 4 (API 1.6) and add the android compatibility package (v4) to add support for Fragments. Yesterday I did this and successfully implemented Fragments to visualize data from a custom class.

    My question is this: what is the benefit for using Fragments as opposed to simply getting a View from a custom object, and still supporting API 1.5?

    For example, say I have the class Foo.java:

    public class Foo extends Fragment {
    
        /** Title of the Foo object*/
        private String title;
        /** A description of Foo */
        private String message;
    
        /** Create a new Foo
         * @param title
         * @param message */
        public Foo(String title, String message) {
            this.title = title;
            this.message = message;
        }//Foo
    
        /** Retrieves the View to display (supports API 1.5. To use,
         * remove 'extends Fragment' from the class statement, along with
         * the method {@link #onCreateView(LayoutInflater, ViewGroup, Bundle)}) 
         * @param context Used for retrieving the inflater */
        public View getView(Context context) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View v = inflater.inflate(R.layout.foo, null);
            TextView t = (TextView) v.findViewById(R.id.title);
            t.setText(this.title);
            TextView m = (TextView) v.findViewById(R.id.message);
            m.setText(this.message);
            return v;
        }//getView 
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
            View v = inflater.inflate(R.layout.foo, null);
            TextView t = (TextView) v.findViewById(R.id.title);
            t.setText(this.title);
            TextView m = (TextView) v.findViewById(R.id.message);
            m.setText(this.message);
            return v;
        }//onCreateView
    
    }//Foo
    

    Both methods are very simple to create and to work with in an Activity that, say, has a List<Foo> to display (for example, programmatically adding each to a ScrollView), so are Fragments really all that useful, or are they just an over-glorified simplification of getting a View, such as through the code above?

    Meino Suvi 2022-08-16
    java - onActivityResult() not called in new nested fragment API

    I have been using the new nested fragment API that Android includes in the support library.

    The problem that I am facing with nested fragments is that, if a nested fragment (that is, a fragment that has been added to another fragment via the FragmentManagerreturned by getChildFragmentManager()) calls startActivityForResult(), the nested fragment's onActivityResult() method is not called. However, both the parent fragment's onActivityResult() and activity's onActivityResult() do get called.

    I don't know if I am missing something about nested fragments, but I did not expect the described behavior. Below is the code that reproduces this problem. I would very much appreciate if someone can point me in the right direction and explain to me what I am doing wrong:

    package com.example.nestedfragmentactivityresult;
    
    import android.media.RingtoneManager;
    import android.os.Bundle;
    import android.content.Intent;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.Toast;
    
    public class MainActivity extends FragmentActivity
    {
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            this.getSupportFragmentManager()
                .beginTransaction()
                .add(android.R.id.content, new ContainerFragment())
                .commit();
        }
    
        public void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            super.onActivityResult(requestCode, resultCode, data);
    
            // This is called
            Toast.makeText(getApplication(),
                "Consumed by activity",
                Toast.LENGTH_SHORT).show();
        }
    
        public static class ContainerFragment extends Fragment
        {
            public final View onCreateView(LayoutInflater inflater,
                                           ViewGroup container,
                                           Bundle savedInstanceState)
            {
                View result = inflater.inflate(R.layout.test_nested_fragment_container,
                    container,
                    false);
    
                return result;
            }
    
            public void onActivityCreated(Bundle savedInstanceState)
            {
                super.onActivityCreated(savedInstanceState);
                getChildFragmentManager().beginTransaction()
                    .add(R.id.content, new NestedFragment())
                    .commit();
            }
    
            public void onActivityResult(int requestCode,
                                         int resultCode,
                                         Intent data)
            {
                super.onActivityResult(requestCode, resultCode, data);
    
                // This is called
                Toast.makeText(getActivity(),
                    "Consumed by parent fragment",
                    Toast.LENGTH_SHORT).show();
            }
        }
    
        public static class NestedFragment extends Fragment
        {
            public final View onCreateView(LayoutInflater inflater,
                                           ViewGroup container,
                                           Bundle savedInstanceState)
            {
                Button button = new Button(getActivity());
                button.setText("Click me!");
                button.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
                        startActivityForResult(intent, 0);
                    }
                });
    
                return button;
            }
    
            public void onActivityResult(int requestCode,
                                         int resultCode,
                                         Intent data)
            {
                super.onActivityResult(requestCode, resultCode, data);
    
                // This is NOT called
                Toast.makeText(getActivity(),
                    "Consumed by nested fragment",
                    Toast.LENGTH_SHORT).show();
            }
        }
    }
    

    test_nested_fragment_container.xml is:

    <?xml version="1.0" encoding="utf-8"?>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    
    </FrameLayout>
    
    Emmy Kanani 2022-08-18
    android - How to implement a ViewPager with different Fragments / Layouts

    When I start an activity which implements viewpager, the viewpager created various fragments. I want to use different layouts for each fragment, but the problem is that viewpager shows only two layouts at the max (second layout on all of the remaining fragments after 1).

    Here is the code for SwipeActivity which implements the viewpager :

    public class SwipeActivity extends FragmentActivity
    {
    
        MyPageAdapter pageAdapter;
    
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_swipe);
            pageAdapter = new MyPageAdapter(getSupportFragmentManager());
            ViewPager pager=(ViewPager)findViewById(R.id.pager);
            pager.setAdapter(pageAdapter);
            ActionBar bar = getActionBar();
            bar.setDisplayHomeAsUpEnabled(true);
        }
        /**
        * Custom Page adapter
        */
        private class MyPageAdapter extends FragmentPagerAdapter
        {
            public MyPageAdapter(FragmentManager fm)
            {
                super(fm);
            }
            @Override
            public int getCount()
            {
                return 5;
            }
            @Override
            public Fragment getItem(int position)
            {
                switch(position)
                {
                    case 0: return new MyFragment();
                    case 1: return SecondFragment.newInstance("asdasd");
                    default : return RamFragment.newInstance("s");
                }
            }
         }
    }
    

    Here is the code for the fragments

    public class MyFragment extends Fragment
    {
       @Override
       public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup,    Bundle paramBundle)
       {
         return paramLayoutInflater.inflate(R.layout.processorlayout, paramViewGroup, false);
       }
    }
    

    I used 5 fragments like this, all having different layouts, but the viewpager shows only 2 at the max.

    EDIT : code for SecondFragment

    public class SecondFragment extends Fragment
    {
       public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
    
      public static final SecondFragment newInstance(String paramString)
      {
        SecondFragment f = new SecondFragment();
        Bundle localBundle = new Bundle(1);
        localBundle.putString("EXTRA_MESSAGE", paramString);
        f.setArguments(localBundle);
        return f;
      }
    
      @Override
      public View onCreateView(LayoutInflater paramLayoutInflater, ViewGroup paramViewGroup, Bundle paramBundle)
      {
         return paramLayoutInflater.inflate(R.layout.motherboardlayout, paramViewGroup, false);
      }
    }
    
    Bóthildr Vilma 2022-08-15
    android - getView returning null when fragment has been created from an activity

    I have a working tablet application which I am now trying to make work on phones too. On a table there is two fragments on the screen a list fragment and a details fragment. When on a phone the list fragment appears and creates a new activity when a list item is pressed. This activity simply creates the fragment in the onCreate() method and commits it to the screen as follows.

    // Place an DeallDetailsFragment as our content pane
    DealDetailsFragment f = new DealDetailsFragment();
    getFragmentManager().beginTransaction().add(android.R.id.content, f).commit();
    getFragmentManager().executePendingTransactions();
    

    This is working as expected however from within this activity I need to tell the fragment what details to load and display. In my DealDetailsFragment class I have a updateDeal() method which updates the content as follows.

    if (deal==null) { // could be null if user presses the loading deals list item before it loads
        return;
    }
    this.deal=deal;
    if (dealTitle==null) { // get the view objects only once
        holder = new ViewHolder();  
        holder.dealHeat=(TextView) getView().findViewById(R.id.dealDetails_heat_textView);
        holder.dealPrice=(TextView) getView().findViewById(R.id.dealDetails_price_textView);
        holder.dealRetailer=(TextView) getView().findViewById(R.id.dealDetails_retailer_textView);
        holder.dealTitle=(TextView) getView().findViewById(R.id.dealDetails_title_textView);
        holder.dealDesc=(TextView) getView().findViewById(R.id.dealDetails_desc_textView);
        holder.goToButton= (LinearLayout) getView().findViewById(R.id.dealDetails_goToDeal);
        holder.dealImage=(ImageView) getView().findViewById(R.id.dealDetails_imageView);
        holder.postedBy=(TextView) getView().findViewById(R.id.dealDetails_poster_textView);
        holder.datePosted=(TextView) getView().findViewById(R.id.dealDetails_date_textView);
    

    getView() is returning null when the application is ran on a phone where there is only a single fragment shown.

    Any ideas? Unfortunately, there is not many fragment examples available online.

    Lenuța Robert 2022-08-19
    android - How can I switch between two fragments, without recreating the fragments each time?

    I'm working on an android application, that uses a navigation drawer to switch between two fragments. However, each time I switch, the fragment is completely recreated.

    Here is the code from my main activity.

    /* The click listener for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }
    
    private void selectItem(int position) {
        android.support.v4.app.Fragment fragment;
        String tag;
        android.support.v4.app.FragmentManager; fragmentManager = getSupportFragmentManager();
    
        switch(position) {
            case 0:
                if(fragmentManager.findFragmentByTag("one") != null) {
                    fragment = fragmentManager.findFragmentByTag("one");
                } else {
                    fragment = new OneFragment();
                }
                tag = "one";
                break;
            case 1:
                if(fragmentManager.findFragmentByTag("two") != null) {
                    fragment = fragmentManager.findFragmentByTag("two");
                } else {
                    fragment = new TwoFragment();
                }
                tag = "two";
                break;
        }
    
        fragment.setRetainInstance(true);
        fragmentManager.beginTransaction().replace(R.id.container, fragment, tag).commit();
    
        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mNavTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }
    

    I've set up some debug logging, and every time selectItem is called, one fragment is destroyed, while the other is created.

    Is there any way to prevent the fragments from being recreated, and just reuse them instead?

    Vitalija Dimas 2022-08-20
    android - How to pass data between fragments

    Im trying to pass data between two fragmens in my program. Its just a simple string that is stored in the List. The List is made public in fragments A, and when the user clicks on a list item, I need it to show up in fragment B. The content provider only seems to support ID's, so that will not work. Any suggestions?

    Wangchuk Lidochka 2022-08-17
    Separate Back Stack for each tab in Android using Fragments

    I'm trying to implement tabs for navigation in an Android app. Since TabActivity and ActivityGroup are deprecated I would like to implement it using Fragments instead.

    I know how to set up one fragment for each tab and then switch fragments when a tab is clicked. But how can I have a separate back stack for each tab?

    For an example Fragment A and B would be under Tab 1 and Fragment C and D under Tab 2. When the app is started Fragment A is shown and Tab 1 is selected. Then Fragment A might be replaced with Fragment B. When Tab 2 is selected Fragment C should be displayed. If Tab 1 is then selected Fragment B should once again be displayed. At this point it should be possible to use the back button to show Fragment A.

    Also, it is important that the state for each tab is maintained when the device is rotated.

    BR Martin

    Eudocia Girolamo 2022-08-15
    android - OnCreateView called multiple times / Working with ActionBar and Fragments

    I switched part of my App from Activities to Fragments so that I can use the neat ActionBar tabs.

    However, after completing the transition I ran into an issue: whenever I switch to another tab, that Fragment gets created all over again. Both onCreate and onCreateView get called every time I get to a tab.

    I have 4 tabs, each of which is meant to open one of these fragments:

    Fragment ShopFragment = new WebActivity();
    Fragment SearchFragment = new SearchActivity(context);
    Fragment StoreFragment = new StoreLocatorActivity(context, this);
    Fragment BlogsFragment = new BlogsActivity(context, this);
    

    Here's my code for the listener:

        class MyTabsListener implements ActionBar.TabListener {
            public Fragment fragment;
    
            public MyTabsListener(Fragment fragment) {
                this.fragment = fragment;
            }
    
            @Override
            public void onTabReselected(Tab tab, FragmentTransaction ft) {
                ft.hide(fragment);
            }
    
            @Override
            public void onTabSelected(Tab tab, FragmentTransaction ft) {
                ft.replace(R.id.fragment_container, fragment);
            }
    
            @Override
            public void onTabUnselected(Tab tab, FragmentTransaction ft) {          
    
            }
    
        }
    

    Could someone please point me in the right direction?

    Benjamín Murali 2022-08-21
    android - Getting Binary XML file line #141: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference

    Logcat

    05-11 19:14:52.567 4489-4489/? E/AndroidRuntime: 
    FATAL EXCEPTION: main                                                  
           Process: com.grab.deals.dealcart, PID: 4489
           java.lang.RuntimeException: Unable to start activity ComponentInfo{com.grab.deals.dealcart/com.grab.deals.dealcart.Full_view.Full_view}: android.view.InflateException: Binary XML file line #141: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
           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: android.view.InflateException: Binary XML file line #141: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
           at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
           at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
           at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
           at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
           at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
           at com.grab.deals.dealcart.Full_view.Full_view.onCreate(Full_view.java:13)
           at android.app.Activity.performCreate(Activity.java:6237)
           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
           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 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
           at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:738)
           at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
           at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
           at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
           at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
           at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
           at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
           at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
           at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
           at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
           at android.view.LayoutInflater.rInflate(LayoutInflater.java:838)
           at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
           at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
           at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
           at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
           at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284) 
           at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143) 
           at com.grab.deals.dealcart.Full_view.Full_view.onCreate(Full_view.java:13) 
           at android.app.Activity.performCreate(Activity.java:6237) 
           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) 
           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) 
           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) 
    

    ExtendView.xml

        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/activity_full_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="5dp">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
            <ImageView
                android:layout_width="match_parent"
                android:layout_height="300dp"
    
                android:id="@+id/img"/>
            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Designer shirt"
                    android:textSize="15dp"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000"/>
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="12dp"
                        android:text="Speatial Price"
                        android:layout_marginLeft="10dp"
                        android:textColor="#34a853"/>
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_marginLeft="5dp"
                        android:layout_height="wrap_content"
                        android:textColor="#000"
                        android:text="Ends in few hours"
                       />
                </LinearLayout>
                <LinearLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="20dp"
                    android:text="25,000"
                    android:layout_marginLeft="10dp"
                    android:textColor="#000"/>
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:layout_height="wrap_content"
                        android:textColor="@color/colorPrimary"
                        android:text="70%off"
                        android:textSize="15dp"/>
                </LinearLayout>
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_marginLeft="10dp"
                    android:layout_height="wrap_content"
                    android:textColor="#34a853"
                    android:text="4.1"/>
    
                <ImageView
                    android:layout_width="15dp"
                    android:layout_height="15dp"
                    app:srcCompat="@drawable/ic_star_border_black_24dp"/>
                </LinearLayout>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_gravity="center"
        android:layout_marginBottom="5dp">
    
    
     <ImageView
         android:layout_width="30dp"
         android:layout_height="30dp"
         app:srcCompat="@drawable/copy"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#000"
            android:layout_marginLeft="10dp"
            android:text="Copy Coupon"
            android:textSize="20sp"
            />
    
    
    </LinearLayout>
            </LinearLayout>
    
        </android.support.v7.widget.CardView>
    
    
            <android.support.v7.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                >
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Details"
        android:layout_margin="20dp"
        android:textSize="20sp"
        android:textColor="#000"/>
                    <view
                        android:layout_width="match_parent"
                        android:layout_height="1dp"/>
    
                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textSize="17sp"
                        android:textColor="#000"
                        android:layout_margin="20dp"
                        android:text="Heighlets \n*shgdfshdflshflsjh\n*a;sjkdfjshgf"/>
                </LinearLayout>
            </android.support.v7.widget.CardView>
    
                <android.support.v7.widget.CardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    >
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">
                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:text="Terms and Conditions"
                            android:layout_margin="20dp"
                            android:textSize="20sp"
                            android:textColor="#000"/>
                        <view
                            android:layout_width="match_parent"
                            android:layout_height="1dp"/>
    
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textSize="17sp"
                            android:textColor="#000"
                            android:layout_margin="20dp"
                            android:text="Heighlets \n*shgdfshdflshflsjh\n*a;sjkdfjshgf"/>
                    </LinearLayout>
                </android.support.v7.widget.CardView>
    
                <android.support.v7.widget.CardView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dp"
                    >
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">
                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:text="Ratings &amp; Reviews"
                            android:layout_margin="20dp"
                            android:textSize="20sp"
                            android:textColor="#000"/>
                        <view
                            android:layout_width="match_parent"
                            android:layout_height="1dp"/>
                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:layout_margin="20dp"
                            android:orientation="vertical">
                        <LinearLayout
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_gravity="center"
                            android:orientation="horizontal">
    
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="4.1"
                                android:layout_marginRight="10dp"
                                android:textSize="40sp"/>
                            <ImageView
                                android:layout_width="50dp"
                                android:layout_height="50dp"
                                app:srcCompat="@drawable/ic_star_border_black_24dp"/>
                        </LinearLayout>
                            <TextView
                                android:layout_width="wrap_content"
                                android:layout_height="wrap_content"
                                android:text="1,500 Reviews"
                                />
                        </LinearLayout>
    
                               </LinearLayout>
                </android.support.v7.widget.CardView>
        </LinearLayout>
            </ScrollView>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="#fff"
        android:layout_alignParentBottom="true"
        android:gravity="center">
        <Button
            android:layout_width="180dp"
            android:layout_height="50dp"
            android:text="Share"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"/>
    
        <Button
            android:layout_width="180dp"
            android:layout_height="50dp"
            android:text="Visit"
            android:textColor="#fff"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:background="@color/colorPrimary"/>
    
    
    
    </LinearLayout>
    
    
    </RelativeLayout>
    

    Full_View.java

    public class Full_View extends Fragment {
    
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View rootview = inflater.inflate(R.layout.activity_full_view,container,false);
            return rootview;
        }
    
    }
    
    Margrit Simon 2022-08-19
    android - Proper way to give initial data to fragments?

    So I've learned that I need an empty constructor in order for my fragments not to crash on reinitialization. My problem is that I use lists of data for my fragments when they are initialized (at least some of them). So what would be a good way to start new fragments with a list of data. Should I in the OnCreate() make a getData method which gets the data from some other source or what would be a proper approach?

    Feeding the bundle with data really wouldn't be a very good approach as I have a lot of data.

    So let's take a case (I understand it tons better that way).

    When a user clicks on a button the fragment is started. What I used to do was creating a new fragment this way:

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        
        fragmentTransaction.replace(R.id.center_container, new DetailFragment(item));
        fragmentTransaction.addToBackStack(DETAIL_TAG);
        
        fragmentTransaction.commit();
    

    Then in my fragment:

    public DetailFragment(EventItem item) {
        mItem = item;
        mPlaces = Database.getContainerPlaces(getActivity()).getValidItems();
    }
    

    I can't give all the data to a bundle, so that wouldn't work. So what should I do?

    A: Should I initialize the fragment with the empty constructor and then from my activity use setters to set the data directly in the fragment? However, won't I be missing data if the user presses home, Android closes the fragment and the user later returns?

    B: Should I initialize the fragment with factory pattern and call setRetainInstance(true), give the fragment a key for identifying the data, and then letting the fragment fetch the data needed in onCreateView from some third source?

    C: Should I just make an empty constructor and then in onCreate() fetch the data needed for the fragment?

    It should be noted that the app is locked in portrait so the issue is primarily with maintaining the objects when Android closes and the user restarts.

    Filibert Nosizwe 2022-08-19
    android - Fragment in ViewPager not restored after popBackStack

    Problem

    A Fragment is not reattached to its hosting ViewPager after returning from another fragment.

    Situation

    One Activity hosting a Fragment whose layout holds a ViewPager (PageListFragment in the example below). The ViewPager is populated by a FragmentStateViewPagerAdapter. The single Fragments hosted inside the pager (PageFragment in the example below) can open sub page lists, containing a new set of pages.

    Behaviour

    All works fine as long as the back button is not pressed. As soon as the user closes one of the sub PageLists the previous List is recreated, but without the Page that was displayed previously. Swiping through the other pages on the parent PageList still works.

    Code

    A sample application can be found on github:

    Activity

    public class MainActivity extends FragmentActivity {
    
    private static final String CURRENT_FRAGMENT = MainActivity.class.getCanonicalName() + ".CURRENT_FRAGMENT";
    
    public static final String ARG_PARENTS = "Parents";
    
    public void goInto(String mHostingLevel, String mPosition) {
        Fragment hostingFragment = newHostingFragment(mHostingLevel, mPosition);
        addFragment(hostingFragment);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addBaseFragment();
    }
    
    private void addBaseFragment() {
        Fragment hostingFragment = newHostingFragment("", "");
        addFragment(hostingFragment);
    }
    
    private Fragment newHostingFragment(String mHostingLevel, String oldPosition) {
        Fragment hostingFragment = new PageListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARENTS, mHostingLevel + oldPosition +" > ");
        hostingFragment.setArguments(args);
        return hostingFragment;
    }
    
    private void addFragment(Fragment hostingFragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragmentSpace, hostingFragment, CURRENT_FRAGMENT);
        transaction.addToBackStack(null);
        transaction.commit();
    }
    
    }
    

    PageListFragment

    public class PageListFragment extends Fragment {
    
    private String mParentString;
    
    public PageListFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_hosting, container, false);
    }
    
    @Override
    public void onResume() {
        mParentString = getArguments().getString(MainActivity.ARG_PARENTS);
        ViewPager viewPager = (ViewPager) getView().findViewById(R.id.viewPager);
        viewPager.setAdapter(new SimpleFragmentStatePagerAdapter(getFragmentManager(),mParentString));
        super.onResume();
    }
    
    private static class SimpleFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
    
        private String mHostingLevel;
    
        public SimpleFragmentStatePagerAdapter(FragmentManager fm, String hostingLevel) {
            super(fm);
            this.mHostingLevel = hostingLevel;
        }
    
        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            PageFragment pageFragment = new PageFragment();
            Bundle args = new Bundle();
            args.putString(MainActivity.ARG_PARENTS, mHostingLevel);
            args.putInt(PageFragment.ARG_POSITION, position);
            pageFragment.setArguments(args);
            return pageFragment;
        }
    
        @Override
        public int getCount() {
            return 5;
        }
    }
    }
    

    PageFragment

    public class PageFragment extends Fragment {
    
    public static final String ARG_POSITION = "Position";
    
    private String mHostingLevel;
    private int mPosition;
    
    public PageFragment() {
        // Required empty public constructor
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_page, container, false);
        setupTextView(contentView);
        setupButton(contentView);
        return contentView;
    }
    
    private void setupTextView(View contentView) {
        mPosition = getArguments().getInt(ARG_POSITION);
        mHostingLevel = getArguments().getString(MainActivity.ARG_PARENTS);
        TextView text = (TextView) contentView.findViewById(R.id.textView);
        text.setText("Parent Fragments " + mHostingLevel + " \n\nCurrent Fragment "+ mPosition);
    }
    
    private void setupButton(View contentView) {
        Button button = (Button) contentView.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openNewLevel();
            }
        });
    }
    
    protected void openNewLevel() {
        MainActivity activity = (MainActivity) getActivity();
        activity.goInto(mHostingLevel, Integer.toString(mPosition));
    }
    
    }
    
    Lotta Daisy 2022-08-19
    android - How to update a menu item shown in the ActionBar?

    I have an Activity that has 2 fragments. Both are ListFragments and both contribute MenuItems to the Menu. I have one MenuItem that I've set the attribute android:showAsAction to have it show as a button on the ActionBar. Which works fine.

    Now the MenuItem is state dependent. It's a Pause/Resume menu option for pausing and resuming a queue. My problem is I can't figure out how to set it's initial statue when the Fragment is created.

    It's state is dependent on the whether the queue is paused or not. So I have an AsyncTask that gets the queue and sets a boolean (paused) based on the state of the queue. I'm calling onPrepareOptionsMenu to set the text for the Pause menu item based on the last known state of the queue and this works great if I leave the MenuItem in the actual menu. You tap the menu icon and onPrepareOptionsMenu is fired and the menu is updated before it's displayed.

    The problem is, if I put that same MenuItem on the ActionBar (showAsAction), how can I force it to update without having to call onPrepareOptionsMenu? I need to be able to do this because on first launch of the app, I send a request to get the queue, but the task returns after the ActionBar is setup and displayed. I've created a handler in my fragment that gets called every time I get a queue update, but from there, how can I update the text for my MenuItem on the ActionBar? I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.

    Rob W.

    Magdalena Naseer 2022-08-17
    android - When a Fragment is replaced and put in the back stack (or removed) does it stay in memory?

    Is the behavior similar to the way Activities work? For example with Activities it works like this:

    Activity A starts Activity B, while B is on screen, the system is able to remove A from memory if it is needed by the system. Upon pressing BACK, A will be recreated into memory as if it never left in the first place.

    I have looked for a clear explanation of what happens memory wise with Fragments and haven't found anything. Does it work the same way? For example:

    Activity C has Fragment F in its layout. Then, at some point F is replaced by Fragment G, but F is kept in its back stack.

    Will F stay in memory until the C is killed or can it be removed by the system as needed?

    Really what I am asking is whether or not I run the risk of running out of memory if I have a back stack of complicated Fragments in a single Activity?

    Marko Yalwa 2022-08-18
    Fragments deprecated in Android P

    I was looking at the documentation and found this

    This class was deprecated in API level P.

    Why are fragments deprecated in android P?

    Magdalena Naseer 2022-08-19
    android - How do I add a Fragment to an Activity with a programmatically created content view

    I want to add a Fragment to an Activity that implements its layout programmatically. I looked over the Fragment documentation but there aren't many examples describing what I need. Here is the type of code I tried to write:

    public class DebugExampleTwo extends Activity {
    
        private ExampleTwoFragment mFragment;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            FrameLayout frame = new FrameLayout(this);
            if (savedInstanceState == null) {
                mFragment = new ExampleTwoFragment();
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.add(frame.getId(), mFragment).commit();
            }
    
            setContentView(frame);
        }
    }
    

    ...

    public class ExampleTwoFragment extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, 
                                 ViewGroup container, 
                                 Bundle savedInstanceState) {
            Button button = new Button(getActivity());
            button.setText("Hello There");
            return button;
        }
    }
    

    This code compiles but crashes at start, probably because my FragmentTransaction.add() is incorrect. What is the correct way to do this?

    Yusup Waldemar 2022-08-14
    android - Fragment re-created on bottom navigation view item selected

    Following is my code for bottom navigation view item selected

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {  
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        Fragment fragment = null;
        switch (item.getItemId()) {
            case R.id.action_one:
                // Switch to page one
                fragment = FragmentA.newInstance();
                break;
            case R.id.action_two:
                // Switch to page two
                fragment = FragmentB.newInstance();
                break;
            case R.id.action_three:
                // Switch to page three
                fragment = FragmentC.newInstance();
                break;
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment,"TAG").commit();
        return true;
    }
    });
    

    Now my problem is every time fragment is re-created and don't want fragment to be recreated every time I also tried adding addToBackStack(null) but it this case on back button press keeps popping fragments from stack which I don't want.

    Is there any way to display fragments on bottom navigation bar selected without re-creating fragment

    Sveinn Erland 2022-08-19
    How to open fragment page, when pressed a notification in android

    I am trying to open a fragment when I press a notification in the notification bar. My app structure is:

    • a base activity with a nav drawer menu
    • some fragment that are opened from menu

      b.setOnClickListener(new OnClickListener() {
      
              @SuppressWarnings({ "deprecation", "static-access" })
              public void onClick(View v) {
      
              w_nm=(NotificationManager) getActivity().getSystemService(getActivity().NOTIFICATION_SERVICE);
      
               Notification notify=new Notification(R.drawable.notnificationlogo,waternoti,System.currentTimeMillis());
      
               Intent notificationIntent = new Intent(getActivity(), Abc.class);
      
      
      
               PendingIntent pending=PendingIntent.getActivity(getActivity(), 0,notificationIntent, 0);
      
      
               notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                       | Intent.FLAG_ACTIVITY_SINGLE_TOP );
      
              notify.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
      
                 notify.setLatestEventInfo(getActivity(),waternoti,waternoti1, pending);
      
               w_nm.notify(0, notify);
      

    Can anyone tell me how to link with next fragment page (the present code is in class that extends fragment)

    Amalia Sopheap 2022-08-19
    java - Request runtime permissions from v4.Fragment and have callback go to Fragment?

    I'm having a weird issue that is causing a conflict. I had to switch to native Fragments to fix it, but there are bugs with that.

    My original problem: I have a navigation drawer setup with v4 Fragments. To ask for permission in one of my Fragments I call ActivityCompat.requestPermissions(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION, 1); The prompt shows up just fine, but when I accept or deny the permission, nothing happens. The callback onRequestPermissionsResult() is never called. Instead it gets called in the Activity that my Fragments are attached to. Useless to me, I need the callback to work in the Fragment.

    With this in mind I was told that I need to use FragmentCompat, but that only works with native Fragments (v13+), so I changed navigation drawer to work from native Fragments instead of the v4 support library Fragments. However, because I'm using AppCompatActivity, certain things do not work, like addToBackStack() and going back to a previous fragment.

    Long story short, does anyone know how I can use the v4.Fragment and still call for permission in the Fragment and get the callback to be in the Fragment? I feel like this is a bug in Android that hasn't been addressed but I'm not 100%.

    Let me know if you need to see my code, it's just the standard methods that you need for runtime permissions, I would like to work with v4 Fragments though which doesn't work from my understanding.

    Louella Eleonora 2022-08-19
    android - how to use setSupportActionBar in fragment

    I need to use the setSupportActionBar in fragment which I am unable to also I am unable to use setContentView please to help with it also Thankyou in advance the related code is given

    public class StudentrFragment extends Fragment {
            Toolbar toolbar;
            TabLayout tabLayout;
            ViewPager viewPager;
            ViewPagerAdapter viewPagerAdapter;
    
    
            public StudentrFragment() {
                // Required empty public constructor
            }
    
    
            @Override
            public void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
                setContentView(R.layout.tabbar_layout);
                toolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(toolbar); 
                tabLayout = (TabLayout) findViewById(R.id.tabLayout);
                viewPager = (ViewPager) findViewById(R.id.viewPager);
                viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
                viewPagerAdapter.addFragments(new CivilFragment(),"Civil Dept");
                viewPagerAdapter.addFragments(new ComputerFragment(),"CSE Dept");
                viewPagerAdapter.addFragments(new EeeFragment(),"EEE Dept");
                viewPagerAdapter.addFragments(new EceFragment(),"ECE Dept");
                viewPager.setAdapter(viewPagerAdapter);
                tabLayout.setupWithViewPager(viewPager);
    
            }
    
        }
    
    Elise Pankaj 2022-08-21
    android - Navigating back to FragmentPagerAdapter -> fragments are empty

    I have a Fragment (I'll call it pagerFragment) that is added to the backstack and is visible. It holds a viewPager with a FragmentPagerAdapter. The FragmentPagerAdapter holds (let's say) two fragments: A and B.

    First adding of the fragments works great.

    Fragment A has a button that once clicked, adds a fragment (C) to the backstack.

    The problem is this: if I add that fragment (C), and then click back, the pagerAdapter is empty, and I cannot see any fragments inside.

    If I use a hack, and destroy the children fragments (A and B) in the pagerFragments onDestroyView(), this solves the problem, although I don't wan't to use this hack.

    Any ideas what the issue could be?

    Filibert Nosizwe 2022-08-19
    android - How to add a fragment to a programmatically generated layout?

    I have the following code working which generates fragments, but only if I am adding them to a linear layout which exists in my XML file.

    LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
    FragmentManager fragMan = getFragmentManager();
    FragmentTransaction fragTransaction = fragMan.beginTransaction();
    
    Fragment myFrag= new ImageFragment();
    fragTransaction.add(R.id.foodItemActvity_linearLayout_fragments, myFrag , "fragment" + fragCount);
    fragTransaction.commit();
    

    Now what if I want to add that fragment to a linear layout that does not already exist in the XML file such as

    LinearLayout rowLayout = new LinearLayout();
    

    Part 2:

        Fragment frag1 = generateAppropriateFragment(type1);
        Fragment frag2 = generateAppropriateFragment(type2);
    
        LinearLayout fragmentsLayout = (LinearLayout) findViewById(R.id.foodItemActvity_linearLayout_fragments);
        LinearLayout rowLayout = new LinearLayout(this);
        rowLayout.setId(12345); // add counter to end
    
        fragmentsLayout.addView(rowLayout);     
        getFragmentManager().beginTransaction().add(rowLayout.getId(), frag1, "fragment_grandchild" + fragCount).commit();
        fragCount++;
        getFragmentManager().beginTransaction().add(rowLayout.getId(), frag2, "fragment_grandchild" + fragCount).commit();
        fragCount++;
    
    Gaynor Valerianus 2022-08-19
    java - Setting Custom ActionBar Title from Fragment

    In my Main FragmentActivity, I setup my custom ActionBar title like this:

        LayoutInflater inflator = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflator.inflate(R.layout.custom_titlebar, null);
    
        TextView tv = (TextView) v.findViewById(R.id.title);
        Typeface tf = Typeface.createFromAsset(this.getAssets(),
                "fonts/capsuula.ttf");
        tv.setTypeface(tf);
        tv.setText(this.getTitle());
    
        actionBar.setCustomView(v);
    

    This works perfect. However, once I open other Fragments, I want the title to change. I am not sure how to access the Main Activity to do this? In the past, I did this:

    ((MainFragmentActivity) getActivity()).getSupportActionBar().setTitle(
                catTitle);
    

    Can someone advise on the proper method?

    XML:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent" >
    
        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:ellipsize="end"
            android:maxLines="1"
            android:text=""
            android:textColor="#fff"
            android:textSize="25sp" />
    
    </RelativeLayout>
    
    Vimal Anderson 2022-08-16
    android - Nested scrollview automatically scrolls to bottom

    I have a GridView within a NestedScrollView. I have used the code below to resize the GridView whenever the content of the GridView is changed. This works fine, however the NestedScrollView scrolls to the very bottom when I swipe from fragment 3 of the app back to fragment 2 (where the NestedScrollView resides). This doesn't happen when swiping from fragment 1 to fragment 2, oddly. It also doesn't happen directly after resizing the GridView.

    How can I repress the NestedScrollView from scrolling to the bottom?

    private static void resizeGridView(GridView gridView, int items, int columns) {
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = singleGridHeight * items;
        gridView.setLayoutParams(params);
        gridView.requestLayout();
    }
    

    The following system methods are called when swiping between fragments: enter image description here

    Mandlenkosi Shantelle 2022-08-22
    android - How to close the current fragment by using Button like the back button?

    I have try to close the current fragment by using Imagebutton.

    I am in Fragment-A and it will turn to the Fragment-B when I click the button.

    And when I click the button at Fragment-B , it will turn to the Fragment-C and close the Fragment-B.

    If I click the back button at Fragment-C , it will back to the Fragment-A.

    The code I have try is like the following

    camera_album = (ImageButton) view.findViewById(R.id.camera_album);
    
    camera_album.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
    
                        closefragment();
            Fragment fragment = FileBrowserFragment.newInstance(null, null, null) ;
            MainActivity.addFragment(LocalFileBrowserFragment.this, fragment) ;
    
    
        }
    });
    
    private void closefragment() {
        getActivity().getFragmentManager().beginTransaction().remove(this).commit();
    }
    

    When I click the back button at fragment-B , it turn to the Fragment-C.

    But when I click the back button on Fragment-C , it doesn't back to the Fragment-A. It back to the empty background. If I want to back to Fragment-A , I have to click the back button once again.

    SO , it seem doesn't close the current fragment complete.

    How to finish the current fragment like the back button of Android ?

    Urbain Vidar 2022-08-16