Android opening a dialogfragment from another fragment throws a casting error - java

I have really browsed through stackoverflow for this solution.
Im trying to access a fragment from another fragment and an error is thrown that
java.lang.ClassCastException: com.noel.myapplication99.IncomeTax cannot be cast to com.noel.myapplication99.IncomeDialog
at com.noel.myapplication99.MainActivity.createOutput(MainActivity.java:119)
at com.noel.myapplication99.IncomeTax$1.onClick(IncomeTax.java:77)
at android.view.View.performClick(View.java:4785)
at android.view.View$PerformClick.run(View.java:19869)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5696)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
These are my codes
MainActivity.java
public class MainActivity extends AppCompatActivity
implements IncomeTax.OnFragmentInteractionListener, ResidentialIncomeTax.OnFragmentInteractionListener, NavigationDrawerFragment.NavigationDrawerCallbacks, IncomeTax.IncomeTaxListener {
public void onFragmentInteraction(Uri uri){
}
private NavigationDrawerFragment mNavigationDrawerFragment;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment=null;
switch(position)
{
case 0:
fragment = new IncomeTax();
mTitle = getString(R.string.title_section1);
break;
case 1:
fragment = new ResidentialIncomeTax();
mTitle = getString(R.string.title_section2);
break;
}
if(fragment!=null)
{
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, fragment, "Tag").commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void createOutput(int i, int f) {
IncomeDialog incomeDialog = (IncomeDialog) getSupportFragmentManager().findFragmentByTag("Tag");
incomeDialog.setOutputText(i, f);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
IncomeTax.java
public class IncomeTax extends Fragment implements AdapterView.OnItemSelectedListener {
IncomeTaxListener activityCommander;
float selectedIncomeType;
public interface IncomeTaxListener{
public void createOutput(int i, int f);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
activityCommander = (IncomeTaxListener) context;
}catch(Exception e){
throw new ClassCastException(toString());
}
}
private OnFragmentInteractionListener mListener;
public IncomeTax() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
Button btnIcCalc;
EditText salary, insuaranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_tax, container, false);
salary = (EditText) view.findViewById(R.id.tvSalary);
insuaranceRelief = (EditText) view.findViewById(R.id.tvReliefCalc);
btnIcCalc = (Button)view.findViewById(R.id.btnIcCalc);
final int iSalary=0;
final int iInsuranceRelief=1;
btnIcCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Dialog box here
activityCommander.createOutput(iSalary, iInsuranceRelief);
FragmentManager manager = getActivity().getSupportFragmentManager();
IncomeDialog myDialog = new IncomeDialog();
myDialog.setTargetFragment(IncomeTax.this, 0);
myDialog.show(manager, "IncomeDialog");
}
});
setSpinnerContent(view);
return view;
}
private void setSpinnerContent( View view )
{
Spinner spinner = (Spinner) view.findViewById( R.id.incomeTypeSpinner );
ArrayAdapter incomeSpinnerArrayAdapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.income_type_array, android.R.layout.simple_spinner_item);
spinner.setAdapter(incomeSpinnerArrayAdapter );
spinner.setOnItemSelectedListener(this);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
selectedIncomeType = 1;
break;
case 1:
selectedIncomeType = 1;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
IncomeDialog.java
public class IncomeDialog extends DialogFragment {
public IncomeDialog() {
// Required empty public constructor
}
TextView netPay, insuranceRelief;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
return view;
}
public void setOutputText(int i, int f){
netPay.setText(i);
insuranceRelief.setText(f);
}

If you want to send data to DialogFragmet then try like this:
Bundle bundle = new Bundle();
bundle.putInt("key1", i);
bundle.putInt("key2", f);
IncomeDialog incomeDialog = new IncomeDialog();
incomeDialog.setArguments(bundle);
Now carry out FragmentTransaction to add this incomeDialog. That will show the dialog.
To receive the bundle data in IncomeDialog:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_income_dialog, null);
netPay = (TextView) view.findViewById(R.id.tvNetPay);
insuranceRelief = (TextView) view.findViewById(R.id.tvPersonalRelief);
Bundle bundle=getArguments();
int i = bundle.getInt("key1");
int f = bundle.getInt("key2");
return view;
}

Related

How to create an custom alertDialog from a tabbed fragment?

