how can i implement a onRefreshListener in fragments if i am using ViewPager (ViewPager 2) with FragmentStateAdapter.
I found only examples with FragmentPageAdapter.
the other code works so far, i mean swiping between fragments an displaying a list of strings.
Just the refresh (pull from top to bottom) don't work.
I just see the refresh symbol short and then it dissapears.
In the debugger the onRefresh functions will not be called, after a refresh action.
This is my Code:
main activity
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this, dataManager));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
viewpager
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 3;
private DataManager dataManager;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity, DataManager dataManager) {
super(fragmentActivity);
this.dataManager = dataManager;
}
#NonNull #Override public Fragment createFragment(int position) {
Fragment fragment = null;
if (position == 0)
{
fragment = new FragmentA();
Bundle bundle = new Bundle(2);
bundle.putString("TOKEN", dataManager.getToken());
bundle.putString("SERVER_URL", dataManager.getServerURL());
fragment.setArguments(bundle);
}
else if (position == 1)
{
fragment = new FragmentB();
}
else if (position == 2)
{
fragment = new FragmentC();
}
return fragment;
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
fragment
public class FragmentA extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private RecyclerView recyclerView;
private SwipeRefreshLayout swipeLayout;
private Bundle bundle;
private ListView mainListView;
private LibrariesAdapter listAdapter;
private LibraryDataManager libraryDataManager;
private RecyclerViewAdapter adapter;
private GetLibrariesTask getLibrariesTask;
private String token;
private String serverUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = getArguments();
if (bundle != null) {
token = bundle.getString("TOKEN");
serverUrl = bundle.getString("SERVER_URL");
libraryDataManager = new LibraryDataManager(token, serverUrl);
} else {
// ToDo show error or something else
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment, container, false);
swipeLayout = rootView.findViewById(R.id.swiperefresh);
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mainListView = view.findViewById(android.R.id.list);
ArrayList<Library> librariesList = new ArrayList<>();
listAdapter = new LibrariesAdapter(getActivity(), librariesList);
mainListView.setAdapter(listAdapter);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
getLibrariesTask = new GetLibrariesTask();
getLibrariesTask.execute();
}
});
}
private class GetLibrariesTask extends AsyncTask<Void, Void, List<Library>> {
#Override
protected List<Library> doInBackground(Void... args) {
List<Library> libraries = libraryDataManager.getLibraries();
return libraries;
}
#Override
protected void onPostExecute(List<Library> libraries) {
listAdapter.clear();
listAdapter.addAll(libraries);
listAdapter.notifyDataSetChanged();
Logger.debug("on refresh2");
// swipeLayout.setRefreshing(false);
}
}
}
Related
Im trying to use Material Container Transform in Recyclerview Adapter as described by this post MaterialContainerTransform transition is not Working on Return , but after implementing this in my project im getting null pointer exception error.
As everyone know Material Container Transform animation tutorials are in kotlin and im doing it in java.
So if anyone know how to properly use material container transform animation in recyclerview and point out my mistakes i will be very much thankful to him.
RecyclerView Adapter Class(source)
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> implements Filterable {
private Context context;
private List<Astadhyayi> wordList;
private List<Astadhyayi> filwordList;
private DictionaryDB dictionaryDB;
private OnclickListenerInterface listener;
public RecyclerViewAdapter(Context context, List<Astadhyayi> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Astadhyayi>(itemList);
}
public void setClickListener(OnclickListenerInterface onclickListener) {
this.listener = onclickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
Astadhyayi word = wordList.get(position);
holder.rsutras.setText(word.mSutras);
// Animation******
holder.rsutras.setTransitionName(word.getMSutras());
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
} else {
holder.bookmark.setImageDrawable(null);
}
}
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Astadhyayi> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Astadhyayi item : filwordList) {
if (item.getMSutras().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Astadhyayi>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView rsutras;
private ImageView bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
rsutras = itemView.findViewById(R.id.tvSansTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
/*
#Override
public void onClick(View view) {
if(listener!=null) listener.onItemClicked(getAbsoluteAdapterPosition(), rsutras);
}
*/
#Override
public void onClick(View view) {
int position = this.getAbsoluteAdapterPosition();
Astadhyayi word = wordList.get(position);
//*************** Bundle **************\\
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
bundle.putString("transition_name", word.getMSutras());
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setSharedElementEnterTransition(new MaterialContainerTransform());
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.setReorderingAllowed(true);
fT.addSharedElement(rsutras, rsutras.getTransitionName()); // Shared element!
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
}
}
RecyclerView Fragment Class(source)
public class ShowtermsTwoFragment extends Fragment {
private RecyclerView rv;
private EditText tV;
private Toolbar toolbar;
private LinearLayoutManager layoutManager;
private static DictionaryDB db;
private RecyclerViewAdapter rvAdapter;
private SearchView searchView = null;
private SearchView.OnQueryTextListener queryTextListener;
private List<Astadhyayi> wordsList = new ArrayList<>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setExitTransition(new MaterialElevationScale(false));
setReenterTransition(new MaterialElevationScale(true));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terms_recyclerview, container, false);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
toolbar = ((Toolbar) view.findViewById(R.id.toolbar_rv));
rv = view.findViewById(R.id.rvTerms);
tV = view.findViewById(R.id.tVinput);
//*********** TOOLBAR
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
// new Get_DbData().execute();
databaseCheck();
recyclerCheck1();
postponeEnterTransition();
((ViewGroup) view.getParent()).getViewTreeObserver()
.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
startPostponedEnterTransition();
return true;
}
});
}
private void databaseCheck() {
String sanskritWord = getActivity().getIntent().getStringExtra("sanskritWord");
//*********** ### DATABASE OPENING ### ***********\\
db = DictionaryDB.getInstance(this.getActivity());
wordsList = db.getWords((sanskritWord));
}
private void recyclerCheck1() {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(rv.getContext(), layoutManager.getOrientation());
rv.addItemDecoration(dividerItemDecoration);
rvAdapter = new RecyclerViewAdapter(getContext(), wordsList, db);
rv.setAdapter(rvAdapter);
/////********** rvAdapter.setClickListener(this);
rvAdapter.notifyDataSetChanged();
}
}
Details Fragment Class(destination)
public class TermThreeDetailsFragment extends Fragment {
private TextView sutraTV,vrittiTV,padaTv,adhyayTV,sutraIdTV ;
private CoordinatorLayout coordinatorLayout;
private FloatingActionButton fabBtn;
private static DictionaryDB db;
private Astadhyayi word;
private BottomAppBar bottomAppBar;
private TextToSpeech pronunciation;
private AudioManager audio;
private String ttsID , trans;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MaterialContainerTransform transform = new MaterialContainerTransform();
transform.setScrimColor(Color.TRANSPARENT);
setSharedElementEnterTransition(transform);
setSharedElementReturnTransition(transform);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
sutraTV = view.findViewById(R.id.tvSutra);
adhyayTV = view.findViewById(R.id.tVAdhyay);
padaTv = view.findViewById(R.id.tVPada);
sutraIdTV = view.findViewById(R.id.tVSutraId);
vrittiTV = view.findViewById(R.id.tvVritti);
fabBtn = view.findViewById(R.id.favFAB);
coordinatorLayout = view.findViewById(R.id.parentCordlayout);
bottomAppBar = view.findViewById(R.id.bottom_app_bar);
bundleCheckWithDb();
WordCheck();
}
private void bundleCheckWithDb() {
//*********** Geting Parcelable Data
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
trans = bundle.getString("transition_name");
adhyayTV.setText(word.getMAdhyay());
padaTv.setText(word.getMPada());
sutraIdTV.setText(word.getMSutra_id());
sutraTV.setText(word.getMSutras());
vrittiTV.setText(word.getMVritti());
}
//*********** DATABASE OPENING
db = DictionaryDB.getInstance(this.getActivity());
}
private void WordCheck() {
if (word.mStatus != null && word.mStatus.equals(DictionaryDB.BOOKMARKED)) {
fabBtn.setImageResource(R.drawable.cards_heart);
} else {
fabBtn.setImageResource(R.drawable.cards_heart_white);
}
fabBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, fabBtn);
}
});
}
}
Error im getting
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.sanskrit.mysearcher.models.Astadhyayi.getMSutras()' on a null object reference
at com.sanskrit.mysearcher.fragments.TermThreeDetailsFragment.onCreateView(TermThreeDetailsFragment.java:69)
From the current given information, I think you should do something like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
word = new Astadhyayi(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
}
View view = inflater.inflate(R.layout.show_three_details, container, false);
view.findViewById(R.id.tvSutra).setTransitionName(word.getMSutras());
return view;
}
Again, I am not sure what getMSutras() actually returns and if it's right to use that here.
I made a quiz application where I display my Question using a Fragment, and using ViewPager. The Question is taken from SQLite, and here I am confused: If I have 10 questions, then I have to use 10 fragments. How can I use 1 Fragment to hold all questions?
Is there an idea for this?
MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private int mFragmentIndex = 0;
private ViewPager viewPager;
private Button back, next;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
setupViewPager(viewPager);
back = findViewById(R.id.buttonBack);
next = findViewById(R.id.buttonNext);
back.setOnClickListener(this);
next.setOnClickListener(this);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Question1(), "Question1");
adapter.addFrag(new Question2(), "Question2");
adapter.addFrag(new Question3(), "Question3");
viewPager.setOffscreenPageLimit(adapter.getCount());
viewPager.setAdapter(adapter);
}
#Override
public void onClick(View view) {
if (view == back) {
mfragmentIndex--;
viewPager.setCurrentItem(mFragmentIndex);
} else if(view == next) {
mfragmentIndex++;
viewPager.setCurrentItem(mFragmentIndex);
}
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitle = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment,String title){
mFragmentList.add(fragment);
mFragmentTitle.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return super.getPageTitle(position);
}
}
}
My Fragment, Question1:
public class Question1 extends Fragment {
private List<Question> questionsList;
private Question currentQuestion;
private TextView txtQuestion, tvNoOfQs;
private RadioButton rbtnA, rbtnB, rbtnC, rbtnD;
private int obtainedScore = 0;
private int questionId = 0;
private int answeredQsNo = 0;
ArrayList<String> myAnsList;
public Question1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final DBAdapter dbAdapter = new DBAdapter(getContext());
questionsList = dbAdapter.getAllQuestions();
currentQuestion = questionsList.get(questionId);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_question1, container, false);
final RadioGroup grp = (RadioGroup)view.findViewById(R.id.radioGroup1);
tvNoOfQs = (TextView)view.findViewById(R.id.tvNumberOfQuestions);
txtQuestion = (TextView)view.findViewById(R.id.tvQuestion);
rbtnA = (RadioButton)view.findViewById(R.id.radio0);
rbtnB = (RadioButton)view.findViewById(R.id.radio1);
rbtnC = (RadioButton)view.findViewById(R.id.radio2);
rbtnD = (RadioButton)view.findViewById(R.id.radio3);
setPertanyaan();
myAnsList = new ArrayList<String>();
return view;
}
private void setPertanyaan() {
rbtnA.setChecked(false);
rbtnB.setChecked(false);
rbtnC.setChecked(false);
rbtnD.setChecked(false);
answeredQsNo = questionId+1;
tvNoOfQs.setText(+answeredQsNo+"/"+questionsList.size());
txtQuestion.setText(currentQuestion.getQUESTION());
rbtnA.setText(currentQuestion.getOptionA());
rbtnB.setText(currentQuestion.getOptionB());
rbtnC.setText(currentQuestion.getOptionC());
rbtnD.setText(currentQuestion.getOptionD());
questionId++;
}
}
I'd recommend using the Fragment's arguments to pass in the question ID. You already have an abstraction around a Question -- it appears that the only thing that really changes here is the question ID.
For example, you would have just a QuestionFragment which is responsible for displaying any given Question:
public class QuestionFragment extends Fragment {
private static final String ARG_QUESTION_ID = "question_id";
public static QuestionFragment newInstance(String questionId) {
final QuestionFragment fragment = new QuestionFragment();
final Bundle args = new Bundle();
args.putString(ARG_QUESTION_ID, questionId);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final String questionId = getArguments().getString(questionId);
final DBAdapter dbAdapter = new DBAdapter(getContext());
questionsList = dbAdapter.getAllQuestions();
currentQuestion = questionsList.get(questionId);
// ...
return view;
}
}
Then, when setting up your ViewPager, just provide the question ID to each instance as you create it:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(QuestionFragment.newInstance(0), "Question1"));
adapter.addFrag(QuestionFragment.newInstance(1), "Question2"));
adapter.addFrag(QuestionFragment.newInstance(2), "Question3"));
viewPager.setOffscreenPageLimit(adapter.getCount());
viewPager.setAdapter(adapter);
}
I am a having a fragment with TabLayout. As soon as I move from TabLayout Fragment to the next Fragment and press the back key. The content on the default TabLayout fragment disappears. I found a possible solution to this in the post. Following is the code for the TabLayout.
public class IndividualCollectionSheetFragment extends MifosBaseFragment {
private TabLayout tabLayout;
private ViewPager viewPager;
private View rootView;
public IndividualCollectionSheetFragment() {
}
public static IndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
IndividualCollectionSheetFragment fragment = new IndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_individual_recycler, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
viewPager = rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
viewPager.setAdapter(adapter);
}
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 solution in the post suggested using getChildFramentManager instead of getSupportFragmentManager. As soon as I changed to getChildFragmentManager. I got the error.
java.lang.IllegalStateException: Fragment CollectionSheetDialogFragment{572dd42 #0 Identifier Dialog Fragment} declared target fragment NewIndividualCollectionSheetFragment{45e8153 #0 id=0x7f090361 android:switcher:2131297121:0} that does not belong to this FragmentManager!
which might be because of the class CollectionSheetDialogFragment which extends DialogFragment and there must be inconsistencies with the different Fragment Managers being used.
NewIndividualCollectionSheet.java(first fragment in tablayout)
public class NewIndividualCollectionSheetFragment extends MifosBaseFragment implements
IndividualCollectionSheetMvpView, MFDatePicker.OnDatePickListener,
Spinner.OnItemSelectedListener, View.OnClickListener {
#BindView(R.id.btn_fetch_collection_sheet)
Button btnFetchSheet;
#BindView(R.id.sp_office_list)
Spinner spOffices;
#BindView(R.id.sp_staff_list)
Spinner spStaff;
#BindView(R.id.tv_repayment_date)
TextView tvRepaymentDate;
#Inject
NewIndividualCollectionSheetPresenter presenter;
private IndividualCollectionSheet sheet;
private DialogFragment datePicker;
private RequestCollectionSheetPayload requestPayload;
private View rootView;
private ArrayAdapter<String> officeAdapter;
private ArrayList<String> officeNameList;
private List<Office> officeList;
private ArrayAdapter<String> staffAdapter;
private ArrayList<String> staffNameList;
private List<Staff> staffList;
private int officeId;
private int staffId;
private int requestCode = 1;
private boolean success = true;
private String actualDisbursementDate;
private String transactionDate;
public NewIndividualCollectionSheetFragment() {
}
public static NewIndividualCollectionSheetFragment newInstance() {
Bundle args = new Bundle();
NewIndividualCollectionSheetFragment fragment = new NewIndividualCollectionSheetFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
if (savedInstanceState != null) {
sheet = (IndividualCollectionSheet) savedInstanceState.get(
Constants.EXTRA_COLLECTION_INDIVIDUAL);
}
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_new_collection_sheet, container, false);
ButterKnife.bind(this, rootView);
setToolbarTitle(getStringMessage(R.string.individual_collection_sheet));
presenter.attachView(this);
setUpUi();
return rootView;
}
private void setUpUi() {
setRepaymentDate();
officeNameList = new ArrayList<>();
officeAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, officeNameList);
officeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOffices.setAdapter(officeAdapter);
spOffices.setOnItemSelectedListener(this);
staffNameList = new ArrayList<>();
staffAdapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_spinner_item, staffNameList);
staffAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spStaff.setAdapter(staffAdapter);
tvRepaymentDate.setOnClickListener(this);
btnFetchSheet.setOnClickListener(this);
presenter.fetchOffices();
}
void setRepaymentDate() {
datePicker = MFDatePicker.newInsance(this);
String date = DateHelper.
getDateAsStringUsedForCollectionSheetPayload(MFDatePicker.getDatePickedAsString());
tvRepaymentDate.setText(date.replace('-', ' '));
transactionDate = date.replace('-', ' ');
actualDisbursementDate = transactionDate;
}
private void prepareRequestPayload() {
requestPayload = new RequestCollectionSheetPayload();
requestPayload.setOfficeId(officeId);
requestPayload.setStaffId(staffId);
requestPayload.setTransactionDate(tvRepaymentDate.getText().toString());
}
#Override
public void setOfficeSpinner(List<Office> offices) {
officeList = offices;
officeNameList.clear();
officeNameList.add(getString(R.string.spinner_office));
officeNameList.addAll(presenter.filterOffices(officeList));
officeAdapter.notifyDataSetChanged();
}
#Override
public void onDatePicked(String date) {
String d = DateHelper.getDateAsStringUsedForCollectionSheetPayload(date);
tvRepaymentDate.setText(d.replace('-', ' '));
}
public void retrieveCollectionSheet() {
prepareRequestPayload();
presenter.fetchIndividualCollectionSheet(requestPayload);
}
public void setTvRepaymentDate() {
datePicker.show(getActivity().getSupportFragmentManager(),
FragmentConstants.DFRAG_DATE_PICKER);
}
#Override
public void setStaffSpinner(List<Staff> staffs) {
spStaff.setOnItemSelectedListener(this);
staffList = staffs;
staffNameList.clear();
staffNameList.add(getString(R.string.spinner_staff));
staffNameList.addAll(presenter.filterStaff(staffList));
staffAdapter.notifyDataSetChanged();
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch (adapterView.getId()) {
case R.id.sp_office_list:
if (i == officeList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_office));
} else {
Toaster.show(rootView, officeNameList.get(i));
officeId = officeList.get(i - 1).getId();
presenter.fetchStaff(officeId);
}
break;
case R.id.sp_staff_list:
if (i == staffList.size() || i == 0) {
Toaster.show(rootView, getStringMessage(R.string.error_select_staff));
} else {
staffId = staffList.get(i - 1).getId();
}
break;
}
}
public void popupDialog() {
CollectionSheetDialogFragment collectionSheetDialogFragment =
CollectionSheetDialogFragment.newInstance(tvRepaymentDate.getText().toString(),
sheet.getClients().size());
collectionSheetDialogFragment.setTargetFragment(this, requestCode);
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.addToBackStack(FragmentConstants.FRAG_DOCUMENT_LIST);
collectionSheetDialogFragment.show(fragmentTransaction, "Identifier Dialog Fragment");
}
public void getResponse(String response) {
switch (response) {
case "FillNow":
FragmentManager fm = getActivity()
.getSupportFragmentManager();
fm.popBackStack();
IndividualCollectionSheetDetailsFragment frag = new
IndividualCollectionSheetDetailsFragment().newInstance(sheet,
actualDisbursementDate, transactionDate);
((MifosBaseActivity) getActivity()).replaceFragment(frag,
true, R.id.container);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
#Override
public void showSheet(IndividualCollectionSheet individualCollectionSheet) {
sheet = individualCollectionSheet;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(Constants.EXTRA_COLLECTION_INDIVIDUAL, sheet);
}
#Override
public void showSuccess() {
if (success) {
popupDialog();
}
}
#Override
public void showError(String message) {
Toaster.show(rootView, message);
}
#Override
public void showNoSheetFound() {
success = false;
Toaster.show(rootView, getStringMessage(R.string.no_collectionsheet_found));
}
#Override
public void showProgressbar(boolean b) {
if (b) {
showMifosProgressDialog();
} else {
hideMifosProgressDialog();
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_repayment_date:
setTvRepaymentDate();
break;
case R.id.btn_fetch_collection_sheet:
retrieveCollectionSheet();
break;
}
}
}
CollectionSheetDialogFragment.java
public class CollectionSheetDialogFragment extends DialogFragment {
#BindView(R.id.tv_due_date)
TextView tvDueDate;
#BindView(R.id.tv_members)
TextView tvMembers;
#BindView(R.id.btn_fillnow)
Button btnFillnow;
#BindView(R.id.btn_cancel)
Button btnCancel;
private View rootView;
private String date;
private int members;
public CollectionSheetDialogFragment() {
}
public static CollectionSheetDialogFragment newInstance(String date, int members) {
CollectionSheetDialogFragment collectionSheetDialogFragment =
new CollectionSheetDialogFragment();
Bundle args = new Bundle();
args.putString(Constants.REPAYMENT_DATE, date);
args.putInt(Constants.MEMBERS, members);
collectionSheetDialogFragment.setArguments(args);
return collectionSheetDialogFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MifosBaseActivity) getActivity()).getActivityComponent().inject(this);
date = getArguments().getString(Constants.REPAYMENT_DATE);
members = getArguments().getInt(Constants.MEMBERS);
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable
ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_collection_sheet_dialog, container, false);
ButterKnife.bind(this, rootView);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tvDueDate.setText(date);
tvMembers.setText(Integer.toString(members));
}
#OnClick(R.id.btn_fillnow)
public void setBtnFillnow() {
((NewIndividualCollectionSheetFragment) getTargetFragment()).getResponse("FillNow");
}
#OnClick(R.id.btn_cancel)
public void setBtnCancel() {
getDialog().dismiss();
}
}
Can someone help me get around this error so I can persist the TabLayout On back press?
Maybe This Work :
Replace getFragmentManager() instead of getChildFragmentManager()
Try this changing seupViewPager() in IndividualCollectionSheetFragment.java like this
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
adapter.addFragment(new NewIndividualCollectionSheetFragment(), Constants.NEW);
adapter.addFragment(new SavedIndividualCollectionSheetFragment(), Constants.SAVED);
viewPager.setAdapter(adapter);
}
Im trying to pass string data together with images.
Why when running this code I get only image 'nature4' shown but there is no 'nature2' image and strings 'Fragment1' etc..
public class MainActivity extends AppCompatActivity {
private ViewPager viewPager;
private ArrayList<String> strs;
private FragmentPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("x","onCreateActivity");
strs = new ArrayList<String>();
strs.add("Fragment 1");
strs.add("Fragment 2");
strs.add("Fragment 3");
strs.add("Fragment 4");
strs.add("Fragment 5");
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new FragmentPagerAdapter(getSupportFragmentManager(), strs);
viewPager.setAdapter(adapter);
}
public class FragmentPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<String> itemData;
public FragmentPagerAdapter(FragmentManager fm, ArrayList<String> itemData) {
super(fm);
this.itemData = itemData;
}
#Override
public int getCount()
{
return itemData.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
Log.i("x","destroyItem");
}
#Override
public Fragment getItem(int position){
Log.i("x","getItem");
// pass data to fragment
Fragment1 f = Fragment1.newInstance(itemData.get(position));
return f;
}
}
}
And Fragment.class
public class Fragment1 extends Fragment {
public Fragment1(){}
String stringValue;
private int [] images = {R.drawable.nature2,R.drawable.nature4};
public static Fragment1 newInstance(String str)
{
Fragment1 slider=new Fragment1();
Bundle b=new Bundle();
b.putString("stringValue", str);
slider.setArguments(b);
return slider;
}
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("x","onCreateViewFragment");
View view = inflater.inflate(R.layout.fragment1, container, false);
textView = (TextView) view.findViewById(R.id.textView);
ImageView photo = (ImageView) view.findViewById(image);
photo.setImageResource(images[1]);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i("x","onActivityCreatedFragment");
super.onActivityCreated(savedInstanceState);
stringValue = getArguments().getString("stringValue");
textView.setText(stringValue);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i("x","onCreateFragment");
super.onCreate(savedInstanceState);
}
}
I think you need to make your question clear. If you want to pass String stringValue and in imageResId from Activity to Fragment, try the following codes.
public static Fragment1 newInstance(String str, int imageResId) {
Fragment1 slider = new Fragment1();
Bundle b=new Bundle();
b.putString("stringValue", str);
b.putInt("image_resid", imageResId);
slider.setArguments(b);
return slider;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
stringValue = getArguments().getString("stringValue");
imageResId = getArguments().getIn("image_resid");
}
FragmentPagerAdapter:
public class FragmentPagerAdapter extends FragmentStatePagerAdapter {
...
#Override
public Fragment getItem(int position){
Fragment fragment;
String str = itemData.get(position);
int resId;
if (position == 0) {
resId = R.drawable.nature2;
} else if (position == 1) {
resId = R.drawable.nature4;
}
fragment = Fragment1.newInstance(str, resId);
...
return fragment;
}
}
i have written code for image slider but i use drawable images..
Actually i want to know, How to use online images in slideshow instead of
drawables...please help me with complete code as i am new to android..
public class DealsFragment extends Fragment {
private PagerAdapter mPagerAdapter;
public static DealsFragment newInstance() {
DealsFragment fragment = new DealsFragment();
return fragment;
}
public DealsFragment() {
// 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_deals, container, false);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(getActivity(), ImageOneDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageTwoDeals.class.getName()));
fragments.add(Fragment.instantiate(getActivity(), ImageThreeDeals.class.getName()));
mPagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), fragments);
pager.setAdapter(mPagerAdapter);
return view;
}
}
ImageOneDeals.java
public class ImageOneDeals extends Fragment {
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState){
if(container==null){
return null;
}
return (LinearLayout) inflater.inflate(R.layout.image1_deals,container,false);
}
}
ImagePagerAdapter.java
public class ImagePagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public ImagePagerAdapter(FragmentManager fragmentManager, List<Fragment> fragments){
super(fragmentManager);
this.fragments=fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Your Deal Fragment:-
public class DealFragment extends Fragment {
private View rootView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView == null) {
rootView = inflater.inflate(R.layout.slide_view_pager, container, false);
new GetUserImage().execute(); //run your webservices here
}
return rootView;
}
public class GetUserImage extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(getActivity());
pd.setCancelable(true);
pd.setMessage("Loading...");
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.show();
}
#Override
protected String doInBackground(String... params) {
postUserImageData();
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//save your data in a list
// set Adapter after you get data from webservices
mPager = (ViewPager) rootView.findViewById(R.id.slidePager);
ImagePagerAdapter viewImagePagerAdapter = new ImagePagerAdapter(getChildFragmentManager(), TotalCount, imagearr);
mPager.setAdapter(viewImagePagerAdapter);
mPager.getCurrentItem();
}
public void postUserImageData() {
}
}
}
your Adapter:-
public class ImagePagerAdapter extends FragmentPagerAdapter {
private int numOfItemSize;
List<UserImage> arr1;
public ImagePagerAdapter (FragmentManager childFragmentManager, int num_pages, List<UserImage> customMessageListView) {
super(childFragmentManager);
this.numOfItemSize = num_pages;
this.arr1 = customMessageListView;
}
#Override
public Fragment getItem(int position) {
ImageOneDeals userImageDetailFragment = new ImageOneDeals ();
UserImage sc = arr1.get(position);
Bundle bundle = new Bundle();
bundle.putString("ProfilePic", sc.ProfilePic);
bundle.putString("Work", sc.Work);
bundle.putString("BirthTime", sc.BirthTime);
bundle.putString("Message", sc.Message);
userImageDetailFragment.setArguments(bundle);
return userImageDetailFragment;
}
#Override
public int getCount() {
return numOfItemSize;
}
}
your ImageOneDeals :-
public class ImageOneDeals extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Title = getArguments().getString("ProfilePic");
BirthTime = getArguments().getString("BirthTime");
Work = getArguments().getString("Work");
Message = getArguments().getString("Message");
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = (View) inflater.inflate(R.layout.slide_user_image, container, false);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialiseViews();
}
public void initialiseViews() {
ImageView imgDetails = (ImageView) getView().findViewById(R.id.UserimageView);
TextView usrname = (TextView) getView().findViewById(R.id.userName);
TextView usrwork = (TextView) getView().findViewById(R.id.userWork);
// imgLoader.DisplayImage(Title,imgDetails);
Picasso.with(getActivity())
.load(Title)
.placeholder( R.mipmap.add_photo)
.error( R.mipmap.add_photo)
.into(imgDetails);
usrname.setText(Message);
usrwork.setText(Work);
}
}