onCreate() is not overridden when extending Fragment - android

I have this code:
public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
mCrimeRecyclerView = (RecyclerView) view
.findViewById(R.id.crime_recycler_view);
mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
}
I know that when creating fragment, you separately implement onCreate() and onCreateView(). However, onCreate() is obviously missing here.
Why is that?

you separately call onCreate() and onCreateView()
No, you don't call either. The Fragment lifecycle calls them.
onCreate is not needed to be implemented on a simple Fragment class, only Activity classes
As for the title of your question - it should be called if you add that Fragment to an Activity.

Both onCreate() and onCreateView() can be overridden by you.
onCreate() is more optional and you can use to instantiate some variables (but you hardly need to override it).
onCreateView() is mandatory since you must inflate the view that you want and return it (like return view;).
In the docs:
onCreate()
The system calls this when creating the fragment. Within your implementation, you should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.
onCreateView()
The system calls this when it's time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View from this method that is the root of your fragment's layout. You can return null if the fragment does not provide a UI.
You can also check the Fragment Life Cycle.
As you can see in picture below, in case of returning from back stack, only onCreateView() is called again... So, you can use onCreate() to run some code that can be executed only once (when Fragment is created... like configure some array or something like that)...
Then, you leave onCreateView() just to refresh/inflate the Views before displaying it to the user.
But again: onCreate() is not usually overriden and there's no problem with that... Is always up to you...
:

Related

Why is this fragment's fields null?

In my parent Fragment's onCreateView method, I invoke the Child Fragment Manager to insert a Fragment into the layout. This child fragment contains a few FloatingActionButtons.
After I commit the transaction, I then check the contents of my underlying list (powering a RecyclerView), and based on whether any values are present, I either hide/unhide some of the FloatingActionButtons.
However it's telling me that the buttons are null! Does committing a Fragment transaction not call all of its typical lifecycle events first? Is there a way to force it to wait? Is there a better practice for this?
The commit is not synchronous. There's no guarantee when the fragment's life cycle will execute.
If you need to know when the fragment is "ready", implement a callback from the fragment to the hosting activity letting it know.
class CustomB extends CustomA {
interface Listener {
void onViewCreated();
}
public View onCreateView() {
View v = super.onCreateView();
if (getActivity() instanceof Listener) {
((Listener)getActivity()).onViewCreated();
}
return v;
}
}
Generally speaking you should try to design your fragments to be self-contained. If the fragment is tightly bound to the activity, consider implementing the functionality as a custom View instead.

Would this be the correct way to access an arraylist from a Fragment?

Just need to know the proper syntax to accessing an array that was created in a different class.
public class item_fragment extends Fragment {
ArrayList<MyItems> mylist;
#Override
public View onCreateView( LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
mylist = ((MyApplication) getActivity().getApplication()).getItemsArrayList();
return inflater.inflate(R.layout.course_work_item_fragment,container, false);
}//ends onCreate View
}
I'd suggest having a look at Pass ArrayList from fragment to another fragment(extends ListFragment) using bundle, seListAdapter runtime error
This includes
One thing if you read your code carefully, you have declared ArrayAdapter in Monday_fragment, so this list initialize every time when you replace this fragment with other. So just create a ArrayAdapter in MainActivity and getter, setter for the same and change your methode ArrayList toStringList(Collection entryLogs) in the Monday_fragment like below
That will work fine. Except as a caveat. This might well be called before your activity is created. If you look at the fragment lifecycle you'll see.
The core series of lifecycle methods that are called to bring a fragment up to resumed state (interacting with the user) are:
onAttach(Activity) called once the fragment is associated with its activity.
onCreate(Bundle) called to do initial creation of the fragment.
onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
onStart() makes the fragment visible to the user (based on its containing activity being started).
onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed).
You will note that onViewCreated can easily predate the activity created. As such if you say re-initialize that array, your fragment would have an empty array that never got anything added to it. Or if you checked the size before the onActivityCreated() is called you would still have 0 array size assuming you give the array values after it's done initializing.

onCreateView() called from where and when and what is its parameters when called?