Problem:
I'm trying to open a custom dialog after pressing a button in my tabbed fragment.
It's seems like my MainActivity activity is sent to the dialog while i want my tabbed fragment(GroupFragment) to be sent so i can change the editText(for now) in this fragment.
Code:
public class GroupFragment extends Fragment implements AddGroupDialog.AddGroupDialogListener {
private Button addGroupButton;
private TextView textViewNoGroups;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_group, container, false);
addGroupButton = view.findViewById(R.id.addGroupButton);
textViewNoGroups = view.findViewById(R.id.textViewNoGroups);
addGroupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewGroupDialog();
}
});
scaleAnimation(addGroupButton);
return view;
}
private void scaleAnimation(View v){
Animator scale = ObjectAnimator.ofPropertyValuesHolder(v,
PropertyValuesHolder.ofFloat(View.SCALE_X, 0, 1.2f, 1),
PropertyValuesHolder.ofFloat(View.SCALE_Y, 0, 1.2f, 1)
);
scale.setDuration(600);
scale.start();
}
private void addNewGroupDialog(){
AddGroupDialog dialog = new AddGroupDialog();
assert getFragmentManager() != null;
dialog.show(getFragmentManager(), "add new group dialog");
}
#Override
public void applyString(String groupName) {
textViewNoGroups.setText(groupName);
}
}
public class AddGroupDialog extends AppCompatDialogFragment {
private EditText editTextGroupName;
private AddGroupDialogListener listener;
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_add_new_group_dialog, null);
builder.setView(view)
.setTitle("")
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String groupName = editTextGroupName.getText().toString();
listener.applyString(groupName);
}
});
editTextGroupName = view.findViewById(R.id.editTextGroupName);
return builder.create();
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
try {
listener = (AddGroupDialogListener) context;
} catch (ClassCastException e){
throw new ClassCastException(context.toString() +
"Must implement AddGroupDialogListener");
}
}
public interface AddGroupDialogListener{
void applyString(String groupName);
}
}
public class MainActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
#StringRes
private static final int[] TAB_TITLES = new int[]{R.string.tab_text_1, R.string.tab_text_2, R.string.tab_text_3};
private final Context mContext;
public SectionsPagerAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0:
fragment = new GroupFragment();
break;
case 1:
fragment = new AttendanceFragment();
break;
case 2:
fragment = new StatisticsFragment();
break;
}
return fragment;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return mContext.getResources().getString(TAB_TITLES[position]);
}
#Override
public int getCount() {
return TAB_TITLES.length;
}
}
Error:
java.lang.ClassCastException: com.example.attendencetaker.MainActivity#26602bcMust implement AddGroupDialogListener
I hope my explanation of the problem is clear. Thank you!
Make the activity implement your interfaces and so on and then pass all data to the fragment with an method on the fragment. You will need an reference to actual Fragment that is displayed.
In your fragment add a method similar to this:
public void updateData(String data) {
editText.setText(data);
}
And in the override method of the interface in your activity to this:
#Override
public void update(String data) {
fragment.updateData(data);
}
Update
Use this Adapter instead:
public class SectionTabAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragments = new ArrayList<>();
private ArrayList<String> titles = new ArrayList<>();
public SectionTabAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
public void addFragment(Fragment fragment, String title) {
fragments.add(fragment);
titles.add(title);
}
#NonNull
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
In your activity then do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SectionsPagerAdapter sectionTabAdapter = new SectionTabAdapter(this, getSupportFragmentManager());
Fragment groupFragment = new GroupFragment();
Fragment attendanceFragment = new AttendanceFragment();
Fragment statisticsFragment = new StatisticsFragment();
sectionTabAdapter.addFragment(groupFragment, context.getString(R.string.title_1);
sectionTabAdapter.addFragment(attendanceFragment, context.getString(R.string.title_2);
sectionTabAdapter.addFragment(statisticsFragment, context.getString(R.string.title_3);
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionTabAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
}

Two instances of one fragment class works incorrect

I have created tabbed activity, which has viewpager with two instances of one fragment class. This fragment contains listbox, and I have written few functions to
interact with listview items, and one function in activity to do the same thing. The point is when im trying to call fragment methods, it always trying to update the listview of fragment, which was created at first, but when i call function from activity it works absolutely correct. Whats the problem?
Here is the code of activity:
public class CategoriesActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
SparseArray<Fragment> registeredFragments = new SparseArray<>();
Toolbar toolbar;
FloatingActionButton btnAddCategories;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categories);
assignElements();
prepareToolbar();
prepareEelements();
}
public void assignElements() {
toolbar = findViewById(R.id.action_bar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
btnAddCategories = findViewById(R.id.btnAddCategory);
// Set up the ViewPager with the sections adapter.
mViewPager = findViewById(R.id.container);
}
public void prepareToolbar() {
toolbar.setTitle("Категории");
toolbar.setTitleTextColor(getResources().getColor(R.color.colorTextLight));
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public void prepareEelements() {
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = findViewById(R.id.tabs);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
btnAddCategories.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TabCategoriesFragment tabCategoriesFragment = (TabCategoriesFragment) getRegisteredFragment(mViewPager.getCurrentItem());
tabCategoriesFragment.addNewCategory();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.home:
finish();
break;
case R.id.homeAsUp:
finish();
break;
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = TabCategoriesFragment.newInstance(false);
break;
case 1:
fragment = TabCategoriesFragment.newInstance(true);
break;
}
return fragment;
}
#Override
public int getCount() {
return 2;
}
}
}
And of the fragment:
public class TabCategoriesFragment extends Fragment {
private static final String ARG_INCOMING = "Incoming";
private OnFragmentInteractionListener mListener;
public int Incoming = -1;
ListView listView;
ArrayList<Categories> categories;
CategoriesListViewAdapter categoriesListViewAdapter;
DBHelper dbHelper;
SQLiteDatabase sqLiteDatabase;
public TabCategoriesFragment() {
}
public int selectedPostion;
public static TabCategoriesFragment newInstance(boolean Incoming) {
TabCategoriesFragment fragment = new TabCategoriesFragment();
Bundle args = new Bundle();
args.putBoolean(ARG_INCOMING, Incoming);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
if (getArguments().getBoolean(ARG_INCOMING)) {
Incoming = 1;
} else {
Incoming = 0;
}
}
}
public void assignElements(View view) {
dbHelper = new DBHelper(getContext());
sqLiteDatabase = dbHelper.getWritableDatabase();
categories = new ArrayList<>();
categoriesListViewAdapter = new CategoriesListViewAdapter(getContext(), categories);
}
#SuppressLint("ClickableViewAccessibility")
public void prepareElements() {
filldata();
listView.setAdapter(categoriesListViewAdapter);
categoriesListViewAdapter.notifyDataSetChanged();
registerForContextMenu(listView);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
selectedPostion = position;
getActivity().openContextMenu(listView);
return true;
}
});
}
public void deleteCategory(boolean deletecosts, String name) {
try {
//delete from db
} catch (Exception e) {
Toast.makeText(getContext(), "Произошла ошибка" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
public String getTableName() {
if (Incoming == 1) {
return "incomingcategories";
} else {
return "outcomingcategories";
}
}
public String getSign() {
if (Incoming == 1) {
return ">";
} else {
return "<";
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
Objects.requireNonNull(getActivity()).getMenuInflater().inflate(R.menu.edit_category_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
//final int selectedPostion = ((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position;
int id = item.getItemId();
final CheckBox checkBox = new CheckBox(getContext());
switch (id) {
case R.id.categoryDelete:
deleteCategory(categories.get(selectedPosition);
filldata();
categoriesListViewAdapter.notifyDataSetChanged();
case R.id.categorySetbydefault:
break;
case R.id.categoriesSetBydefault:
setCategoryBydefault(categories.get(selectedPostion).description);
filldata();
categoriesListViewAdapter.notifyDataSetChanged();
break;
}
return true;
}
public void setCategoryBydefault(String name) {
//set
}
#Override
public void onStart() {
super.onStart();
prepareElements();
CategoriesActivity categoriesActivity = (CategoriesActivity) getActivity();
}
public void filldata() {
categories.clear();
//do some stuff
}
public void addNewCategory() {
//do some stuff
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_categories, container, false);
listView = view.findViewById(R.id.CategoriesListView);
assignElements(view);
return view;
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}

How to use getChildFragmentManager with a class that extends Dialog fragment

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);
}

Java Passing Data From One Fragment's ListView To Another Fragment

Movie ListView Fragment
Movie Info Fragment
What I have is an app that has a database of movies, in my first tab fragment I have a listview which has all the movies in my database. I want it so when I click a movie in the listview it grabs the movie's database id and moves to the next tab which displays the movie info.
Main Activity (The activity that holds my tabs view pager)
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setOffscreenPageLimit(1);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentMain();
case 1:
return new FragmentManuallyAddMovie();
case 2:
return new FragmentAddInternetMovie();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "MOVIES";
case 1:
return "ADD";
case 2:
return "SEARCH";
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
FragmentMain (Where the movies database is displayed in a listview)
public class FragmentMain extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {
private MoviesDBHandler handler;
private SimpleCursorAdapter adapter;
private ListView lvMovies;
public FragmentMain() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main, container, false);
handler = new MoviesDBHandler(this.getActivity());
v.findViewById(R.id.btn_delete_all_movies).setOnClickListener(this);
lvMovies = (ListView) v.findViewById(R.id.lv_movies);
lvMovies.setEmptyView(v.findViewById(R.id.tv_instructionsa));
lvMovies.setOnItemClickListener(this);
lvMovies.setOnItemLongClickListener(this);
return v;
}
#Override
public void onResume() {
super.onResume();
String[] from = {MoviesDBHelper.MOVIES_TITLE, MoviesDBHelper.MOVIES_GENRE, MoviesDBHelper.MOVIES_YEAR, MoviesDBHelper.MOVIES_PLOT, MoviesDBHelper.MOVIES_RATING, MoviesDBHelper.MOVIES_RUNTIME, MoviesDBHelper.MOVIES_IMAGE_URL};
int[] to = {R.id.tv_title, R.id.tv_genre, R.id.tv_year, R.id.tv_plot, R.id.tv_rating, R.id.tv_runtime, R.id.img_movie_poster};
adapter = new SimpleCursorAdapter(this.getActivity(), R.layout.movie_list_item, handler.getMovies(), from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if(columnIndex == cursor.getColumnIndex(MoviesDBHelper.MOVIES_IMAGE_URL)) {
DatabaseDownloadImage task = new DatabaseDownloadImage((ImageView) view);
task.execute(cursor.getString(columnIndex));
return true;
}
return false;
}
});
lvMovies.setAdapter(adapter);
}
public class DatabaseDownloadImage extends AsyncTask<String, Integer, Bitmap> {
private ImageView imageView;
public DatabaseDownloadImage(ImageView imageView) {
this.imageView = imageView;
}
#Override
protected Bitmap doInBackground(String... params) {
String address = params[0];
HttpURLConnection connection = null;
Bitmap b = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
else {
b = BitmapFactory.decodeStream(connection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return b;
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap == null) {
return;
}
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 120, 180, false));
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
//Delete all movies from database
case R.id.btn_delete_all_movies:
AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
deleteMovieDialog.setTitle("Delete All Movies?");
deleteMovieDialog.setIcon(R.drawable.ic_delete);
deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.deleteAllMovies();
adapter.changeCursor(handler.getMovies());
}
});
deleteMovieDialog.show();
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, final long id) {
AlertDialog deleteMovieDialog = new AlertDialog.Builder(this.getActivity()).create();
deleteMovieDialog.setTitle("Delete Movie?");
deleteMovieDialog.setIcon(R.drawable.ic_delete);
deleteMovieDialog.setButton(DialogInterface.BUTTON_POSITIVE, "No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
deleteMovieDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.deleteMovie(id);
adapter.changeCursor(handler.getMovies());
}
});
deleteMovieDialog.show();
return true;
}
}
All Fragment-to-Fragment communication is done through the associated
Activity. Two Fragments should never communicate directly.
http://developer.android.com/intl/es/training/basics/fragments/communicating.html
You can communicate the two fragments with a static variable in the MainActivity that you change in the first fragment and get the content of this variable in the second fragment.
Update:
Create Movie.class, to save all the data of a one movie:
public class Movie() {
String title;
String genre;
int year;
String plot;
int rating;
int runtime;
String img;
public Movie(String title, String genre, int year, String plot, int rating, int runtime, String img) {
this.title=title;
this.genre=genre;
this.year=year;
this.plot=plot;
this.rating=rating;
this.runtime=runtime;
this.img=img;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title=title;
}
//The same for the other variables
}
and in your MainActivity create a static variable of Movie:
public static Movie movie;
In onClick method save the data of the movie:
MainActivity.movie=new Movie(title, genre, year,plot,rating,runtime,img);
And to get the movie in the second fragment:
String title=MainActivity.movie.getTitle();
String genre=MainActivity.movie.getGenre();
...

