I am new to Android.
I have read through the threads and tried various solutions but none worked for me. Here is what I have which works.
public class Tab1 extends Fragment {
TextView mTextView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
mTextView = (TextView)rootView.findViewById(R.id.myTextView1);
mTextView.setText("This works"); //This works fine
return rootView;
}
}
This will update the TextView just fine with the words "This works".
But when I try this to make it more flexible so I can update it while the app is running, it fails on me with this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.schoolproject.tabs.Tab1.changeText(Tab1.java:29)
public class Tab1 extends Fragment {
TextView mTextView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab1, container, false);
mTextView = (TextView)rootView.findViewById(R.id.myTextView1);
return rootView;
}
public void changeText(String mText) {
mTextView.setText(mText);
}
}
It DOESN'T even let me compile. If I comment out the line mTextView.setText(mText) then it will compile. Why is .setText() triggering this error? My goal was to update the TextView from my MainActivity like so:
Tab1 tab1 = new Tab1();
tab1.changeText("Please Update This Text");
Thanks!
onCreate of a Fragment is a lifecycle event and will not be executed when you instantiate your Tab1 with new.
You have to wait until it's created to call changeText.
By:
Give the String as an argument (Bundle and setArguments) so you can get at onCreateView (getArguments().getString(KEY))
OR:
Store it as a variable in changeText and set at onCreate. This approach is a bad pratice since it cannot be reconstructed if needed, loosing it value.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
i have started to learn android recently and i was looking at a fragment example in a video tutorial
in the tutorial they haven't made the textview static but when i tried to implement fragment with some changes in the code i started to get null pointer exception my code looks like this
public class BlankFragment2 extends Fragment {
TextView tv;
public BlankFragment2() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tv= (TextView) getActivity().findViewById(R.id.txt2);
}
public void setName(String name){
//tv=(TextView)getActivity().findViewById(R.id.txt2);
if(tv == null){
System.out.println("tv is null");
}
tv.setText("Hi "+name);
}
}
i am getting null pointer exception at settext unless i make the textview static can someone please explain why
this is not duplicate of what is NPE i know what NPE is and why it shows up my question here is that after initializing the textview in onActivityCreated why it is null again in setname function
Not getActivity().findViewById(), it must be view.findViewById() because Activity.findViewById() will look for a View in the Activity layout, whereas view.findViewById() will look for the View in the Fragment layout.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
return inflatedView;
}
And in onViewCreated you can initialise your TextView
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// here goes your intialisation using view
tv= (TextView) view.findViewById(R.id.txt2);
}
Make sure you have a TextView with the id txt2 in fragment_blank_fragment2.xml
NullPointerException is thrown when an application attempts to use an
object reference that has the null value.
FYI
You should return VIEW's object
Check findViewById(R.id.txt2 . Make sure you this ID present in XML.
Don't
tv= (TextView) getActivity().findViewById(R.id.txt2);
Do
tv= (TextView) view.findViewById(R.id.txt2);
Try this way
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view= inflater.inflate(R.layout.fragment_blank_fragment2, container, false);
tv= (TextView) view.findViewById(R.id.txt2);
return view;
}
Sorry guys it was a stupid mistake on my side,
in my mainactivity i wrote
BlankFragment2 frag2 = new BlankFragment2();
frag2.setName(name);
i corrected it by writing
BlankFragment2 frag2=(BlankFragment2)getFragmentManager().findFragmentById(R.id.frag2);
fragb.setName(name);
now it is working
i was working with a NavigationDrawer for a menu and there is a fragment for every item on the menu for example i have a home menu which have a homefragemnt.xml and a homefragment.java so in the xml file file there is a textview i wanted to change that textviews values using the MainActivity.java
and used the following code:TextView t1 = (TextView) findViewById(R.id.changetxt);t1.setText("ChangedText");
changetxt is the id of the TextView in the homefragment.xml file
but this code give a runtime error saying Attempt to invoke virtual method on a null object reference.
What is causing this problem and how do i solve it?
You will have to get the reference of textview from the fragment view not activity.
The view which you inflated in the onCreateView of fragment.
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.myview,container,false);
TextView t1 = (TextView) view.findViewById(R.id.changetxt);t1.setText("ChangedText");
return view;
}
here view is the View that the fragment is initaialised with.
this link will help you
Fragment :
public class MyFragment extends Fragment {
TextView t1;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
t1 = (TextView) view.findViewById(R.id.changetxt);
return view;
}
public void setTextViewText(String value){
t1.setText(value);
}
}
Activity :
myFragment.setTextView("ChangedText");
Hope it helps you.
I have a fragment "data" class which receives an array of string from the main activity class and sets those strings as textview inside itself.
I have a function "set" which receives string array as parameters and sets that as textview. Code for fragment "data" class is -
public class data extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.data,container,false);
return v;
}
public void set(String[] a){
LayoutInflater li=(LayoutInflater)getActivity().getLayoutInflater() // Logcat gives error at this line
View v=li.inflate(R.layout.data,null);
TextView t1=(TextView)v.findViewById(R.id.textView3);
TextView t2=(TextView)v.findViewById(R.id.textView4);
t1.setText(a[0]);
t2.setText(a[1]);
}
}
Log cat error is -
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.LayoutInflater android.app.Activity.getLayoutInflater()' on a null object reference
*****EDIT******
Now I am passing data using bundles instead of String array-
My data class looks like this-
public class data extends Fragment {
TextView t1,t2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.data,container,false);
t1=(TextView)v.findViewById(R.id.textView3);
t2=(TextView)v.findViewById(R.id.textView4);
return v;
}
public void set(){
t1.setText(getArguments().getString("name"));
t2.setText(getArguments().getString("email"));
}
}
I am calling this set like this from my main activity
show.setOnClickListener(new OnClickListener(){ public void onClick(View v){
FragmentTransaction ft=getFragmentManager().beginTransaction();
data frag=new data();
ft.add(R.id.ly2,frag);
ft.commit();
String s[]=data.show();
Bundle b=new Bundle();
b.putString("name",s[0]);
b.putString("email",s[1]);
frag.setArguments(b);
frag.set();
}});<br><br>
My show function is inside another class that uses database-
public String[] show(){
String[] col={"name","email"};
Cursor c=sdb.query("book",col,null,null,null,null,null);
c.moveToFirst();
String d[]=new String[2];
d[0] =c.getString(c.getColumnIndex("name"));
d[1] =c.getString(c.getColumnIndex("email"));
return d;
}
Logcat now says-
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
Kindly help.
You are calling set() before the fragment has been attached to the activity.
UPDATE: In your edited question, you are still calling set() before the fragment has been attached to the activity. commit() on a FragmentTransaction is asynchronous; work on attaching the fragment to the activity will not begin until after you return control of the main application thread back to the framework.
public class data extends Fragment {
TextView t1;
TextView t2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.data,container,false);
t1=(TextView)v.findViewById(R.id.textView3);
t2=(TextView)v.findViewById(R.id.textView4);
return v;
}
public void set(String[] a){
t1.setText(a[0]);
t2.setText(a[1]);
}
}
You do not need to inflate the layout twice in a fragment.
I'm doing a Navigation Drawer app. I have all the cases working, I mean, when in touch a section the app goes to the right View. But when I want to start coding I don't know how to use methods inside the View. I think my code will explain better than me:
public class News extends android.support.v4.app.Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setText();
return inflater.inflate(R.layout.lay_news, container, false);
}
public void setText(){
TextView texts = (TextView) getView().findViewById(R.id.textView);
texto.setText("hi");
}
}
NullPointerException when I call the method setText. I know that it's the TextView definition, but I don't know how to "find" it in the layout without getView() or getActivty(), both return a NullPointerException when the view loads.
Just do
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.lay_news, container, false);
setText(v);
return v;
}
and
public void setText(View v){
TextView texts = (TextView)v.findViewById(R.id.textView);
texto.setText("hi");
}
I am using Fragment for Sliding Menu. Now, I want to extend Activity to get reference of layout.xml and many more. But we can't bind Fragment and Activity together. So what is the way to solve this ?
Fragment Code :
public class FindPeopleFragment extends Fragment {
public FindPeopleFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.becomeexpert, container,
false);
return rootView;
}
}
If I am using extends Fragment then I can't use findViewbyId and many more things. So I am confused as I am using Fragment first time. Please help me regarding this.
Since you have the view inflated you can call rootView.findViewById(...)
I think this is what you are after:
public class FindPeopleFragment extends Fragment {
private View rootView;
private View myTextView;
public FindPeopleFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.becomeexpert, container,
false);
myTextView = rootView.findViewById(R.id.my_textview);
return rootView;
}
private void someFunction()
{
View myButton = rootView.findViewById(R.id.my_button);
}
}
You can save a reference to the views that you need before onCreateView returns, or you can save a reference to the rootView and call findViewById on that later on if you need to.