lets assume that we have 2 activity
1: MainActivity (we call this A)
2: FragmetnActivity (B)
A in its layout only had a FrameLayout to hold B
Based on this guid when A is in its onCreate() the first four method of B would called respectively, yes??? they called one-by-one by A or no the A just call the first method and the rest execute respectively???
and about onCreateView() parameters, i know that it had 3 parameters (here):
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
i want to now what would be the second parameters (ViewGroup container) when this method called by caller in my example???
Don't call it manually. onCreateView is part of the Fragment's lifecycle and calling it and the timing is up to Android.
i want to now what would be the second parameters (ViewGroup
container) when this method
is the container that will host the fragment. You usually provide it through a transaction in the add/replace methods

Fragment save the state of a listener

In an Android Fragment, which is a part of a ViewPager, there is a ListView with EditText for filtering.
filterEditText = (EditText) view.findViewById(R.id.filter_friends);
filterEditText. addTextChangedListener(textWatcher);
When I navigate to another Fragment ondestroyview is called and then when I navigate back to this fragment onCreateView is called and the filtering doesn't work anymore, though the instance variables still exist.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_new_game_facebook, container,
false);
return view;
}
How this situation should be handled correctly?
You are probably using a FragmentStatePagerAdapter, which will destroy all non-active fragments to save memory. This is helpful for when you do not know how many fragments you will use until runtime, but is overly aggressive if you know which fragments will be in the pager. Try using a FragmentPagerAdapter instead, which will not destroy the fragments as soon as you navigate away from them, so you will not need to manually persist the state of each fragment and reload it.

Call back method referring to old fragment

I have a fragment activity that contains a Fragment , the Fragment starts an Asynctask that downloads some data, I have implemented a callback method in my Fragment that updates some values in an adapter and a listview. The problem I have is the following: This is my onCreateView method(important part):
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
list=(PullToRefreshListView)v1.findViewById(R.id.listapull);
adapterList=new ListViewAdapter(secciones, mContext);
}
when I rotate the device while the AsyncTask is running, the doInBackground() method keeps running, then on post execute it triggers the listener and starts the callback method in my fragment, this method has the old references of my adapter and my list view:
The fragment and its content are recreated when an orientation change happens and that is correct, but does anyone knows why the call back method is keeping the reference to the adapter and listview that where created before the orientation change?
EDIT:
I have a button that executes the asynctask like this:
asyncRefresh = new PullRefreshTask(taskContext, mContext, secciones);
asyncRefresh.setUpdatePull2RefreshListener(this);
asyncRefresh.execute();
If the user press the button the asyncTask will set old Fragment as the listener and when an orientation change occurs while the asynctask is running, I thought the activated callback method was the one from the newly created fragment method but I'm not sure anymore.
EDIT 2:
I have resolved my problem, as i said in my first edit the call back method was being called for the old fragment . so what I did was to save my asynctask in a variable in another class named "Info" and in on create view i did this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
list=(PullToRefreshListView)v1.findViewById(R.id.listapull);
adapterList=new ListViewAdapter(secciones, mContext);
PullRefreshTasktask task = Info.getAsyncTask();
asyncRefresh = task;
asyncRefresh.setUpdatePull2RefreshListener(this);
}
This way I set the new reference of my fragment in my
setUpdatePull2RefreshListener()
method of the running asynctask
...does anyone knows why the call back method is keeping the reference
to the adapter and listview that where created before the orientation
change?
(This answer comes without knowing your callback implementation or how your AsyncTask looks)
Why the callback shouldn't keep the reference to the old fragment? You set in that Button's listener the current Fragment instance and then do the device rotation while the task runs. You don't have any code in your Fragment that, as it is reconstructed after the configuration changes, will update the callback instance in your AsyncTask to point to the new fragment. Depending on how you use that Fragment you could use the Fragment.setRetainInstance() method which will prevent the Fragment to be destroyed so your task will have the same callback instance even after the rotation. Also have a look at an answer from one of the Android engineers regarding this particular problem.

Categories

Resources