Android - Add code to a fragment
android, fragment
Solution
First of all I can see a few mistakes in your code.First of all as `@user1873880` mentioned, `onCreate()` is always called before `onCreateView()`, so you should consider dealing with your views in `onCreateView()`. Second mistake which I can see is that you are not creating your `View` as it's designed to be used on `Fragment`. In my opinion the way your Fragment should look is like this :
public class FragmentOne extends Fragment {
private static final String TAG = "FragmentOne";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
// create your view using LayoutInflater
return inflater.inflate(R.layout.fragmentone, container, false);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// do your variables initialisations here except Views!!!
}
public void onViewCreated(View view, Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
// initialise your views
EditText etData = (EditText) view.findViewById(R.id.etData);
}
}
Hope this helps you! : )
Problem
I am a beginner in coding for Android and i am trying to do an application with two fragments. Unfortunately, when i add code to set action to my layout, it makes my application crash, so i'm wondering where i should put my code on the fragment file. If i take out the function onCreate, the application doesn't crash and my layout is good. Here is my code. Thank you so much for your answer. ``` public class FragmentOne extends Fragment{ public static final String TAG = "FragmentOne"; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = View.inflate(getActivity(), R.layout.fragmentone, null); return v; } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final EditText etData = (EditText) getView().findViewById(R.id.etData); } } ```