ViewPager Hosting Two Fragments with CursorLoader Loading Only One Loader - android

I am trying to load data in two fragments hosted in a viewpager using cursorloaders. Everytime Ilaunch the activity only one fragment1 cursorloader loads data. Fragment2 loads when there is an orientation change and at this point fragment1 doesnt load data.The code for fragment1 is:
public class TransactionFragment extends Fragment
implements LoaderManager.LoaderCallbacks<Cursor>{
private static final int TRANSACTION_LOADER = 0;
private int walletId;
private RecyclerView transactionRecycler;
TransactionCursorAdapter adapter;
public TransactionFragment() {
// Required empty public constructor
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
walletId=WalletViewDashboardActivity.walletId;
getActivity().getSupportLoaderManager().initLoader(TRANSACTION_LOADER, null, this);
}
#Override
public void onResume() {
super.onResume();
getActivity().getSupportLoaderManager().restartLoader(TRANSACTION_LOADER, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView=inflater.inflate(R.layout.fragment_transaction, container, false);
transactionRecycler = (RecyclerView) rootView.findViewById(R.id.recycler_transactions);
transactionRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
return rootView;
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String sTransactionSelection =
CarepayContract.InvoiceEntry.TABLE_NAME +
"." + CarepayContract.InvoiceEntry.COLUMN_WALLET_ID + " = ? ";
String[] sArguments = {String.valueOf(walletId)};
return new CursorLoader(
getActivity(),
CarepayContract.InvoiceEntry.CONTENT_URI,
null,
sTransactionSelection,
sArguments,
null
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.e("Transactions", String.valueOf(data.getCount()));
adapter = new TransactionCursorAdapter(getActivity(), data);
transactionRecycler.setAdapter(adapter);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}}
The code for the second fragment is:
public class DependantFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private RecyclerView recyclerView;
private static final int DEPENDANT_LOADER = 0;
private int walletId;
private DependantCursorAdapter adapter;
public DependantFragment() {}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
walletId=WalletViewDashboardActivity.walletId;
recyclerView.setAdapter(adapter);
getActivity().getSupportLoaderManager().initLoader(DEPENDANT_LOADER, null, this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
recyclerView.setAdapter(adapter);
getActivity().getSupportLoaderManager().restartLoader(DEPENDANT_LOADER, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_dependant, container, false);
recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_dependants);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return rootView;
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
String sDependantSelection =
CarepayContract.UserEntry.TABLE_NAME +
"." + CarepayContract.UserEntry.COLUMN_TYPE + " = ? AND " + CarepayContract.UserEntry.TABLE_NAME +
"." + CarepayContract.UserEntry.COLUMN_WALLET_ID + " = ?";
String[] sArguments = {"1", String.valueOf(walletId)};
return new CursorLoader(
getActivity(),
CarepayContract.UserEntry.DEPENDANT_URI,
null,
sDependantSelection,
sArguments,
null
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.e("Dependant", String.valueOf(data.getCount()));
adapter = new DependantCursorAdapter(getActivity(), data);
recyclerView.setAdapter(adapter);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
} }
The code for the hosting activity is:
public class WalletViewDashboardActivity extends AppCompatActivity {
public static int walletId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wallet_view_dashboard);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
walletId = Integer.parseInt(getIntent().getStringExtra("wallet_id"));
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Transactions"));
tabLayout.addTab(tabLayout.newTab().setText("Dependants"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final WalletViewPagerAdapter adapter = new WalletViewPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
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) {
}
});
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public class WalletViewPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public WalletViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new TransactionFragment();
case 1:
return new DependantFragment();
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}}

private static final int TRANSACTION_LOADER = 0;
private static final int DEPENDANT_LOADER = 0;
You use getActivity(), so you use one loadermanager and set 0 as id for both loaders, just change one of constants to 1 and all will be fine

Related

push data from Fragment to Fragment

