how I get the current visible fragment from view pager Adapter..? - android-fragments

I have implemented these lines of code but it is not working .
pagerAdapter= new AbstractPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager)findViewById(R.id.pager);
MyFragment frg = (MyFragment)pagerAdapter.getItem(mViewPager.getCurrentItem());
public class AbstractPagerAdapter extends FragmentPagerAdapter {
public AbstractPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return AbstractDetailFragment.newInstance(objlist.get(position),position == notePosition ? true : false);
}
#Override
public int getCount() {
return objlist.size();
}
#Override
public CharSequence getPageTitle(int position) {
return objlist.get(position).getTitle();
}
}

To get the currently visible fragment instance try the following
viewPager.setOnPageChangeListener(this);
and in the following method
#Override
public void onPageSelected(int position) {
if (position == 0)
setFragmentFor(0);
if (position == 1)
setFragmentFor(1);
.
.
.
// Upto how many fragments you've in your ViewPager
}
so in the setFragmentFor() method you should write your own logic to get the new Instance of Fragment depending upon the argument value passed over the setFragmentFor().

Related

JavaFX: Custom TableViewSelectionModel

I have a TableView which lists several addresses as a preview. The selected address can be edited in a form next to the TableView. In case that the user has made changes to the selected address and changes the selected address in the TableView, I want to ask him if he wants to proceed without saving changes. If no, I want the Tableview to stay at the currently selected position, if the user wants to discard the changes the TableView may perform the selection change.
My approach would have been to extend the SelectionModel of the TableView and only allow the selection to change if the user answers the described dialog or there are no changes. Basically I only want to add an if-clause before changing the selection in the Tableview. Unfortunately, I only found the abstract class “TableViewSelectionModel” and no concrete implementations of it.
Is there any way to obtain this desired behavior without implementing the whole class?
Solved it with James_D's recommendation:
public class ControllableTableSelectionModel<T> extends TableViewSelectionModel<T>{
private TableViewSelectionModel<T> originalModel;
private ControlsTableView controller;
public ControllableTableSelectionModel(TableViewSelectionModel<T> originalModel, ControlsTableView controller) {
super(originalModel.getTableView());
this.originalModel=originalModel;
this.controller=controller;
}
#Override
public boolean isSelected(int row, TableColumnBase<T, ?> column) {
return originalModel.isSelected(row, column);
}
#Override
public void selectLeftCell() {
if(controller.canSelect(this))
{
originalModel.selectLeftCell();
}
}
#Override
public void selectRightCell() {
if(controller.canSelect(this))
{
originalModel.selectRightCell();
}
}
#Override
public void selectAboveCell() {
if(controller.canSelect(this))
{
originalModel.selectAboveCell();
}
}
#Override
public void selectBelowCell() {
if(controller.canSelect(this))
{
originalModel.selectBelowCell();
}
}
#Override
public void selectRange(int minRow, TableColumnBase<T, ?> minColumn, int maxRow,
TableColumnBase<T, ?> maxColumn) {
if(controller.canSelect(this))
{
originalModel.selectRange(minRow, minColumn, maxRow, maxColumn);
}
}
#Override
protected int getItemCount() {
return originalModel.getTableView().getItems().size();
}
#Override
protected T getModelItem(int index) {
return originalModel.getTableView().getItems().get(index);
}
#Override
public void focus(int index) {
originalModel.getTableView().getFocusModel().focus(index);
}
#Override
public int getFocusedIndex() {
return originalModel.getTableView().getFocusModel().getFocusedIndex();
}
#Override
public ObservableList<TablePosition> getSelectedCells() {
return originalModel.getSelectedCells();
}
#Override
public boolean isSelected(int row, TableColumn<T, ?> column) {
return originalModel.isSelected(row, column);
}
#Override
public void select(int row, TableColumn<T, ?> column) {
if(controller.canSelect(this))
{
originalModel.select(row, column);
}
}
#Override
public void clearAndSelect(int row, TableColumn<T, ?> column) {
if(controller.canSelect(this))
{
originalModel.clearAndSelect(row, column);
}
}
#Override
public void clearSelection(int row, TableColumn<T, ?> column) {
if(controller.canSelect(this))
{
originalModel.clearSelection(row, column);
}
}
}
I'd like to add an improvement to your self-answer by making it more generic and applying the "tell, don't ask!" principle:
public class ControllableTableSelectionModel<T> extends TableViewSelectionModel<T> {
#FunctionalInterface
public interface VetoableSelectAction{
void execute();
}
#FunctionalInterface
public interface SelectionVeto {
<T> void allow(TableViewSelectionModel<T> tableViewSelectionModel, SelectionVeto vetoableSelectAction);
}
private final TableViewSelectionModel<T> originalModel;
private final SelectionVeto selectionVeto;
public ControllableTableSelectionModel(TableViewSelectionModel<T> originalModel, SelectionVeto selectionVeto) {
super(originalModel.getTableView());
this.originalModel = originalModel;
this.selectionVeto = selectionVeto;
}
#Override
public boolean isSelected(int row, TableColumnBase<T, ?> column) {
return originalModel.isSelected(row, column);
}
#Override
public void selectLeftCell() {
selectionVeto.allow(this, () -> originalModel.selectLeftCell());
}
// ...
}
I personally have no use for the second parameter in allow():
public class ControllableTableSelectionModel<T> extends TableViewSelectionModel<T> {
// ...
#FunctionalInterface
public interface SelectionVeto{
void allow(VetoableSelectAction vetoableSelectAction);
}
// ...
#Override
public void selectLeftCell() {
selectionVeto.allow(() -> originalModel.selectLeftCell());
}
// ...
}

