How do I fix Fragment already added in my code? - java

I open a dialog fragment from A fragment, and when the dialog fragment is closed,
I want to switch from A fragment to B fragment at the same time.
But I keep getting Fragment already added error.
I am using show() instead of replace() to change the screen.
Fragment already added error was easily solved on the web, but
I don't work out weird.
Probably there is a problem with my code, please let me know where the problem is.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNav;
FragmentManager fm;
FragmentTransaction transaction;
Fragment curFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fm = getSupportFragmentManager();
transaction = fm.beginTransaction();
curFrag = fm.getPrimaryNavigationFragment();
String tag = String.valueOf(item.getItemId());
int id = item.getItemId();
if(curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if(fragment == null) {
if(id == R.id.list)
fragment = new WorkoutListFragment();
transaction.add(R.id.content_layout, fragment, tag);
}
else {
transaction.show(fragment);
}
transaction.setPrimaryNavigationFragment(fragment);
transaction.setReorderingAllowed(true);
transaction.commitNow();
return true;
}
});
}
// Method for screen switching
public void onFragmentChanged() {
// transaction = fm.beginTransaction();
String tag = "WriteRoutine";
curFrag = fm.getPrimaryNavigationFragment();
if (curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null) {
fragment = new WriteRoutineFragment();
fragment.setArguments(curFrag.getArguments());
transaction.add(R.id.content_layout, fragment, tag);
} else {
transaction.show(fragment);
}
transaction.setReorderingAllowed(true);
transaction.commit();
}
}
WorkoutListFragment.java (A Fragment)
public class WorkoutListFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getParentFragmentManager().setFragmentResultListener("result", this, new FragmentResultListener(){
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle result) {
if(result != null)
WorkoutListFragment.this.setArguments(result);
titleData = result.getStringArrayList("title");
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_workout_list, container, false);
initViews(rootView);
((AppCompatActivity) getActivity()).setSupportActionBar((toolbar));
return rootView;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
menu.clear();
inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.record_item_add, menu);
}
#Override // open dialog
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
BodyPartDialogFragment dialog = new BodyPartDialogFragment();
dialog.show(getActivity().getSupportFragmentManager(), "BodyPartDialog");
return true;
}
}
DialogFragment.java
public class BodyPartDialogFragment extends DialogFragment {
Button startBtn;
ArrayList<String> bodypart_strData;
int selectedNum;
final static String TAG = "DialogFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_body_part_dialog, null);
startBtn = view.findViewById(R.id.check);
// A D D
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedNum == 0){
Toast.makeText(getContext(), "Plaese select", Toast.LENGTH_SHORT).show();
}
else {
MainActivity activity = (MainActivity) getActivity();
Bundle result = new Bundle();
result.putStringArrayList("title", bodypart_strData);
getParentFragmentManager().setFragmentResult("result", result);
activity.onFragmentChanged();
dismiss();
}
}
});
return view;
}

Upon testing your code, you'll just need to reinstantiate the transaction object before adding/replacing your fragment.
So, you need to add below in onFragmentChanged():
transaction = getSupportFragmentManager().beginTransaction();
And here it is:
// Method for screen switching
public void onFragmentChanged() {
String tag = "WriteRoutine";
transaction = getSupportFragmentManager().beginTransaction(); // <<< THE CHANGE IS HERE
curFrag = fm.getPrimaryNavigationFragment();
if (curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null) {
fragment = new WriteRoutineFragment();
fragment.setArguments(curFrag.getArguments());
transaction.add(R.id.content_layout, fragment, tag);
} else {
transaction.show(fragment);
}
transaction.setReorderingAllowed(true);
transaction.commit();
}

Related

android shared element transition with fragments doesn't show exit animation

