Converting Activity to Fragment - java

I am converting an activity to a fragment so that I can use it within the Android Studio Navigation Drawer template.
I have changed all my activities to extend from fragment, and ensured that I am importing v4 support for fragments.
I have resolved most of the issues that Android Studio has raised...but I am really stuck on the final issue:
I have a fragment that used to be the mainActivity (now called liveview_fragment.java), which calls a class called ApplicationController in a file called ApplicationController.java. However, the line in liveview_fragment that calls ApplicationController gives the following error:
I am new to android/java, with most of my learning coming from tutorials and trial/error. Please could someone point out what I have missed in order to resolve this issue?
Thanks

You'll probably need to pass a context to the ApplicationController. Try with getActivity() or getContext() instead of this

The problem is that liveview_fragment is now a Fragment instead of an Activity. In order to get the hosting Activity, you can call getActivity(). This will probably fix the error.

Always use the getActivity() method to get the context of your attached activity, but always remember one thing: Fragments are slightly unstable and getActivity returns null some times, so for that, always check the isAdded() method of fragment before getting context by getActivity() refer Using context in a fragment

Related

Initialize Fragment With Listener no Constructor

Users will face problems like Could not find Fragment constructor when rotates phone or changes to a Dark mode(when My activity recreates).
Unable to start activity ComponentInfo{e.Quran.Qaz/e.Quran.Qaz.ui.Zhuz.QuranByPage}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment e.Quran.Qaz.ui.Zhuz.PageFragment: could not find Fragment constructor
I have multiple places in my project, where I have to use Fragments. I have solved almost everything with this solution. However, I have to initialize my Fragment with the listener. But, with this solution it is impossible. I wasn't able to comment on that answer due to my StackOverflow reputation.
There was an accepted answer. There was said:
All Fragment classes you create must have a public, no-arg constructor. In general, the best practice is to simply never define any constructors at all and rely on Java to generate the default constructor for you.
And suggested initializing Fragment like this:
public static ProductsFragment newInstance(String id) {
Bundle args = new Bundle();
args.putString("id", id);
ProductsFragment f = new ProductsFragment();
f.setArguments(args);
return f;
}
Are there any ways to initialize it with Listener in the newInstance method?
P.S. I would appreciate any help. It is one of my first questions, don't judge me so strong. :)
Solution is here
Non-default constructors in fragments with DatePicker Callback
In the answer, that worked for me there was written:
The fragment should have an Empty constructor If you don't want to have issues with configurations changed such as screen rotation or low memory case. When configurations changed, Android will re-create Fragment using an empty constructor automatically.
For your case. DateChangeListener should be implemented by
Host Activity - If you Open DatePickerFragment from Activity TargetFragment (by setting setTargetFragment from Fragment) - If you open DatePickerFragment from Fragment (like parent fragment)
From DatePickerFragment, you can access DateChangeListener by casting as below:
(DateChangeListener)this.getActivity() ----> If the host activity implement DateChangeListener (DateChangeListener)this.getTargetFragment() ---> If the parent fragment (setTargetFragment) implement DateChangeListener
It was duplicated question, with another context. So I won't delete this question.

Fragments always go through onAttach to onDestroyView, instead of onCreateView to onDestroyView

I am using 4 fragments in 1 activity. The navigation is done via NavDrawer. Every time I navigate through the fragments, each fragment goes through the following methods:
onAttach() to onDestroyView()
I was expecting them to go through these once and then go through onCreateView() to onDestroyView() but this is not happening.
I would like to initialize certain things only once in onCreate() but now I cannot.
Does anybody have any experience with this?
Hi Thanks for the reply.
I found the problem. I was creating a new fragment in the nav drawers itemselect. To solve it I created an instance of each fragment in main activity and just set this to current fragment instead of creating a new one.
Thanks again

Issue with setContentView() in AsyncTask on fragment view

