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);
}
}
Related
My app creates drawer submenus from sharedpreference values. These submenus are basically called "interests" or categories. I'm trying to move this same functionality to tablayout since that is much more convenient but can't seem to get it to work!
Edit: New code based on suggestions.
TabsFragment:
public class HomeTabsFragment extends Fragment implements ViewPager.OnPageChangeListener {
private View view;
private SectionsPagerAdapterHome homePageAdapter;
public ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.view = inflater.inflate(R.layout.fragment_articles_tabs, container, false);
TabLayout tabLayout = view.findViewById(R.id.home_list_tabs);
viewPager = view.findViewById(R.id.home_list_tabs_container);
homePageAdapter = new SectionsPagerAdapterHome(getFragmentManager());
viewPager.setAdapter(homePageAdapter);
viewPager.setOffscreenPageLimit(tabLayout.getTabCount());
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
if(SharedPrefernces.getUserInterests()!=null) {
List<String> my_interests = SharedPrefernces.getUserInterests();
Collections.sort(my_interests, String::compareToIgnoreCase);
my_interests.add(0, getString(R.string.all_stories));
for (String interest : my_interests) {
homePageAdapter.addTabPage(new FeedsFragment(), interest);
}
}
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Do something that differs the Activity's menu here
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = homePageAdapter.getFragment(position);
if (fragment != null) {
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Adapter:
public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private FragmentManager fragmentManager;
private ArrayList fragmentTags = new ArrayList();
private ArrayList<String> titles = new ArrayList();
protected SectionsPagerAdapterHome(FragmentManager fm) {
super(fm, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
fragmentManager = fm;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
fragmentTags.add(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
Object tag = fragmentTags.get(position);
if (tag != null) {
fragment = fragmentManager.findFragmentByTag(String.valueOf(tag));
}
return fragment;
}
#Override
public Fragment getItem(int position) {
return FeedsFragment.newInstance();
}
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragmentTags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
}
I'm not sure how I can achieve this so need help.
Since you are using a ViewPager with an Adapter instead of using tabLayout.addTab(...) you have to add the item in the adapter.
Something like:
public class SectionsPagerAdapterHome extends FragmentPagerAdapter {
private ArrayList fragmentTags = new ArrayList();
private ArrayList<String> titles = new ArrayList();
//.....
public void addTabPage(Fragment fragment,String title) {
titles.add(title);
fragmentTags.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragmentTags.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tables.get(position);
}
}
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);
}
I would like to change text other fragment in tabs when user input edittext and enter this
and I have some problem about viewpager , it's not refresh automaticly when user enter, but if user swipe tab refresh it's work!
example :
current in tab1 when user enter ,tab1 is not refresh but user swipe to tab2 ,tab2 is refresh and user swipe to tab1 ,tab1 is refresh!
I want to viewpager is refresh automaticaly
thanks for your help and sorry my english is not good.
my activity
public class SearchActivity extends AppCompatActivity {
public static EditText edt_home_titlebar;
ImageView btn_home_slidemenu;
public static String query_text=null;
ViewPager pager;
SmartTabLayout tabs;
private ArrayList<PagerItem> mTabs = new ArrayList<PagerItem>();
MyPagerAdapter myPager;
#Override
protected void onDestroy() {
super.onDestroy();
query_text=null;
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
edt_home_titlebar = (EditText) findViewById(R.id.edt_home_titlebar);
btn_home_slidemenu = (ImageView) findViewById(R.id.btn_home_slidemenu);
initTabs();
pager = (ViewPager) findViewById(R.id.pager);
tabs = (SmartTabLayout) findViewById(R.id.tabs);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
tabs.setDistributeEvenly(true);
tabs.setViewPager(pager);
Log.d("SearchActivity", "onCreate: " + query_text);
edt_home_titlebar.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
query_text = edt_home_titlebar.getText().toString().trim();
Log.d("SearchActivity", "onEditorAction4: " + query_text);
return true;
}
return false;
}
});
btn_home_slidemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return mTabs.get(position).createFragment(position);
}
#Override
public int getCount() {
return mTabs.size();
}
#Override
public CharSequence getPageTitle(int position) {
Log.d("SearchActivity","mTabs=>"+mTabs.get(position).getTitle().toString());
return mTabs.get(position).getTitle().toString();
}
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
}
class PagerItem {
private final CharSequence mTitle;
PagerItem(CharSequence title) {
mTitle = title;
}
Fragment createFragment(int i) {
Log.d("SearchActivity","getI=>"+i);
// Fragment fragment = null;
switch (i) {
case 0:
SearchSlideFragment fragment1 = new SearchSlideFragment();
Log.d("SearchActivity","(FRIEND)title=>"+mTabs.get(0).getTitle().toString());
return fragment1;
case 1:
SearchPage fragment2 =new SearchPage();
Log.d("SearchActivity","get(1)title=>"+mTabs.get(1).getTitle().toString());
return fragment2;
case 2:
SearchDiaryFragment fragment3 = new SearchDiaryFragment();
Log.d("SearchActivity","(DIARY)title=>"+mTabs.get(2).getTitle().toString());
return fragment3;
case 3:
SearchQuestFragment fragment4 = new SearchQuestFragment();
Log.d("SearchActivity","(QUEST)title=>"+mTabs.get(3).getTitle().toString());
return fragment4;
case 4:
Log.d("SearchActivity","get(4)title=>"+mTabs.get(4).getTitle().toString());
SearchReviewFragment fragment5 = new SearchReviewFragment();
return fragment5;
case 5:
SearchTopicFragment fragment6 = new SearchTopicFragment();
Log.d("SearchActivity","(TOPIC)title=>"+mTabs.get(5).getTitle().toString());
return fragment6;
default:
return null;
}
}
CharSequence getTitle() {
return mTitle;
}
}
private void initTabs(){
mTabs.clear();
mTabs.add(new PagerItem(this.getResources().getString(R.string.tx_people)));
mTabs.add(new PagerItem(this.getResources().getString(R.string.tx_slide_page)));
mTabs.add(new PagerItem(this.getResources().getString(R.string.tx_diary)));
mTabs.add(new PagerItem(this.getResources().getString(R.string.tx_quest)));
mTabs.add(new PagerItem(this.getResources().getString(R.string.tx_review)));
mTabs.add(new PagerItem(this.getResources().getString(R.string.tx_topic)));
}
}
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;
}
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();
...