I have a main activity that handles the static elements, attached to the main activity there is a fragment, this fragment has a tablelayout with a viewpager2, each page shows a recycler view.
The shared element transition works well from FRAGMENT A(Tab_1) to FRAGMENT B(ElementDetails), but when I press the back button, the return shared element transition doesn't work.
TAb_1(Fragment A):
public class tab1_anime extends Fragment {
private RecyclerView recycler_view;
public static AFSGAdapter adapter;
private ArrayList<AddElement> a_list = new ArrayList<>();
private Context context;
public tab1_anime(){ };
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
View view = inflater.inflate(R.layout.fragment_tab1_anime, container, false);
recycler_view = view.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
context = getActivity();
LinearLayoutManager layoutManager_anime_crucial = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
recycler_view.setLayoutManager(layoutManager_anime_crucial);
recycler_view.setItemAnimator(new DefaultItemAnimator());
int spanCount = 3; // 3 columns
int spacing = 10; // 10 for my phone, 35 for the emulator
boolean includeEdge = true;
recycler_view.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
adapter = new AFSGAdapter(a_list, getContext(), this);
adapter.setDataSet(a_list);
recycler_view.setAdapter(adapter);
recycler_view.scheduleLayoutAnimation();
adapter.notifyDataSetChanged();
return view;
}
public void openShowElementFragment(int position, View view) {
AddElement element = a_list.get(position);
ShowElementFragment showElementFragment = new ShowElementFragment();
Bundle bundle = new Bundle();
bundle.putString("transitionName", "transition" + position);
bundle.putSerializable("element", element);
showElementFragment.setArguments(bundle);
((MainActivity) context).showFragmentWithTransition(this, showElementFragment, "showElementFragment", view, "transition" + position);
}
}
ShoeElementDetails(Fragment B):
public class ShowElementFragment extends Fragment {
private AddElement elemento;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_show_element, parent, false);
//showelement_background_image.setTransitionName("example_transition");
Bundle b = getArguments();
if (b != null) {
String transitionName = b.getString("transitionName");
elemento = (AddElement) b.getSerializable("element");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
showelement_image.setTransitionName(transitionName);
}
}
//postponeEnterTransition();
Glide.with(this)
.load(elemento.image_url)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(false)
.apply(RequestOptions.bitmapTransform(new BlurTransformation(10, 3)))
.into(showelement_background_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().getSharedElementEnterTransition().setDuration(800);//.setInterpolator(new AccelerateInterpolator());
getActivity().getWindow().getSharedElementReturnTransition().setDuration(850);//.setInterpolator(new DecelerateInterpolator());
}
showelement_backarrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, new MainFragment())
.commit();
//startActivity(new Intent(ShowElementActivity.this, AnimeActivity.class));
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
postponeEnterTransition();
OneShotPreDrawListener.add(view, this::startPostponedEnterTransition);
super.onViewCreated(view, savedInstanceState);
}
}
Inside the adapter I handle the click of the element to start the transition:
inside adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public void onClick(View v) {
fragment.openShowElementFragment(holder.getAdapterPosition(), v.findViewById(R.id.main_image));
}
});
the openShowElementFragment called is inside main activity:
public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
FragmentManager fragmentManager = getSupportFragmentManager();
// check if the fragment is in back stack
boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
if (fragmentPopped) {
// fragment is pop from backStack
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentHolder, newFragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.addSharedElement(sharedView, sharedElementName);
fragmentTransaction.commit();
}
}
It's my first time approaching with fragments.

Unable to send fragments back in Java