I was trying to build a typical ListView using the default fragment view in Android - so I need to use setContentView() first to after get the appropriate ListView in that layout. However, I keep getting this error:
Cannot make a static reference to the non-static method
setContentView(int) from the type Activity
I understand this error but do not know how to fix it here (I cannot just go and transform it to static). I am sure my layout name is correct (R.layout.menuList). I am executing this in an AsyncTask under the onPostExecute() section (so it is the same thread as the UI). What am I missing here?
My first thought: Although you've not mentioned but since its complaining about static reference, I assume that you are trying YourActivity.setContentView(R.layout.menuList); ?
Instead try using YourActivity.this.setContentView(R.layout.menuList);. You need correct context.

Android UI fragments. Changing fragment due to button push

I'm trying to open a new fragment based on a button push in a previous fragment. What's the best way to implement this?
I'm curious if it's Activity -> .add + .commit original fragment - > from that fragment.java .replace new fragment?
Or do I need to pass an intent back up to the activity and create/replace that fragment from the activity?
So summarize: Activity A - > Fragment 1 - > Fragment 2.
I'm also slightly confused on what things I [need] to #Override. I think only onCreate and onCreateView [within each fragment]?
I'm only looking for high-level here; I want to struggle through the code myself.
Fragments are generally unaware of their host so I would use the standard callback method to call your activity and ask it to switch fragments.
Create an interface
Have your activity implement the interface.
Cast the getActivity() call to your interface.
Call the interface method.
This is much cleaner than casting the host activity and calling methods on it. It also means your fragment can be hosted in different activities with no cast errors.
http://developer.android.com/training/basics/fragments/communicating.html
You need to cast getActivity like:
((MyActivity) getActivity())
And then if you have that, you can call a method in yout activity:
((MyActivity) getActivity()).replaceFragments(Object... params);
And inside the method you should do the replace fragment process.
So simply you have the right idea.

Fragments onClick method in fragment element

I read quite some articles about fragments, but I am still confused about how to do what.
I have a MainActivity, which displays two fragments side by side. In one of the fragments I have a button and defined in the fragments layout XML for the button
android:onClick="buttonClicked"
Now I want to implement that method
public void buttonClicked(View view)
I would have assumed that this has to be implemented in FragmentA.java and not in MainActivity.java. But it only works if that method is implemented in MainActivity.java. Why is that? To me that doesn't make sense. Pre Honeycomb a method belonging to one activity stayed in that activity, now on a tablet I am merging many activities to one MainActivity and all the different methods are merged? Whatever do you put for example in FragmentA.java then? What if you have to start you an own activity because this app runs on a handheld, then the onClick method has not to be in the MainActivity but in the Activity which needs to be called then. I am pretty confused at the moment...
I'm not sure what the specific problem is, but maybe this will help.
From the Android documentation on Fragments:
You should design each fragment as a modular and reusable activity component. That is, because each fragment defines its own layout and its own behavior with its own lifecycle callbacks, you can include one fragment in multiple activities, so you should design for reuse and avoid directly manipulating one fragment from another fragment.
That is, you should never manipulate a fragment from another fragment; rather, this should be done through the underlying Activity. Read the "Creating event callbacks to the activity" section in this article for more information (it's important stuff!!).
On the other hand, if you want the button to perform an action within the Fragment itself (i.e. if you wanted a Button click to change the text of a TextView within the Fragment), you should implement this in the Fragment, not the Activity (this is because the resulting behavior is contained within the Fragment and has nothing to do with the parent Activity).
Leave a comment and I can clarify if my post is confusing... I only recently began to understand Fragment's myself :).
Well,
I guess it is related to hierarchy of android context structure.
Activity is host of all child views and hence you can say fragment is actually using its host's context.And that's why when you use onClick with fragment system always searches it in Host activity of fragment.
Check it on.
Android developer onClick attribute description
I haven't checked one thing but you could put a test.
By providing implementation in host activity rather than in fragment,but use onClick on layout file of fragment.It should call parent's method.

Categories