I have main activity that contains major parameters that I need to pass to all the application activities. (username - User Privilege - Team .. ETC).
I know how to do that except in an activity that contains three fragments, that are displayed using pager and tablayout. How can I pass the parameters to all these fragments? .. should I pass it to the activity then pass it to the three fragments as a second step? if yes, how can I pass to the fragments in the below code:
Second Activity Java:
public class DCODatabase extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dcodatabase);
Toolbar toolbar = (Toolbar) findViewById(R.id.DCODatabaseToolbar);
setSupportActionBar(toolbar);
assert toolbar != null;
toolbar.setLogo(R.drawable.dco1);
//Receving bundle from main activity// --> Working
Bundle extras = getIntent().getExtras();
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab);
assert tabLayout != null;
tabLayout.addTab(tabLayout.newTab().setText("General Reports"));
tabLayout.addTab(tabLayout.newTab().setText("Report Display"));
tabLayout.addTab(tabLayout.newTab().setText("New Report"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount(),extras);
assert viewPager != null;
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
Pager Adapter:
public class PagerAdapter extends FragmentStatePagerAdapter{
int mNumOfTabs;
private final Bundle fragmentBundle;
public PagerAdapter(FragmentManager fm, int mNumOfTabs, Bundle bundle) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
this.fragmentBundle = bundle; ---> Receving in Adapter.
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
DCOGeneralReports tab1 = new DCOGeneralReports();
tab1.setArguments(fragmentBundle); --> Sending to fragement
return tab1;
case 1:
DCOReportDisplay tab2 = new DCOReportDisplay();
return tab2;
case 2:
DCO_New_Report tab3 = new DCO_New_Report();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Fragment Example:
public class DCOGeneralReports extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dco_general_report, container, false);
// here the problem. (SavedInstance is null! --> Not Receving the data)
Name = savedInstanceState.getString("Name");
UserGroup = savedInstanceState.getString("UserGroup");
Team = savedInstanceState.getString("Team");
Inside activity class when you create an instance of adapter you can pass the argument, so that you can retrieve that value in adapter's constructor.
Inside getItem() method of PagerAdapter try this
Bundle =new Bundle();
b.putString("key","value");
tab1.setArgument(b);
return tab1;
And also there is no need of passing argument for each activity till you need it in final activity.you can write it by using getIntent.putExtra() so that later it can be retrieved by using the getExtra("key")
In order to pass the value create an instance like this
ArrayList demo=new ArrayList();
demo.add("A");
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount(),demo);
And in adapter class change the constructor
ArrayList frag;
public PagerAdapter(FragmentManager fm, int mNumOfTabs,ArrayList frag) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
this.frag = frag;
}
Related
so i got one main activity that has a Tablayout and a ViewPager to present diffrent fragments.
when i move between the fragments with my Tablayout everything works good, but if i use a button to open fragment, when going back to the former fragment (by pushing the cancel button) the elements of the fragment i left staying on the screen (as in the picture).
i tried to use a method viewPager.setCurrentItem(0); in the fragment to go back to the homepage from the fragment instade of ft.replace(R.id.fragment_edit_reminder, new Main_Activity_fragment()).commit(); but it didn't moved back to my home fragment (with the repalce it does go back but as i saied the elements.
this is my main:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tableLayout = findViewById(R.id.Tablayouting);
final ViewPager viewPager = findViewById(R.id.ViewPager);
PagerAdapter pagerAdapter = new
PagerAdapter(getSupportFragmentManager(),tableLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
this is the fragment:
public class edit_reminder_fragment extends Fragment implements View.OnClickListener {
private Button cancelButton;
public edit_reminder_fragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment edit_reminder_fragment.
*/
public static edit_reminder_fragment newInstance() {
edit_reminder_fragment fragment = new edit_reminder_fragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void onClick(View view)//TODO: make a utility method for switching fragments on the main_activity_fragment(see note).
{
switch (view.getId()) {//recognizing what button was pushed
case R.id.ButtonCancelReminder:
//region
FragmentTransaction ft = getFragmentManager().beginTransaction();
Main_Activity_fragment maf = new Main_Activity_fragment();
ft.replace(R.id.fragment_edit_reminder, maf).commit();
break;
//endregion
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_reminder_fragment, container, false);
cancelButton = view.findViewById(R.id.ButtonCancelReminder);
cancelButton.setOnClickListener(this);
return view;
}
}
my pagerAdapted class:
public class PagerAdapter extends FragmentPagerAdapter {
//https://www.youtube.com/watch?v=HHd-Fa3DCng&ab_channel=MasterCoding
private int numOfTabs;
public PagerAdapter(FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs = numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Main_Activity_fragment();
case 1:
return new key_words_fragment();
case 2:
return new groups_and_points_fragment();
case 3:
return new Fragment_Past_Reminders();
case 4:
return new edit_reminder_fragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
in the picture we see the home page fragment ,on it 3 buttons (cancel, save, Add a sub reminder) that stayed from a fragment that open when clicking on the ADD NEW REMINDER button (when clicking on cancel in the second fragment it's going back to the home page):
First, try the following as an adaper:
public class PagerAdapter extends
FragmentPagerAdapter {
private final ArrayList<Fragment> mFragments = new ArrayList<>();
private final ArrayList<String> mFragmentTitle = new ArrayList<>();
public PagerAdapter(FragmentManager mManager) {
super(mManager);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitle.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitle.get(position);
}
public Fragment getFragment(int position) {
if (position < mFragments.size() && position >= 0) {
return mFragments.get(position);
}
return null;
}
}
Then in your MainActivity's onCreate, initialize the following:
mTabs = (TabLayout) findViewById(R.id.tabs);
mPager = (ViewPager) findViewById(R.id.view_pager);
mMainAdapter = new PagerAdapter( getSupportFragmentManager() );
setupContents();
Then the private method setupContents() as follows:
mMainAdapter.addFragment(new FragmentOne(), getResources().getString(R.string.tab_albums));
mMainAdapter.addFragment(new FragmentTwo(), getResources().getString(R.string.tab_songs));
mMainAdapter.addFragment(new FragmentThree(), getResources().getString(R.string.tab_playlists));
// you can add as many fragments as you wish
//just follow the previous method #mMainAdapter.addFragment
mPager.setAdapter(mMainAdapter);
mTabs.setupWithViewPager(mPager);
To get the current fragment:
public Fragment getCurrentFragment() {
return mMainAdapter.getFragment(mPager.getCurrentItem());
}
To check if the current fragment is FragmentOne:
private boolean isFragmentOne() {
return getCurrentFragment() instanceof FragmentOne;
}
I have one app that have 2 tabs:
PESQUISA (Filter)
SEUS FAVORITOS (Your Favorite).
The "PESQUISA" tab: this tab has some card views.
The "SEUS FAVORITOS" tab: this tab has a listview.
Whenever I click in one card into "PESQUISA" tab I would like that add the information about card into listview, but I don't know how to update the listview in "SEUS FAVORITOS" tab.
Actually, the listview is updated when I close and open app again.
I tried search some examples in stack-overflow, google, but I cannot find.
MY ACTIVITY
public class FiltersActivity extends AppCompatActivity {
private CellPhone cellPhone;
private FavoriteFragment favoriteFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filters);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle(R.string.app_name);
setSupportActionBar(toolbar);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
List<String> titles = new ArrayList<>();
titles.add(getString(R.string.search));
titles.add(getString(R.string.your_favorite));
cellPhone = getIntent().getParcelableExtra("currentCellPhone");
final FiltersViewPagerAdapter mainViewPagerAdapter = new FiltersViewPagerAdapter(getSupportFragmentManager(), titles, cellPhone);
viewPager.setAdapter(mainViewPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
}
MY FAVORITE Fragment
public class FavoriteFragment extends Fragment {
private RecyclerView mRecycleView;
private CellPhoneFavoriteListAdapter mAdapter;
private List<CellPhone> cellPhoneList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
mRecycleView = (RecyclerView) view.findViewById(R.id.recycler_view_result_phones);
mRecycleView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecycleView.setLayoutManager(layoutManager);
DatabaseSQLiteService dao = new DatabaseSQLiteService(view.getContext());
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter = new CellPhoneFavoriteListAdapter(view.getContext(), cellPhoneList);
mRecycleView.setAdapter(mAdapter);
return view;
}
}
MY FragmentPagerAdapter
public class FiltersViewPagerAdapter extends FragmentPagerAdapter {
private List<String> mFragmentTitleList = new ArrayList<>();
private FragmentManager mFragmentManager;
private CellPhone cellPhone;
public FiltersViewPagerAdapter(FragmentManager fm, List<String> titles, CellPhone cellPhone) {
super(fm);
mFragmentManager = fm;
this.mFragmentTitleList = titles;
this.cellPhone = cellPhone;
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
if (position == 0) {
fragment = new FiltersFragment();
Bundle bundle = new Bundle();
bundle.putParcelable("currentCellPhone", cellPhone);
fragment.setArguments(bundle);
} else {
fragment = new FavoriteFragment();
Bundle bundle = new Bundle();
bundle.putInt("tipo", position);
fragment.setArguments(bundle);
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
My sugestion is to replace the List<String> titles, which is local to onCreate(), by a member variable List<TitleItem> which could be accessed by any of the fragments using a callback on the Activity. (The callback can be done by casting getActivity() to FiltersActivity in the Fragment, or by defining an interface and having FiltersActivity implement it.
On another side, TitleItem, would have the title String, and the state which would indicate if it is a favourite or not.
When a title is selected from PESQUIZA, it would the change the item's state (in the list). When the user switches to SEUS FAVORITOS, the lisview would be repopulated with items with favourite state active.
To repopulate the listview, as a ViewPager is in use, it would have to be done when the fragment becomes visible vs. the loading ahead of time that ViewPager does. To do this override public void setUserVisibleHint(boolean isVisibleToUser) and put the update logic in here.
EDIT I
I had wrongly interpreted the titles list as the list of items that could become favourites. After re-reading the question I see the items are being queried from the internal database.
What you cando is the following:
In the recycler view adapter add these methods:
public void setData(List<CellPhone> data) {
this.data = data;
refreshData();
}
private void refreshData(){
this.notifyDataSetChanged();
}
Note: data is the dataset member variable you defined probably with a different name.
Then in the fragment:
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Refresh your fragment here
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter.setData(cellPhoneList);
}
}
According to Juan help the correctly solution is:
In MY FAVORITE Fragment
public class FavoriteFragment extends Fragment {
private RecyclerView mRecycleView;
private CellPhoneFavoriteListAdapter mAdapter;
private List<CellPhone> cellPhoneList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_favorite, container, false);
mRecycleView = (RecyclerView) view.findViewById(R.id.recycler_view_result_phones);
mRecycleView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecycleView.setLayoutManager(layoutManager);
DatabaseSQLiteService dao = new DatabaseSQLiteService(view.getContext());
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter = new CellPhoneFavoriteListAdapter(view.getContext(), cellPhoneList);
mRecycleView.setAdapter(mAdapter);
return view;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// Update Listview here
DatabaseSQLiteService dao = new DatabaseSQLiteService(getContext());
cellPhoneList = dao.getAllFavoriteCellphone();
mAdapter.setData(cellPhoneList);
}
}
}
and in MY ADAPTER I just add two method
public void setData(List<CellPhone> data) {
this.itemsList = data;
refreshData();
}
private void refreshData(){
this.notifyDataSetChanged();
}
This is what I was trying to do, The "Tab One" "Tab Two" as my Tabbed Page Title. Ignore the Toolbar
I created an app that uses tabbed activity, I used the preset tabbed activity in android studio and modified it to my use. But I'm having a problem in showing the tabbed title. I'm working only on 2 tabs for now but i'm planning to add more as I progress.
Here is the codes for my Tabbed Activity Class
public class StudLearnTab extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
String key;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabbed_content);
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
Bundle bundle = new Bundle();
bundle.putString("keys",key);
fragment_tabbed_content tab1 = new fragment_tabbed_content();
tab1.setArguments(bundle);
return tab1;
case 1:
fragment_tabbed_activity tab2 = new fragment_tabbed_activity();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0:
return "Content";
case 1:
return "Try Yourself";
}
return null;
}
}
}
My Fragments only contains the constructor and createview but I'll included it here for reference. Both fragments are almost the same.
public class fragment_tabbed_activity extends Fragment {
public fragment_tabbed_activity() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabbed_activity, container, false);
return rootView;
}
}
i have a Fragment(C) with a ViewPager(Adapter) with 2 Fragments(A/B).
When i call the Fragment once time, they load fine.
But when i call the Fragment(C) the secend time, the Fragment A and B dont call the View onCreateView methode and the isnĀ“t loaded.
The Fragment C is called with Fragmetnmanger:
FragmentC fragment = new FragmentC();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.adressenmdf_detail_container, fragment).addToBackStack(null).commit();
Fragment C
public BelegeDetails(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_belege_details, container, false);
//TODO Actionbar noch anpassen
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
The Setups from Fragment C
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
adapter.addFragment(new BelegeDetails1(),"Details" );
adapter.addFragment(new BelegeDetailsPos(), "Positionen");
viewPager.setAdapter(adapter);
}
private void setupTabIcons() {
tabLayout.getTabAt(1).setIcon(R.drawable.ic_belege);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
The Fragment A BelegDetails1 und the Fragment B BelegDetailsPos are normal Fragment Classes like:
public BelegeDetails1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState.......
try changing this:
ViewPagerAdapter adapter = new ViewPagerAdapter(this.getFragmentManager());
with:
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
As you are nesting fragments, you need to use getChildFragmentManager() instead of getFragmentManager()
I have three tabs using the implementation below and they perform very well. When tab is changed the proper fragment is load and so on. The problem is that, when i get to the last tab and comeback to the first fragment, its like its oncreateview method is always triggered again running the other codes it in causing duplicates. Any help will be greatly appreciated.
//Activity on the tab is based
public class Dashboard extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private int[] tabIcon = {R.drawable.ic_home, R.drawable.ic_message, R.drawable.ic_person};
android.support.v7.widget.Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
//Toolbar
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//ViewPager
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
//Tablayout
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(0).setIcon(tabIcon[0]);
tabLayout.getTabAt(1).setIcon(tabIcon[1]);
tabLayout.getTabAt(2).setIcon(tabIcon[2]);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switch(tab.getPosition()) {
case 0:
viewPager.setCurrentItem(0);
toolbar.setTitle("Home");
break;
case 1:
viewPager.setCurrentItem(1);
toolbar.setTitle("Messages");
break;
case 2:
viewPager.setCurrentItem(2);
toolbar.setTitle("Profile");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setupViewPager(ViewPager viewPager){
myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager());
myViewPagerAdapter.addFragments(new CategoryFragment(), "Categories");
myViewPagerAdapter.addFragments(new MessagesFragment(), "Messages");
myViewPagerAdapter.addFragments(new ProfileFragment(), "Profile");
viewPager.setAdapter(myViewPagerAdapter);
}
//View Pager Adapter
public class MyViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
public void addFragments(Fragment fragments, String titles){
this.fragments.add(fragments);
this.tabTitles.add(titles);
}
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
//return tabTitles.get(position);
return null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
//Main first fragment code
public class CategoryFragment extends Fragment {
private DBHandler dbHandler;
private ListView listView;
private ListAdapter adapter;
ArrayList<Categories> categoriesList = new ArrayList<Categories>();
public CategoryFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
//Setting up the basic categories
dbHandler = new DBHandler(view.getContext());
//Get Categories from database
final Cursor cursor = dbHandler.getCategories(0);
if (cursor != null) {
if(cursor.moveToFirst()){
do{
Categories categories = new Categories();
categories.set_id(cursor.getInt(0));
categories.set_categoryname(cursor.getString(2));
categories.set_categoriescaption(cursor.getString(3));
categoriesList.add(categories);
}while (cursor.moveToNext());
}
cursor.close();
}
listView = (ListView) view.findViewById(R.id.categories);
adapter = new CategoryAdapter(view.getContext(), R.layout.cursor_row, categoriesList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Integer cid = (int) (long) adapter.getItemId(position);
TextView categoryname = (TextView) view.findViewById(R.id.cursor);
String cname = categoryname.getText().toString();
Intent i = new Intent(view.getContext(), CategoryList.class);
i.putExtra("categoryname", cname);
i.putExtra("categoryid", cid);
startActivity(i);
}
}
);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
So when i swipe back here from the last tab. OncreateView runs again. How can i handle that and prevent duplicates. Thank you
By defaults ViewPager retains only 1 page in the view hierarchy in an idle state.So when you swipe to third tab the viepager destroys the first tab in order to retain the second one.
To solve this issue add this line
viewPager.setOffscreenPageLimit(3);
after you set your adapter.
Check here the documentation for more