I am currently developing an Android mobile application and I encountered a problem. Although I tried and searched many sites and resources in stackoverflow, I could not find the solution. I am sharing my codes below.
What I want to do i want the fragments to go back when the back button is pressed, but it goes back to the activity part. As a result of how many Fragments are clicked, it returns to the activity part. What can I do. Sorry for my missing English.
InternalFilesActivity
public class InternalFilesActivity extends AppCompatActivity {
private FragmentManager manager;
private FragmentTransaction transaction;
private File[] files;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_internal_files);
String path = Environment.getExternalStorageDirectory().toString();
File directory = new File(path);
files = directory.listFiles();
manager = getSupportFragmentManager();
Fragment fr = FilesFragment.newInstance(files);
transaction = manager.beginTransaction();
transaction.add(R.id.fragment_container, fr);
transaction.commit();
}
#Override
public void onBackPressed() {
if (manager.getBackStackEntryCount() > 1) {
manager.popBackStackImmediate();
} else {
super.onBackPressed();
}
}
}
FilesFragment
public class FilesFragment extends Fragment {
private static File[] frFiles;
public FilesFragment() {
}
public static FilesFragment newInstance(File[] files) {
FilesFragment fragment = new FilesFragment();
frFiles = files;
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_files, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView internalList = view.findViewById(R.id.lv_internal);
InternalListAdapter adapter = new InternalListAdapter(frFiles, getContext(), getActivity());
internalList.setAdapter(adapter);
}
}
InternalListAdapter
public class InternalListAdapter extends BaseAdapter {
public File[] dataList;
public Context context;
public FragmentActivity activity;
public InternalListAdapter(File[] dataList, Context context, FragmentActivity activity) {
this.dataList = dataList;
this.context = context;
this.activity = activity;
}
#Override
public int getCount() {
return dataList.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = LayoutInflater.from(context).inflate(R.layout.internal_list_item, parent, false);
TextView fileName = convertView.findViewById(R.id.tv_file_name);
fileName.setText(dataList[position].getName());
ImageView listImage = convertView.findViewById(R.id.iv_list_image);
if (dataList[position].isDirectory()) {
listImage.setImageResource(R.drawable.ic_directory);
} else {
listImage.setImageResource(R.drawable.ic_file);
}
LinearLayout listItemLayout = convertView.findViewById(R.id.ll_list_item);
listItemLayout.setOnClickListener(v -> {
if (dataList[position].isDirectory()) {
createFragment(position);
}
});
return convertView;
}
private void createFragment(int position) {
FragmentManager manager = activity.getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fr = FilesFragment.newInstance(dataList[position].listFiles());
transaction.replace(R.id.fragment_container, fr);
transaction.commit();
}
}
in back press you have implemented Fragment popping up from back stack, but you are not adding your fragments to back stack in fact
use addToBackStack(someName) method for putting your fragments in there and then your back press should start working (more info in this SO topic)
manager = getSupportFragmentManager();
Fragment fr = FilesFragment.newInstance(files);
transaction = manager.beginTransaction();
transaction.addToBackStack("initialFragment"); // also may be null
transaction.add(R.id.fragment_container, fr);
transaction.commit();
check my answer.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
int count = getSupportFragmentManager().getBackStackEntryCount();
if(count==1){
finish();
}
}
return super.onKeyDown(keyCode,event);
}
SOLVED
The problem was that I used fragment as an instance. The problem was resolved when I created and used a new object.
private static File[] files;
public FilesFragment(File[] files) {
this.files = files;
}
I used the new FileManager() code instead of FileFragment.newInstance()

Fragments - tag, condition and show