I am new to Android. Please excuse me if it's a silly question:
If i click on button of a Fragment - it has to trigger a test and show the result in other Fragment. So to make things simple, have written a code on button click as follows. It's not working. Please suggest.
My actual intent is to register a log.add BroadcastReceiver, so that anywhere any log error or debug is called, that message has to appear in the TestStatusFragment.
public class TriggerTestFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_trigger, container, false);
Button stopScheduler = (Button) view.findViewById(R.id.testButton);
stopScheduler.setOnClickListener((View sview) -> {
View teststatusView = inflater.inflate(R.layout.fragment_teststatus, container, false);
TextView textView = (TextView) teststatusView.findViewById(R.id.text_view);
textView.setText("test result....");
});
return view;
}
}
MainActivity.java
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new TriggerTestFragment(), "TRIGGERTEST");
adapter.addFragment(new TestStatusFragment(), "TEST STATUS");
viewPager.setAdapter(adapter);
}
Second Fragment:
public class TestStatusFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Context context = getContext();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_teststatus, container, false);
return view;
}
}
Use interface to communicate between them.
Fragment One
public class FragOne extends Fragment {
EditText etxtName, etxtDesc;
Button btnSubmit;
String name, desc;
private OnFragmentInteractionListener mListener;
public FragOne() {
// 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_frag_one, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
etxtName = (EditText) view.findViewById(R.id.etxtName);
etxtDesc = (EditText) view.findViewById(R.id.etxtDesc);
btnSubmit = (Button) view.findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = etxtName.getText().toString().trim();
desc = etxtDesc.getText().toString().trim();
if(name == null || desc == null) {
Toast.makeText(getActivity(), "Both fields required", Toast.LENGTH_SHORT).show();
} else {
mListener.onFragmentInteraction(name, desc);
etxtName.setText("");
etxtDesc.setText("");
}
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String name, String desc);
}
}
Fragment Two
public class FragTwo extends Fragment implements FragOne.OnFragmentInteractionListener{
TextView textView, textDesc;
public FragTwo() {
// 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_frag_two, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
textView = (TextView) view.findViewById(R.id.txtName);
textDesc = (TextView) view.findViewById(R.id.txtDesc);
}
#Override
public void onFragmentInteraction(String name, String desc) {
textView.setText(name);
textDesc.setText(desc);
}
}
Init fragments
fragOne = new FragOne();
fragTwo = new FragTwo();
PagerAdapter
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
MainActivity need implement onFragmentInteraction interface
public class MainActivity extends AppCompatActivity implements FragOne.OnFragmentInteractionListener{
static FragOne fragOne;
static FragTwo fragTwo;
MyPagerAdapter myPagerAdapter;
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragOne = new FragOne();
fragTwo = new FragTwo();
viewPager = (ViewPager) findViewById(R.id.viewPager);
myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(myPagerAdapter);
}
#Override
public void onFragmentInteraction(String name, String desc) {
myPagerAdapter.onFragmentInteraction(name, desc );
}
public static class MyPagerAdapter extends FragmentPagerAdapter implements FragOne.OnFragmentInteractionListener{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return fragOne;
case 1:
return fragTwo;
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
return "Page " + position;
}
#Override
public void onFragmentInteraction(String name, String desc) {
fragTwo.onFragmentInteraction(name, desc);
}
}
}
You can read full article here https://www.mytrendin.com/passing-data-between-fragments/

ViewPager not working properly, when scrolling showing wrong positions

