Answer the question
In order to leave comments, you need to log in
Why doesn't calling a method from another class work?
The activity class contains a method:
.....
public void openListView(){
FragmentManager manager = getSupportFragmentManager();
androidx.fragment.app.FragmentTransaction transaction = manager.beginTransaction();
ListViewFragment listViewFragment = new ListViewFragment();
transaction.replace(R.id.fragmentFrameLayout, listViewFragment);
transaction.commit();
}
ProductsActivity productsActivity = new ProductsActivity();
productsActivity.openListView();
9913-9913/ru.retail.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: ru.retail.app, PID: 9913
java.lang.IllegalStateException: Activity has been destroyed
at androidx.fragment.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2114)
at androidx.fragment.app.BackStackRecord.commitInternal(BackStackRecord.java:683)
at androidx.fragment.app.BackStackRecord.commit(BackStackRecord.java:637)
at ru.retail.app.Activity.ProductsActivity.openListView(ProductsActivity.java:203)
at ru.retail.app.adapter.ProductsActivity_CategoriesRecyclerViewAdapter.openCategory(ProductsActivity_CategoriesRecyclerViewAdapter.java:121)
at ru.retail.app.adapter.ProductsActivity_CategoriesRecyclerViewAdapter$categoriesButtonListener.onClick(ProductsActivity_CategoriesRecyclerViewAdapter.java:198)
at android.view.View.performClick(View.java:5675)
at android.view.View$PerformClick.run(View.java:22641)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6251)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Answer the question
In order to leave comments, you need to log in
You can't do that, and it's not just about classes and methods. Activity in android is one of the fundamental components. They are always created by the OS, you can only do something in the lifecycle callback methods.
Also, in a fragment , you can get an instance of the Activity to which this fragment is added (getActivity()). True, this can not always be done, but only between onAttach / onDetach calls.
After reading the info on the links you should understand something. Not 100%, but some understanding should arise.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question