Disable ContextMenu with dependency to TreeTableView selection

I have a TreeTableView which allows multiselection. I got a ContextMenu for editing or deleting that selected items.
Delete and edit should only be enabled if there is at least one selection.
final BooleanBinding isTableSelectionEmpty = Bindings.isEmpty(this.table.getSelectionModel().getSelectedItems());
this.menuItemDelete.disableProperty().bind(isTableSelectionEmpty);
That is working as expected.
But now I have dependencies on different values of the selected rows. Like for example that the row is system-mandatory and should not be deleted.
I tried the following but it is not working
final BooleanBinding invalidSelection = Bindings.and(Bindings.isEmpty(tableSelection),
Bindings.isNotEmpty(tableSelection.filtered(item -> {
this.logger.trace("filtering :" + item);
return item.getValue().getSystemProperty().get();
})));
this.menuItemDelete.disableProperty().bind(invalidSelection);
Not even the debug-trace is printed and the value of the binding is always false (thus enabling the menu item). Now I am a bit lost. Where is my mistake?
FilteredList relies on a correct ListIterator, but currently there is a bug in the ListIterator the selectedItems list in MultipleSelectionModelBase. This prevents the filtering to properly work. To fix this you could create a ObservableList implementation delegating everything but the ListIterator creation to a source ObservableList. Most IDEs have a functionality to generate this kind of methods automatically, reducing the amount of work to a minimum (e.g.in NetBeans: Generate -> Delegate Method).
public class ObservableListIteratorFix<T> implements ObservableList<T> {
private final ObservableList<T> list;
public ObservableListIteratorFix(ObservableList<T> list) {
this.list = list;
}
#Override
public void addListener(ListChangeListener<? super T> listener) {
list.addListener(listener);
}
#Override
public void removeListener(ListChangeListener<? super T> listener) {
list.removeListener(listener);
}
#Override
public boolean addAll(T... elements) {
return list.addAll(elements);
}
...
private class CustomListIterator implements ListIterator<T> {
private final ListIterator<T> iterator;
private int index;
public CustomListIterator(int index) {
this.iterator = list.listIterator(index);
this.index = index;
}
#Override
public boolean hasNext() {
return iterator.hasNext();
}
#Override
public T next() {
T t = iterator.next();
index++;
return t;
}
#Override
public boolean hasPrevious() {
return iterator.hasPrevious();
}
#Override
public T previous() {
T t = iterator.previous();
index--;
return t;
}
#Override
public int nextIndex() {
return index;
}
#Override
public int previousIndex() {
return index-1;
}
#Override
public void remove() {
iterator.remove();
}
#Override
public void set(T e) {
iterator.set(e);
}
#Override
public void add(T e) {
iterator.add(e);
}
#Override
public void forEachRemaining(Consumer<? super T> action) {
iterator.forEachRemaining(action);
}
}
#Override
public ListIterator<T> listIterator() {
return listIterator(0);
}
#Override
public ListIterator<T> listIterator(int index) {
return new CustomListIterator(index);
}
#Override
public FilteredList<T> filtered(Predicate<T> predicate) {
return new FilteredList<>(this, predicate);
}
...
This allows you to use the class as wrapper the selectedItems which should fix the filtering...
new ObservableListIteratorFix<>(tableSelection).filtered(...)

android fragment reloading (onCreate) each time when back Button pressed

I am new in android using fragments in my Project. first time my fragment is creating then api called and get data load in fragment. here when i clicked at any item i replaced fragment by another fragment there also another api called and load data to fragment.
now here problem situation generated for me.
from here i back Button pressed.
fragment reloading same as first time creating but it should be show data as i left before going to next fragment.
so please provide me solution how i can get same data as i left means savedInstanceState data.
im my first fragment getCategory method call Api and get Data first time when i choose any category i replace fragment with another fragment but when i m returning same getCategory method recall perform same process as it first time.
fragment should not call api method again on backpressed it should show same category on this i clicked before.
my first fragment where calling api......
public class LandingFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private GridLayoutManager gridLayoutManager;
private static RecyclerView category_Grid;
private Fragment myFragment = null;
ProgressBar mProgressView;
View mLoginFormView;
private Category category;
private CategoryAdapter categoryAdapter;
private List<CategoryObject> rowListItem;
private String productId;
private OnFragmentInteractionListener mListener;
public LandingFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment LandingFragment.
*/
// TODO: Rename and change types and number of parameters
public static LandingFragment newInstance(String param1, String param2) {
LandingFragment fragment = new LandingFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v= inflater.inflate(R.layout.fragment_landing, container, false);
return v;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initViews(view);
RecyclerViewListeners();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Activity 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;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
private void initViews(final View v) {
mLoginFormView = (View)v.findViewById(R.id.mainView);
mProgressView = (ProgressBar)v.findViewById(R.id.login_progress);
category_Grid = (RecyclerView)v.findViewById(R.id.cat_grid);
category_Grid.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 3);
category_Grid.setLayoutManager(gridLayoutManager);
}
private void RecyclerViewListeners(){
category_Grid.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), category_Grid, new ItemClickListener(){
#Override
public void onClick(View view, int position) {
String entityId = rowListItem.get(position).getCategoryId();
String catName = rowListItem.get(position).getName();
Integer ishave = rowListItem.get(position).getIshaveSubcategories();
if(ishave==1) {
myFragment = SubcategoryFragment.newInstance(""+catName, "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}else{
myFragment = ProductListFragment.newInstance("", "" + entityId);
ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
public void getCategory() {
showProgress(true);
String URL = getResources().getString(R.string.category_api);
StringRequest req = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.v("Response:%n %s", response);
Gson gson = new GsonBuilder().serializeNulls().create();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals(getResources().getString(R.string.response_success))){
category = gson.fromJson(response, Category.class);
rowListItem = category.getCategory();
if(navigationUpdated){
someEventListener.someEvent(rowListItem);
navigationUpdated = false;
}
Log.d("CATEGORYID::::::::",""+rowListItem.get(1).getCategoryId());
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
return;
}
else if (jsonObject.getString("status").equals(getResources().getString(R.string.login_Er_respose))){
Log.e("","ERRORRRRRR");
return;
}
} catch (JSONException e) {
showProgress(false);
Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
showProgress(false);
VolleyLog.e("Error: ", error.getMessage());
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};
AppController.getInstance().addToRequestQueue(req);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
});
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mProgressView.animate().setDuration(shortAnimTime).alpha(
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
}
});
} else {
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
You can check your rowListItem.size(), if it's size is 0 then call getCategory() service, otherwise load your data from your rowListItem. Here is sample code which I am using to load data from arraylist if it is not empty:
if (mArrayArticle.size() == 0) {
isDataLoading = true;
mRecyclerList.setVisibility(View.INVISIBLE);
getCategory();
} else {
mHomeItemAdapter = new HomeItemAdapter(getActivity(), mArrayArticle, this);
mRecyclerList.setAdapter(mHomeItemAdapter);
}
Here mArrayArticle is my ArrayList, Hope it will help you.
for more clarification i want to tell..
how i implement the #Bhvk_AndroidBee solution
fragment backpressed call onActivityCreated Method so first overridethis method in fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//here you can check null condition for rowListItem
}
}
inside onActivityCreated method I checked the condition like that
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(rowListItem!=null){
categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
category_Grid.setAdapter(categoryAdapter);
categoryAdapter.notifyDataSetChanged();
}else {
//call the method for first time creating your view
getCategory();
}
}
hope this would be helpfull for more strugglers like me...