TabLayout not working properly, when scrolling right it works correctly sometime but after scrolling left it shows same data. I'm calling Same Fragment class nine times in SectionPagerAdapter and trying to change data dynamically in Recyclerview.
ViewPagerFragment Class
public class ViewPagerFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager mViewPager;
private SectionsPagerAdapter mSectionsPagerAdapter;
// private ArrayList tabName;
private String[] tabName = {"bangladesh","international","economy" ,"opinion","sports","entertainment", "features","life-style","northamerica"};
public ViewPagerFragment() {
}
public ViewPagerFragment newInstance(String navigation) {
ViewPagerFragment fragment = new ViewPagerFragment();
Bundle args = new Bundle();
args.putString(Constants.FRAG_A, navigation);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.test_fragment, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
mViewPager = (ViewPager)view.findViewById(R.id.container);
for(int i=0; i<=8; i++){
tabLayout.addTab(tabLayout.newTab().setText(tabName[i]));
}
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition()); Log.v("pagerF ^&%&^^&: ",tabName[tab.getPosition()]);
getChildFragmentManager().beginTransaction().addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Note that we are passing childFragmentManager, not FragmentManager
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public void onResume() {
super.onResume();
if (mSectionsPagerAdapter!=null){
mSectionsPagerAdapter.notifyDataSetChanged();
}
}
SectionsPagerAdapter Class
public class SectionsPagerAdapter extends FragmentPagerAdapter {
int mNumOfTabs;
String[] tabName;
public SectionsPagerAdapter(FragmentManager fm, int NumOfTabs, String[] tabName) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.tabName=tabName;
}
#Override
public Fragment getItem(int position) {
HomeFragment comn = new HomeFragment();
return comn.newInstance(tabName[position-1]);
}
#Override
public int getCount() {
Log.v("Count*^&*^ ", String.valueOf(mNumOfTabs));
return mNumOfTabs;
}
}
HomeFragment Class
public class HomeFragment extends Fragment {
public static String fragmentName = "";
HorizontalAdapter adapterhor; VerticalAdapter adapterver;
ProthomAlo prothomAlo;
RecyclerView recyclerViewh, recyclerViewv;
public HomeFragment newInstance(String navigation) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putString(Constants.FRAG_A, navigation);
fragment.setArguments(args);
fragmentName = navigation;
Log.v("home^^* :", navigation);
return fragment;
}
public HomeFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
recyclerViewh = view.findViewById(R.id.recycler_View_ho);
recyclerViewv = view.findViewById(R.id.recycler_View_ver);
prothomAlo = new ProthomAlo();
prothomAlo.getProthomAloPage(fragmentName, new ProthomAlo.ApiCallback() {
#Override
public void onSuccess(ArrayList<SingleVertical> result) {
adapterhor = new HorizontalAdapter(getActivity(), result);
adapterver = new VerticalAdapter(getActivity(), result);
recyclerViewh.setAdapter(adapterhor); recyclerViewv.setAdapter(adapterver);
recyclerViewv.setLayoutManager(new LinearLayoutManager(getActivity()));
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerViewh.setLayoutManager(layoutManager);
// Log.v("$^&^$$^&", fragmentName);
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
//adapterver.notifyDataSetChanged(); adapterhor.notifyDataSetChanged();
Log.v("home^^* :", fragmentName);
}
}

Android viewPager not changing the title in titlebar

I have this "frame" app with toolbar and viewPager.
BaseActivity:
public abstract class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
}
protected abstract int getLayoutResource();
}
ToolbarActivity:
protected static Toolbar toolbar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = findViewById(R.id.flToolbarContentContainer);
if (contentView instanceof ViewGroup) {
((ViewGroup) contentView)
.addView(LayoutInflater.from(this)
.inflate(getToolbarLayoutResource()
, (ViewGroup) contentView, false));
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected int getLayoutResource() {
return R.layout.activity_toolbar;
}
protected abstract int getToolbarLayoutResource();
public void showToolbar() {
toolbar.setVisibility(View.VISIBLE);
}
public void hideToolbar() {
toolbar.setVisibility(View.GONE);
}
public static void setTitle(String title){
toolbar.setTitle(title);
}
}
MainActivity:
public class MainActivity extends ToolbarActivity {
#Override
protected int getToolbarLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabFragment homeFragment = new TabFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.llMainActivityContainer, homeFragment)
.commit();
}
And The. TabFragment:
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
private String[] titles = new String[3];
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
titles[0] = "Összes";
titles[1] = "Saját";
titles[2] = "Közelben";
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.view_pager,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
ToolbarActivity.setTitle(""+titles[position]);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SecondFragment();
case 2 : return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
My problem is if I open a new activity from the viewPager and finish it,
when I return to the viewPager activity the onPageSelected listener runs but not changing my toolbar title.
Can you help me how can I solve this?
Thank you!
try
getActivity.setTitle(""+titles[position]);

Same fragment with different contents in viewpager