I will be very grateful for the analysis of these lines of code, because I do not understand the relationship between them. Especially if I
I will change tags to 2 different tags, nothing changes in the application. In addition, if the condition if is removed, there are also no changes. In the comments I have a brief translation, I am still unable to understand these three lines.
Fragment fr = manager.findFragmentByTag("AddCity");
What role does this condition fulfill?
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();
}
And:
fr2.show(manager, "AddCity");
This is the whole code snippet
/*
I create a variable manager, and then I get a FragmentManager and assign it to the variable manager,
thanks to the variable manager, I can run actions on fragments
*/
FragmentManager manager = getSupportFragmentManager();
Fragment fr = manager.findFragmentByTag("AddCity");//I created fr variable and ???
Fragment1 fr1 = (Fragment1)
manager.findFragmentById(R.id.list); // I created fr1 variable and assigned fragment list to the variable fr1
if (view.equals(b1)) {
if (fr != null) {// if ???
manager.beginTransaction().remove(fr).commit();//Creates a new transaction to change fragments at runtime, removes an existing fragment, plans to commit the transaction.
}
Fragment2 fr2 = new Fragment2();//Created object Fragment2
fr2.show(manager, "AddCity");//Display the dialog box by adding the fragment to the given FragmentManager.
}
EDIT:
This is my MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button b1, b2;
static int itemSelected;
static boolean isSelected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = findViewById(R.id.button1);
b2 = findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
FragmentManager manager = getSupportFragmentManager();//
Fragment fr = manager.findFragmentByTag("addCity");
Fragment1 fr1 = (Fragment1)
getSupportFragmentManager().findFragmentById(R.id.list);
if (view.equals(b1)) {
if (fr != null) {
manager.beginTransaction().remove(fr).commit();
}
Fragment2 fr2 = new Fragment2();
fr2.show(manager, "");
}
if (view.equals(b2)) {
if (!fr1.cities.isEmpty()) {
if (isSelected) {
fr1.cities.remove(itemSelected);
fr1.adapter.notifyDataSetChanged();
itemSelected = 0;
isSelected = false;
fr1.getListView()
.setSelector(android.R.color.transparent);
} else {
Toast.makeText(this, "Select city to be deleted",
Toast.LENGTH_LONG).show();
}
}
}
}
}
Fragment1:
public class Fragment1 extends ListFragment {
ArrayList<String> cities = new ArrayList<>();
ArrayAdapter<String> adapter;
String name;
public Fragment1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment1,
viewGroup, false);
adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, cities);
setListAdapter(adapter);
return view;
}
public void onListItemClick(ListView listView, View view,
int position, long id) {
MainActivity.itemSelected = position;
MainActivity.isSelected = true;
getListView().setSelector(android.R.color.holo_blue_dark);
}
}
Fragment2:
public class Fragment2 extends DialogFragment {
EditText et;
public Fragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment2, viewGroup, false);
}
public void onViewCreated(View view, Bundle savedInstanceState) {
et = view.findViewById(R.id.editText);
Button b = view.findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String country = et.getText().toString();
Fragment1 fr1 = (Fragment1)
getFragmentManager().findFragmentById(R.id.list);
if (!country.equals("")) {
fr1.cities.add(country);
fr1.adapter.notifyDataSetChanged();
}
getActivity().getSupportFragmentManager().beginTransaction()
.remove(Fragment2.this).commit();
}
});
}
}
You are adding another fragment in the same name. Can you try changing the name to something else and try?
Like
fr2.show(manager, "Add District");
so that you can find the difference.
Adding a fragment
Fragment fr2 = new Fragment();
FragmentManager manger = getSupportFragmentManager();
FragmentTransaction ft = manger.beginTransaction();
ft.add(R.id.placeHolder, fr2,tag);
ft.commitAllowingStateLoss();
if(fr2.isAdded()){
fr2.show(manager, "");
}
Before calling show, you have to add the fragment.

Passing data from Fragments to Fragments error

I use a Bundle to pass data between Fragments. However, I ran into some problems. My Bundle is not working, I do not know why. Because I do everything as I did before.
Here is my Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jegyek);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_lista,
new Tantargylista()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new ObjectList();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new ExamList();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_lista,
selectedFragment).commit();
return true;
}
};
}
My first Fragment:
View v;
DB mydb;
ListView listView;
String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Jegyekview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Empty", Toast.LENGTH_SHORT).show();
} else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
bundle.putString("test", teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
FragTan.commit();
}
}
});
}
return v;
}
There is a second Fragment which has a Button. If the Button is pressed, then the third Fragment is open.
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});
My third Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("test");
//Here crash the program. :/
return rootView;
}
You have not passed anything from your second Fragment while opening your third Fragment. Hence you need to do something like the following.
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
// Get a bundle
Bundle bundle = new Bundle();
bundle.putString("test", teszt);
// Set as argument
jegyekAllando.setArguments(bundle);
// Begin the transaction
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});
I think the problem is your second fragment is not passing the bundle from the first fragment to the third fragment in this code
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});

Android opening a dialogfragment from another fragment throws a casting error

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

Categories