Custom Observable List implementation, notifying consumers of changes

I have created a custom ObservableList implementation for a list of TreeItems. My custom implementation can listen to various notifications from inside my app (using OSGi EventAdmin), and update itself accordingly. I then expect its consumer (a TreeView widget) to be updated with the changes to the list. However, I can't see how to notify the consumer.
In the ObservableList subclass I am implementing addListener(ListChangeListener), which I would expect to get called when the object is added to the widget. However it is never called; I have no listeners thus no apparent way to notify anyone when the list changes. I must be missing something.
Here is a snippet from my TreeItem implementation, which returns an instance of my ObservableList in response to a getChildren call:
#Override
public ObservableList<TreeItem<DataObject>> getChildren() {
if (needChildren) {
needChildren = false;
children = new MyObservableList();
}
return children;
}
Here is an abridged version of my custom ObservableList implementation, which simply wraps an FXCollections.observableArrayList and adds an OSGi event handler. I listen to changes on the internal list so that I can pass those changes on to my listeners.
public class MyObservableList implements ObservableList<TreeItem<DataObject>>, EventHandler {
private List<ListChangeListener<? super TreeItem<DataObject>>> changeListeners = new ArrayList<>();
private List<InvalidationListener> invalidationListeners = new ArrayList<>();
private ObservableList<TreeItem<DataObject>> theList;
private int size;
public MyObservableList() {
theList = FXCollections.observableArrayList();
theList.addListener(new ListChangeListener<TreeItem<DataObject>>() {
#Override
public void onChanged(Change<? extends TreeItem<DataObject>> change) {
fireValueChangedEvent(change);
}
});
}
#Override
public int size() {
return theList.size();
}
#Override
public boolean isEmpty() {
return (size == 0);
}
#Override
public boolean contains(Object o) {
return theList.contains(o);
}
#Override
public Iterator iterator() {
return theList.iterator();
}
#Override
public boolean remove(Object o) {
return theList.remove(o);
}
#Override
public boolean addAll(Collection c) {
return theList.addAll(c);
}
#Override
public boolean addAll(int index, Collection c) {
return theList.addAll(index, c);
}
#Override
public void clear() {
theList.clear();
}
#Override
public TreeItem<DataObject> get(int index) {
return theList.get(index);
}
#Override
public int indexOf(Object o) {
return theList.indexOf(o);
}
#Override
public int lastIndexOf(Object o) {
return theList.lastIndexOf(o);
}
#Override
public ListIterator listIterator() {
return theList.listIterator();
}
#Override
public ListIterator listIterator(int index) {
return theList.listIterator(index);
}
#Override
public List<TreeItem<DataObject>> subList(int fromIndex, int toIndex) {
return theList.subList(fromIndex, toIndex);
}
#Override
public Object[] toArray(Object[] a) {
return theList.toArray(a);
}
#Override
public void addListener(ListChangeListener<? super TreeItem<DataObject>> listChangeListener) {
changeListeners.add(listChangeListener);
}
#Override
public void removeListener(ListChangeListener<? super TreeItem<DataObject>> listChangeListener) {
changeListeners.remove(listChangeListener);
}
#Override
public boolean addAll(TreeItem<DataObject>... treeItems) {
return theList.addAll(treeItems);
}
#Override
public boolean setAll(TreeItem<DataObject>... treeItems) {
return theList.setAll(treeItems);
}
#Override
public boolean setAll(Collection<? extends TreeItem<DataObject>> treeItems) {
return theList.setAll(treeItems);
}
#Override
public boolean removeAll(TreeItem<DataObject>... treeItems) {
return theList.removeAll(treeItems);
}
#Override
public boolean retainAll(TreeItem<DataObject>... treeItems) {
return theList.retainAll(treeItems);
}
#Override
public void remove(int i, int i2) {
theList.remove(i, i2);
}
#Override
public Object[] toArray() {
return theList.toArray();
}
#Override
public boolean add(TreeItem<DataObject> dataObjectTreeItem) {
return theList.add(dataObjectTreeItem);
}
#Override
public boolean containsAll(Collection<?> c) {
return theList.containsAll(c);
}
#Override
public boolean removeAll(Collection<?> c) {
return theList.removeAll(c);
}
#Override
public boolean retainAll(Collection<?> c) {
return theList.retainAll(c);
}
#Override
public TreeItem<DataObject> set(int index, TreeItem<DataObject> element) {
return theList.set(index, element);
}
#Override
public void add(int index, TreeItem<DataObject> element) {
theList.add(index, element);
}
#Override
public TreeItem<DataObject> remove(int index) {
return theList.remove(index);
}
#Override
public void addListener(InvalidationListener invalidationListener) {
invalidationListeners.add(invalidationListener);
}
#Override
public void removeListener(InvalidationListener invalidationListener) {
invalidationListeners.remove(invalidationListener);
}
private void fireValueChangedEvent(ListChangeListener.Change<? extends TreeItem<DataObject>> change) {
for (ListChangeListener<? super TreeItem<DataObject>> listener : changeListeners) {
listener.onChanged(change);
}
}
#Override
public void handleEvent(Event event) {
// Here I add or remove TreeItem<DataObject> instances to the list based on event.
//
// At this point, onChanged() gets called above in my listener, but my changeListeners list is empty. There is
// no one to pass the Change on to.
}
}
Thanks for any help.
I figured out what's going on here after looking through the JavaFX source.
It turns out that the listening on the ObservableList of children is all set up in the TreeItem itself, not the TreeView as I had somehow assumed. This means that any subclass of TreeView that overrides getChildren() must call super.getChildren() and add its children to the resulting list. This means that using a custom ObservableList implementation is not possible as TreeItem is hardcoded to use FXCollections.observableArrayList() to create the list.
I am taking a different approach to this now where I call super.getChildren(), add my children, and then instantiate another object that holds a reference to that list and does all of my app's event handling business, operating on the list as needed. So my getChildren() method looks something like this now.
private MyEventHandler eventHandler;
private ObservableList<TreeItem<DataObject>> children;
#Override
public ObservableList<TreeItem<DataObject>> getChildren() {
if (needChildren) {
needChildren = false;
children = super.getChildren();
eventHandler = new MyEventHandler(children); // handles app events
}
return children;
}