Fragment activity reference after screen rotation

I have an Activity with two Action bar tabs with one fragment in each tab. Everything is working properly until a screen rotation. I have references to the fragments in my activity. If i call a method of the fragmet from my activity and that method call getActivity(), the getActivity() return null.
I don't know if i shouldn't have references to the fragments as member fields of my Activity class. If i can't keep that reference in the activity class, how can i get the values of some fields in the layout of a fragment.
Here is my activity class:
public class MyActivity extends ActionBarActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private MyPagerAdapter pagerAdapter;
private ActionBar actionBar;
DetallesAvisoFragment fragment1;
DetallesPiezaFragment fragment2;
ActionMode actionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_avisos);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager = (ViewPager) findViewById(R.id.viewPager);
Intent intent = getIntent();
fragment1 = new Fragment1();
fragment2 = new Fragment2();
List<Fragment> fragmentList = new ArrayList<Fragment>();
fragmentList.add(fragment1);
fragmentList.add(fragment2);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(pagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
actionBar.addTab(actionBar.newTab().setText("Frag1 Tab").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Frag2 Tab").setTabListener(this));
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/**
* This method work properly until screen rotation
*/
public void getValues() {
String value1 = fragment1.getValueFromSomeField();
String value2 = fragment2.getValueFromOtherField();
}
}
The FragmentPagerAdapter class:
public class MyPagerAdapter extends FragmentPagerAdapter{
List<Fragment> fragmentList;
public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
fragmentList = fragments;
}
#Override
public Fragment getItem(int index) {
if (index >= fragmentList.size()) {
return null;
}
return fragmentList.get(index);
}
#Override
public int getCount() {
return fragmentList.size();
}
}
And my Fragment classes:
public class Fragment1 extends Fragment {
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceBundle) {
return inflater.inflate(R.layout.fragment1_layout, container, false);;
}
public String getValueFromSomeField() {
TextView testView = (TextView) getActivity().findViewById(R.id.someField);
return testView.getText().toString();
}
}
public class Fragment2 extends Fragment {
public Fragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceBundle) {
return inflater.inflate(R.layout.fragment2_layout, container, false);;
}
public String getValueFromSomeOtherField() {
TextView testView = (TextView) getActivity().findViewById(R.id.someOtherField);
return testView.getText().toString();
}
}
Note: I need support for SDK 8 so I have to use Fragments using the SupportLibrary
you declare
static final String STORE_FRAGMENT1 = "fragment1";
static final String STORE_FRAGMENT2 = "fragment2";
you Override method onSaveInstanceState to save tag fragment1 and fragment 2;
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
if (fragment1 != null) {
savedInstanceState.putString(STORE_FRAGMENT1,
fragment1.getTag());
}
if (fragment2 != null) {
savedInstanceState.putString(STORE_FRAGMENT2,
fragment2.getTag());
}
super.onSaveInstanceState(savedInstanceState);
}
when OnCreated you get tag fragment1 and fragment 2 to get fragment1 and fragment2 saved before rotation
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_avisos);
actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewPager = (ViewPager) findViewById(R.id.viewPager);
Intent intent = getIntent();
//----edit-------
String TagFragment1;
String TagFragment2;
if (savedInstanceState != null) {
FragmentManager fm = getSupportFragmentManager();
TagFragment1 = savedInstanceState.getString(STORE_FRAGMENT1);
fragment1 = (SubjectFragment) fm
.findFragmentByTag(TagFragment1);
TagFragment2 = savedInstanceState.getString(STORE_FRAGMENT2);
fragment2 = (CircuitFragment) fm
.findFragmentByTag(TagFragment2);
}
else {
fragment1 = new Fragment1();
fragment2 = new Fragment2();
}
//---end--edit-----
List<Fragment> fragmentList = new ArrayList<Fragment>();
fragmentList.add(fragment1);
fragmentList.add(fragment2);
pagerAdapter = new MyPagerAdapter(getSupportFragmentManager(), fragmentList);
viewPager.setAdapter(pagerAdapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
actionBar.setSelectedNavigationItem(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
actionBar.addTab(actionBar.newTab().setText("Frag1 Tab").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Frag2 Tab").setTabListener(this));
}

Categories