I have one parent fragment where there is viewpager and tablayout.
Viewpager holds the fragment with different contents associated with it.
Every think works fine on swipe but whenever I tap on the different tabs of the tablayout, categoryId and categoryName of SwipableFragment is changed to adjacent tab's SwipableFragmet to the visible fragment.
Basically when I launch my FragmentAllNews (containing a ViewPager) it's shown the second fragment/page instead of the first and when I swipe to the second I see the third... In other words It's always shown the next or the previous fragment/page depending on the swipe direction (left or right).
Sorry For my bad english :(
here are my Fragments and FragmentStatePagerAdater class
###1 FragmentAllNews which holds the viewpager and tablayout
public class FragmentAllNews extends Fragment {
#Bind(R.id.tab_layout)
TabLayout tabLayout;
#Bind(R.id.all_news_viewpager)
ViewPager viewPager;
SessionManager sessionManager;
String categoryId;
String categoryName;
ArrayList<TabModel> tabs;
public static FragmentAllNews createNewInstance() {
FragmentAllNews fragmentAllNews = new FragmentAllNews();
return fragmentAllNews;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
tabs = sessionManager.getSwitchedNewsValue() == 0 ?
StaticStorage.getTabData(0) :
StaticStorage.getTabData(1);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.fragment_all_news, container, false);
ButterKnife.bind(this, fragmentView);
return fragmentView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setViewPager(tabs);
setTabLayout();
}
private void setTabLayout() {
tabLayout.setupWithViewPager(viewPager);
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) {
}
});
}
private void setViewPager(ArrayList<TabModel> tabs) {
ArrayList<NewsFragmentModel> frags = new ArrayList<>();
for (int i = 0; i < tabs.size(); i++) {
if (i == 0) {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(FragmentBreakingAndLatestNews.createNewInstance(categoryId, categoryName), categoryName));
} else {
categoryId = tabs.get(i).cat_id;
categoryName = tabs.get(i).cat_name;
frags.add(new NewsFragmentModel(SwipableFragment.createNewInstance(categoryId, categoryName), categoryName));
}
}
NewsPagerAdapter adapter = new NewsPagerAdapter(getChildFragmentManager(),frags);
viewPager.setAdapter(adapter);
}
#Override
public void onDestroyView() {
super.onDestroyView();
ButterKnife.unbind(this);
}
}
###2 SwipableFragment which the fragment attached to the viewpager
public class SwipableFragment extends Fragment implements NewsTitlesAdapter.RecyclerPositionListener {
#Bind(R.id.recycler_view)
RecyclerView recyclerView;
#Bind(R.id.progess)
ProgressBar progressBar;
#Bind(R.id.cat_id)
TextView categoryTextView;
ArrayList<NewsObj> newsObjs;
NewsTitlesAdapter newsTitlesAdapter;
SessionManager sessionManager;
private static String categoryId;
private static String categoryName;
public static SwipableFragment createNewInstance(String category_id, String category_name) {
SwipableFragment swipableFragment = new SwipableFragment();
Bundle box = new Bundle();
box.putString(StaticStorage.NEWS_CATEGORY_ID, category_id);
box.putString(StaticStorage.NEWS_CATEGORY, category_name);
swipableFragment.setArguments(box);
return swipableFragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sessionManager = new SessionManager(getActivity());
categoryId = getArguments().getString(StaticStorage.NEWS_CATEGORY_ID);
categoryName = getArguments().getString(StaticStorage.NEWS_CATEGORY);
newsObjs = (sessionManager.getSwitchedNewsValue() == 0) ?
NewsData.getNewsRepublica(getActivity()) :
NewsData.getNewsNagarik(getActivity(),categoryName);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_swipable, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.i("category", categoryId + " " + categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
newsTitlesAdapter = new NewsTitlesAdapter(newsObjs);
newsTitlesAdapter.setOnRecyclerPositionListener(this);
recyclerView.setAdapter(newsTitlesAdapter);
recyclerView.addOnScrollListener(new EndlessScrollListener(linearLayoutManager) {
#Override
public void onLoadMore(int current_page) {
Log.i("categoryId", categoryId+" "+categoryName);
categoryTextView.setText(categoryId+" "+categoryName);
progressBar.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ArrayList<NewsObj> moreNews = sessionManager.getSwitchedNewsValue() == 0 ?
NewsData.getNewsRepublica(getContext()) :
NewsData.getNewsNagarik(getContext(),categoryName);
int curSize = newsTitlesAdapter.getItemCount();
newsObjs.addAll(moreNews);
newsTitlesAdapter.notifyItemRangeInserted(curSize, newsObjs.size() - 1);
progressBar.setVisibility(View.GONE);
}
}, 5000);
}
});
}
#Override
public void onChildItemPositionListen(int position, View view) {
if (view.getId() == R.id.news_share_text_view) {
} else if (view.getId() == R.id.news_show_detail_text_view) {
} else {
Intent newsDetailIntent = new Intent(getActivity(), NewsDetailActivity.class);
NewsObj newsObj = newsObjs.get(position);
newsObj.setNewsCategory(categoryName);
newsDetailIntent.putExtra(NewsDetailActivity.NEWS_TITLE_EXTRA_STRING, newsObj);
startActivity(newsDetailIntent);
}
}
}
###3 NewsPagerAdapter is the subclass extended from FragmentStatePagerAdapter
public class NewsPagerAdapter extends FragmentStatePagerAdapter {
ArrayList<NewsFragmentModel> frags;
public NewsPagerAdapter(FragmentManager fm) {
super(fm);
}
public NewsPagerAdapter(FragmentManager fm,ArrayList<NewsFragmentModel> frags){
super(fm);
this.frags = frags;
}
#Override
public Fragment getItem(int position) {
return frags.get(position).getFrag();
}
#Override
public int getCount() {
return frags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return frags.get(position).getTitle();
}
}
###4 NewsFragmentModel
public class NewsFragmentModel {
private Fragment frag;
private String title;
public NewsFragmentModel(Fragment frag, String title) {
this.frag = frag;
this.title = title;
}
public Fragment getFrag() {
return frag;
}
public void setFrag(Fragment frag) {
this.frag = frag;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
Am I doing any mistakes ? please help me.If you need more info please let me know. My final hope is Stackoverflow

Dynamically load next fragment with ViewPager

I'm creating a demo app with the new android compatibility library. I want to show two listfragments with ViewPager. The first shows the root categories and the second shows the subcategories. After somebody clicks on root category the viewpager move to the subcategory, but it won't work, because always show the root category elements.
I spend few minutes with debug and I'm realised the ViewPager creates the second fragment after the first one.(I think the pager cache the next view or fragment.)
Is it possible to load the second fragment after onListItemClick?
Here is the code:
public class ViewPagerDemoActivity extends FragmentActivity implements OnBookSelectedListener {
private static int mSelectedCategoryId;
private MyAdapter mMyAdapter;
private ViewPager mPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupPager();
}
private void setupPager() {
mPager = (ViewPager) findViewById(R.id.pager);
mMyAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyAdapter);
}
#Override
public void onBookSelected(int categoryId) {
mSelectedCategoryId = categoryId;
if (mSelectedCategoryId == 0) {
mPager.setCurrentItem(1);
} else {
mPager.setCurrentItem(0);
}
}
public static class MyAdapter extends FragmentPagerAdapter {
private static final int NUMBER_OF_FRAGMENTS = 2;
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return BookListFragment.newInstance(mSelectedCategoryId);
}
#Override
public int getCount() {
return NUMBER_OF_FRAGMENTS;
}
}
}
public class BookListFragment extends ListFragment {
private static final String ARGUMENT_KEY = "categoryId";
private OnBookSelectedListener mOnBookSelectedListener;
private int mCategoryId;
public static BookListFragment newInstance(int categoryId) {
BookListFragment bookListFragment = new BookListFragment();
Bundle argument = new Bundle();
argument.putInt(ARGUMENT_KEY, categoryId);
bookListFragment.setArguments(argument);
return bookListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCategoryId = getArguments() != null ? getArguments().getInt(ARGUMENT_KEY) : 0;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Books.getBooks(mCategoryId)));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pager_list, container, false);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Category :" + mCategoryId);
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (mCategoryId == 0) {
mOnBookSelectedListener.onBookSelected(1);
} else {
mOnBookSelectedListener.onBookSelected(0);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOnBookSelectedListener = (OnBookSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + "Must Implement OnBookSelectedListener.");
}
}
public interface OnBookSelectedListener {
public void onBookSelected(int categoryId);
}
}
public class Books {
private static final String[] fruits = new String[] { "Apple", "Banana", "Orange" };
private static final String[] category = new String[] { "Lorem", "Dolor", "Ipsum" };
public static String[] getBooks(int categoryId) {
return categoryId == 0 ? category : fruits;
}
}
I solved the problem, I need to add List to the adapter and after that the getItem don't create new instance, only gets the item from the list.
This is the new code.
public class ViewPagerDemoActivity extends FragmentActivity implements OnBookSelectedListener {
private MyAdapter mMyAdapter;
private ViewPager mPager;
private BookOnPageChangeListener mBookOnPageChangeListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupPager();
}
private void setupPager() {
mPager = (ViewPager) findViewById(R.id.pager);
mMyAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyAdapter);
mBookOnPageChangeListener = new BookOnPageChangeListener();
mPager.setOnPageChangeListener(mBookOnPageChangeListener);
}
#Override
public void onBookSelected(int categoryId) {
mMyAdapter.addPage(categoryId);
mPager.setCurrentItem(mBookOnPageChangeListener.getCurrentPage() + 1);
}
public static class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> pages;
public MyAdapter(FragmentManager fm) {
super(fm);
initPages();
}
/**
* Create the list and add the first ListFragment to the ViewPager.
*/
private void initPages() {
pages = new ArrayList<Fragment>();
addPage(0);
}
/**
* Add new BookListFragment to the ViewPager.
*
* #param categoryId
* - the category id
*/
public void addPage(int categoryId) {
pages.add(BookListFragment.newInstance(categoryId));
}
#Override
public Fragment getItem(int position) {
return pages.get(position);
}
#Override
public int getCount() {
return pages.size();
}
}
/**
* Get the current view position from the ViewPager.
*/
public static class BookOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
private int currentPage;
#Override
public void onPageSelected(int position) {
// current page from the actual position
currentPage = position;
}
public int getCurrentPage() {
return currentPage;
}
}
}
Have you tried using setOnItemClickListener()?

Categories

Resources