ViewPager: Performing an Operation In Between Scrolls

Currently, the project in question is set up using a ViewPager which has an adapter capable of loading 4 different fragments. The last 3 Fragments are dependent upon the first fragment giving them a value (the SQL foreign key comes from the a value from the first item in the ViewPager).
My question is: how do I retrieve a value from the first Fragment's EditText, perform an SQL Operation and pass a value once the user attempts to "swipe" to the next tab?
Note, that I am trying to do this on swipe, and not via button. So far I have attempted to override OnPageScrolled, which yielded a null pointer when referring to the first fragment. I am assuming that the first fragment has been destroyed when I attempt to call it's hasPopulatedClassName() function
For Reference, the offending activity. Note the comment under OnPageScrolled
public class ActivityClassEdit extends FragmentActivity implements ViewPager.
private ClassEditPagerAdapter aPager;
//Views
private ViewPager vPager;
//Boolean telling us if we are good to move on to Criteria, People, or Links
private boolean mClassInserted;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class_edit);
if(getIntent().hasExtra(CM.BKEY_PASSED_SEMESTERKEY)){
//Set the views
vPager=(ViewPager) findViewById(R.id.ace_pager);
//Instantiate the pager and set it
aPager=new ClassEditPagerAdapter(this, getIntent().getExtras().getLong(CM.BKEY_PASSED_SEMESTERKEY, -1));
vPager.setAdapter(aPager);
vPager.setOnPageChangeListener(this);
} else {
//TODO handle not having a semester key
}
}
//=============PageScrollListener==============
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if(!mClassInserted) {
if (position == 1) {
//FragmentClassEdit fCE = (FragmentClassEdit) aPager.getRegisteredFragment(0);
FragmentClassEdit fCE = (FragmentClassEdit) aPager.getRegisteredFragment(0);
if (fCE.hasPopulatedClassName() == false) {
vPager.setCurrentItem(0);
Toast.makeText(this, getResources().getString(R.string.toast_typeInClassName), Toast.LENGTH_LONG).show();
} else {
//Save to shared Preferences, in case we have to delete on user cancellation
//null pointer here!!!
long mInsertedClassID= Long.getLong(fCE.insertClass());
getSharedPreferences(CM.SP, Activity.MODE_PRIVATE).edit().putLong(CM.SP_LASTINSERTEDCLASS, mInsertedClassID).apply();
aPager.setClassID(mInsertedClassID);
vPager.setCurrentItem(position);
}
}
} else {
vPager.setCurrentItem(position);
}
}
And here is the ViewPagerAdapter:
public class ClassEditPagerAdapter extends FragmentStatePagerAdapter{
private FragmentClassEdit fCE;
private Fragment fCrit;
private Fragment fLinks;
private Fragment fPeople;
private FragmentManager fragmentManager;
private String[] sTabText;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
private Context ctx;
private long semID;
private long cID;
public ClassEditPagerAdapter(FragmentActivity context, long semesterID){
super(context.getSupportFragmentManager());
fragmentManager=context.getSupportFragmentManager();
ctx= context;
sTabText = ctx.getResources().getStringArray(R.array.cepa_titles);
cID=-1;
semID=semesterID;
}
public void setClassID(long classID){
cID=classID;
}
#Override
public Fragment getItem(int fragID) {
switch (fragID) {
//FragClassEdit
case 0:
fCE = FragmentClassEdit.newInstance(semID);
return fCE;
//FragTypeEdit
case 1:
fCrit = FragmentCriteriaEdit.newInstance(cID);
return fCrit;
//FragPeople
case 2:
fPeople = FragmentPeopleEdit.newInstance(cID);
return fPeople;
//FragLinks
case 3:
fLinks = FragmentLinkEdit.newInstance(cID);
return fLinks;
}
return null;
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
#Override
public int getCount() {
return 4;
}
#Override
public String getPageTitle(int position){
return sTabText[position];
}
}

Resources