This code works:
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
Intent intent = getActivity().getIntent();
String weather = intent.getStringExtra(Intent.EXTRA_TEXT);
if(weather != null) {
TextView textViewWeather=(TextView)rootView.findViewById(R.id.weatherText);
textViewWeather.setText(weather);
BUT if you replace, in the line
(TextView)rootView.findViewById(R.id.weatherText);
rootView by findView() or getActivity, it returns null so the next line creates a run time fatal error which halts the program.
I don't understand why. I thought that the context is the activity?! I'm confused,and can't find a good answer via android developer,so here I am...
Thanks in advance to whoever helps!!
when you call :
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
TextView textViewWeather=(TextView)rootView.findViewById(R.id.weatherText);
the rootView now contains the views that are defined in fargment_detail.xml .
and weatherText is one of them.
but when you call getActivity().findViewById() or findViewById() you want to find the weatherText inside xml file of activity and there is no weatherText there so it will retun null
This line gets the element with id weatherText from its rootView. Which is nothing but your fragment xml file
TextView textViewWeather=(TextView)rootView.findViewById(R.id.weatherText);
Now if you are replacing above code with below
TextView textViewWeather=(TextView)getActivity().findViewById(R.id.weatherText);
now the parent Activity in which this fragment is hosted which has TextView and id weatherText will be searched by framework. Which is obvious is not present at all.
If you remove the rootView you are calling it directly on the activity so those two suggestions are equal (and activity is indeed the context).
But the activity doesn't know about the layout yet, you just inflated it from xml but it has not been given to the activity yet, and therefore can't be found. You do that by returning it from the onCreateView call you are in in your example code.
Related
What is the difference between getView() and getActivity()?
I have used both methods but don't understand the basic difference even methodology of usage are also same in android:
ListView deliverItemList = (ListView) getView().findViewById(R.id.load_item_list);
ListView deliverItemList = (ListView) getActivity().findViewById(R.id.load_item_list);
I have assumed that getView() may produce NullPointerException, share your knowledge with me and which method is recommended?
getActivity() returns the Activity hosting the Fragment, while getView() returns the view you inflated and returned by onCreateView. The latter returns a value != null only after onCreateView returns
From android docs:
getActivity() returns the Activity this fragment is currently
associated with, and getView() returns the root view for the
fragment's layout (the one returned by onCreateView(LayoutInflater,
ViewGroup, Bundle)), if provided.
So, in your case, by the following line of code:
getView().findViewById(R.id.load_item_list);
you are searching for the view in your fragment, but using the following line of code:
getActivity().findViewById(R.id.load_item_list);
you are searching for the view in your activity hosting your fragment.
About your question of which one to use, it depends. If you are trying to inflate fragment, you need to inflate your xml in onCreateView, and using that inflated view you search for your views like this:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.your_layout, container, false);
ListView lv = (ListView)v.findViewById(R.id.view_id);
}
I am new in Android programming.
I created the main Activity of my app style google shop ussing ActionBarSherlock and a NavigationTabs, with fragments, each referencing another activity (Fragment 1 Fragment 2, etc) and each fragment inflating a layout.
However, I'm used to create layouts in xml and then customize them in java. To put a different text depending on the time of day, or according to some data in a database, giving function to buttons, etc.. But in a Fragment Class, I can not even use setContentView to work with each text or button, and set the context for using my database is giving me problems.
How I can customize a xml layout in a fragment?
Or what would be the right thing to do?
Here my Fragment:
public class Fragment1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.menu, container, false);
}
This is more simple then you think. onCreateView instanciate au returns the view for your Fragment. As you said, in a simple Activity you set (and instanciate) the view with setContentView() and then you get your Views with findViewById().
findViewById() asks for the view to return the view item that you want, you can call it from your view before returning it. Like this:
public class Fragment1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.menu, container, false);
// For example, getting a TextView
TextView tv = (TextView) v.findViewById(R.id.myTextView);
// do your job
return v;
}
so far so good, you just need to use the view you are inflating to get everything.
here is an example
View v = inflater.inflate(R.layout.menu, container, false);
Button b = (Button)v.findViewById(r.id.button1);
return v;
inside onActivityCreated you could use:
View mView = getView();
TextView textView = (TextView) view.findViewById(R.id.theIdOfTextView);
where theIdOfTextView is declared inside R.layout.menu.
getView() returns the View you inflated inside onCreateView. You use it only after onCreateView has been executed
When a layout , which is defined for a Fragment and used inside setContentView() method and it has no relation with Activity .
then why we need Activity Reference to access it .
so I want to create a ListView , inside a Fragment . than i have to create it inside Activity layout or inside Fragment layout .
Hey Neil , i have a question because every time I have made a mistake because , i am performing this
TextView txt = ( TextView ) getActivity().findViewById(R.id.txt);
txt.setText("nayak nahi , khalnayak hun mein");
inside oncreateView() so it is creating problem but when ever i am implementing this inside
onActivityCreated() , it is working , so can you please tell me Why this is happening .
if you want to find the view by getActivity(), you should do that after onCreateView is called, because till onCreateView is called the view of fragment is null. So you can do:
#Override
public void onResume() {
super.onResume();
TextView txt = ( TextView ) getActivity().findViewById(R.id.txt);
txt.setText("nayak nahi , khalnayak hun mein");
}
You can define a ListView in a layout for your Fragment. Try something like this in your fragment to define a alternative layout
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
_baseView = inflater.inflate(R.layout.yourlayout, null); //where base view is your upper most parent in your layout
return _baseView;
}
Then in your onActivityCreated you can use _baseView.findViewById('yourListView') to set your ListView. I don't know if this is best practice but it works perfectly for me.
In Fragment you should use its View but getActivity:
public View onCreateView(…){
View rootView = inflater.inflate(R.layout.listview_xml_file, container, false);
ListView ListNewsBelarus = (ListView) rootView.findViewById(R.id.listViewId);
return rootView;
}
I am currently messing around with DialogFragment to learn to use it. I assumed that compared to onCreateView(), onCreate() can do this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
testTextView.setText("SUCCESS!"); //ERROR HERE
}
But I am wrong. Not sure why its not working. The error goes away when I comment out testTextView.setText("Success!");
The error is a NullPointerException, and then it just flags line 39 which is where the offending line of code is. Any clarifications much appreciated.
EDIT:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View testView = (View)inflater.inflate(R.layout.test_dialog_file, container, false);
//instantiated testTextView globally
testTextView = (TextView)testView.findViewById(R.id.set_text);
testTextView.setText("SUCCESS!");
return testView;
}
testTextView is NOT pointing to any object so try something like
testTextView = (TextView) findViewById(R.id.testTextView);
EDIT:
If you see the lifecycle of a fragment, it says that onCreateView is called after onCreate hence your onCreate doesn't have any reference to your object, that is textview in your layout
You haven't used setContentView yet, so you are getting a NPE for the TextView.
onCreate happens before onCreateView. If you want to access something from the layout there, you need to setContentView... which is not a good idea for a DialogFragment.
Move that bit of code to onCreateView after you setContentView and you'll be ok.
For your reference, here's the Fragment Lifecycle:
Did you initialize the testTextView in onCreateView? You have to use a LayoutInflater in onCreateView to get the Layout and then you have to access the TextView via findViewById.
I have a working tablet application which I am now trying to make work on phones too.
On a table there is two fragments on the screen a list fragment and a details fragment.
When on a phone the list fragment appears and creates a new activity when a list item is pressed.
This activity simply creates the fragment in the onCreate() method and commits it to the screen as follows.
// Place an DeallDetailsFragment as our content pane
DealDetailsFragment f = new DealDetailsFragment();
getFragmentManager().beginTransaction().add(android.R.id.content, f).commit();
getFragmentManager().executePendingTransactions();
This is working as expected however from within this activity I need to tell the fragment what details to load and display. In my DealDetailsFragment class I have a updateDeal() method which updates the content as follows.
if (deal==null) { // could be null if user presses the loading deals list item before it loads
return;
}
this.deal=deal;
if (dealTitle==null) { // get the view objects only once
holder = new ViewHolder();
holder.dealHeat=(TextView) getView().findViewById(R.id.dealDetails_heat_textView);
holder.dealPrice=(TextView) getView().findViewById(R.id.dealDetails_price_textView);
holder.dealRetailer=(TextView) getView().findViewById(R.id.dealDetails_retailer_textView);
holder.dealTitle=(TextView) getView().findViewById(R.id.dealDetails_title_textView);
holder.dealDesc=(TextView) getView().findViewById(R.id.dealDetails_desc_textView);
holder.goToButton= (LinearLayout) getView().findViewById(R.id.dealDetails_goToDeal);
holder.dealImage=(ImageView) getView().findViewById(R.id.dealDetails_imageView);
holder.postedBy=(TextView) getView().findViewById(R.id.dealDetails_poster_textView);
holder.datePosted=(TextView) getView().findViewById(R.id.dealDetails_date_textView);
getView() is returning null when the application is ran on a phone where there is only a single fragment shown.
Any ideas? Unfortunately, there is not many fragment examples available online.
Move your method call to be executed during onCreateView, and use the view you are inflating for reference instead of getView(). See the fragment lifecycle for more information: https://developer.android.com/guide/components/fragments.html#Creating
and the documentation of getView() that explains why it returns null before onCreateView(LayoutInflater, ViewGroup, Bundle) returns:
getView()
Get the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.
https://developer.android.com/reference/android/app/Fragment.html#getView()
Moving the method to onCreateView() did not help me.so... Create a global variable mView
protected View mView;
and in onCreateView()
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG, "oncreateView");
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_secure_cloud_drive_folder, container, false);
this.mView = view;
return view;
}
and the replace all your getView() with mView
You can fix that by putting your code inside the onViewCreated()-method, which you should override. Don't forget to call super() on it.
You must check the Android Lifecycle to understand WHY is it null on
onAttach(...) function.
The first function called when fragment is created is added is onAttach(), but actually no view has been created. That's why null is returned when you try to access within this call.
Next function is onCreate()... but there is no view created yet!!!!
The third function called is onCreateView(), and it's here where you have to indicate which is the view attached to this fragment.... And it's only from this call where a view object exists and can be accessed.
Read and learn the full lifecycle here.
Greetings
Because onCreate() is called before onCreateView() , whether you inflate a view in onCreateView() or not, you'll get nothing through getView() in onCreate(), because in that time , onCreate() has not been called yet .
it becomes null basically because you call getview() before the view being inflated. Create a View object and fill using inflaterand then find your UI element see code below
View view = inflater.inflate(R.layout.fragment_albumslist, container, false);
TextView t= (TextView)view.findViewById(R.id.txtTest);
t.setText(strtext);
return view;