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.
Related
I am trying to add a fragment to an existing layout from within the onClick method of a button in another Fragment class..
In my MainActivity I add two fragments to the layout..
public class MainActivity extends AppCompatActivity {
private Collapsebutton_Fragment cbut_frag;
private ColourView_Fragment cvw_frag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cbut_frag = new Collapsebutton_Fragment();
cvw_frag = new ColourView_Fragment();
//ColourView Fragment ready
//CollapseButton Fragment ready
getSupportFragmentManager().beginTransaction()
.add(R.id.container_mainactivity, cbut_frag)
.add(R.id.container_mainactivity, cvw_frag)
.commit();
}
}
One of the added fragments contains a button. When clicking that button - accessing the onClick method of the button - I want to add another fragment..
My code is the following:
public class ColourView_Fragment extends Fragment {
FragmentManager fragmentManager;
ThreeButton_Fragment tbt_fragment;
public ColourView_Fragment(){}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.colourview_fragment, container, false);
FrameLayout frameLayout = (FrameLayout)rootView.findViewById(R.id.ColourView);
frameLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().beginTransaction()
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.add(R.id.container_mainactivity, tbt_fragment)
.commit();
}
});
return rootView;
}
I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
There is an error in line
.add(R.id.container_mainactivity, tbt_fragment)
How can I correct?
You haven't initialized tbt_fragment in ColourView_Fragment
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.
i have seen the relative post to my issue but, it's not solve my probleme.
I'm trying to get a swipe view with 3 fragment.
In the main fragment i have this:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View vue = inflater.inflate(R.layout.fragment_conversions, container, false);
ConversionsPagerAdapter cPageAdapter = new ConversionsPagerAdapter(getActivity().getSupportFragmentManager());
ViewPager vp = vue.findViewById(R.id.conversionsPager);
cPageAdapter.getItem(0);
vp.setAdapter(cPageAdapter);
Button convKmhKts = (Button) vue.findViewById(R.id.convKmhKts);
convKmhKts.setText("...");
...
Here is the class of my FragmentStatePagerAdapter:
public class ConversionsPagerAdapter extends FragmentStatePagerAdapter{
public ConversionsPagerAdapter(FragmentManager fm) {
super(fm);
Log.i("ARKA", "FragmentStatePagerAdapter CONSTRUCTOR");
}
#Override
public Fragment getItem(int i) {
return ConversionFragment.newInstance(i);
}
#Override
public int getCount() {
return 1;
}
}
And finnaly the Fragment which display the Tab:
public class ConversionFragment extends Fragment {
public static final String ID_CONVERSION = "id_conversion";
public static ConversionFragment newInstance(int pos) {
ConversionFragment stf = new ConversionFragment();
Bundle args = new Bundle();
args.putInt("pos", pos);
stf.setArguments(args);
return stf;
}
public ConversionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
// The last two arguments ensure LayoutParams are inflated
// properly.
Bundle args = getArguments();
int idConversion = args.getInt(ID_CONVERSION);
Log.i("idConversion", String.valueOf(idConversion));
int idVue;
switch (idConversion){
case 0: idVue = R.layout.fragment_conversions_vitesse;
break;
case 1: idVue = R.layout.fragment_conversions_vitesse;
default: idVue = R.layout.fragment_conversions_vitesse;
break;
}
View rootView = inflater.inflate(idVue, null);
return rootView;
}
}
The fact is, the getItem() is never called.
I try to change getActivity().getSupportFragmentManager() by getChildFragmentManager(), but it seem it's not the good way...
When i'm trying to acces my button i get this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
At the line where i'm using the button.
If you use ViewPager inside fragment you have to use chield fragment manager so try replace getActivity().getSupportFragmentManager() with getChildFragmentManager(). If you use one fragment manager for all stuff, it will bring some bugs to you.
For more information
You are doing wrong here
cPageAdapter.getItem(0);
vp.setAdapter(cPageAdapter);
Set adapter to view pager first and then try to call get item method.
vp.setAdapter(cPageAdapter);
cPageAdapter.getItem(0);
Ok,
the probleme was that i try to acces a component which is not inflated:
convKmhKts.setText("...");
I acces to it in the child fragment and now it's ok....
i have two fragments, i want use callback using interface to change imageview
in first fragment from the second fragment but when callback is fired its get imageview null and i get the below error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.ImageView.setImageResource(int)' on a null object
reference
first fragment:
public class firstfragment extends Fragment implements MyProfileCallback
{
Imageview myprofile_image;
public firstfragment()
{
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.fisrt, container, false);
myprofile_image=(ImageView) rootview.(find.id.myprofile_image);
/
...
/
}
#Override
public void callbackCall()
{
myprofile_image.setImageResource(R.drawable.profile_friends);
}
}
second fragment:
public class secondfragment extends Fragment
{
MyProfileCallback mcallback;
public secondfragment()
{
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View rootview = inflater.inflate(R.layout.second, container, false);
mcallback.callbackCall();
return rootview;
}
interface
public interface MyProfileCallback
{
void callbackCall();
}
Your question is kind of hard to understand so is your code, BUT, I think you should load the resource file in this case R.drawable.profile_friends
when the fragment view has being created
You can:
EDIT:
You are calling your callback from the onCreateView method meaning your mypfile_image view does not have a reference to your element yet
and you get a null pointer exception
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mcallback.callbackCall();
}
calling fragment method from activity returns null object reference, why ?
Fragment:
private RelativeLayout waitingForTerminal;
private RelativeLayout blackContent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.waiting_for_terminal, container, false);
setViews(rootView);
return rootView;
}
private void setViews(View view){
waitingForTerminal = (RelativeLayout) view.findViewById(R.id.waiting_for_terminal);
blackContent = (RelativeLayout) view.findViewById(R.id.blank_content);
}
public void hideWaitingForTerminal(){
waitingForTerminal.setVisibility(View.INVISIBLE);
blackContent.setVisibility(View.VISIBLE);
}
MainActivity:
public void run() {
WaitingForTerminalFragment fragment = new WaitingForTerminalFragment();
fragment.hideWaitingForTerminal();
showToast(terminalConnectionEvent.getTerminalInformation().getSerialNumber());
}
Here is how I solved it.
Fragment:
public void hideWaitingForTerminal(View view) {
RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.waiting_for_terminal);
relativeLayout.setVisibility(RelativeLayout.GONE);
}
MainActivity:
private void changeWaitingForTerminalLayout(WaitingForTerminalFragment waitingForTerminalFragment){
waitingForTerminalFragment.hideWaitingForTerminal(this.findViewById(R.id.terminal).getRootView());
}
try by giving the refrence :
WaitingForTerminalFragment fragment = (WaitingForTerminalFragment)getFragmentManager().findFragmentById(R.id.youfragmentid);
fragment.<specific_function_name>();
By only creating object of that fragment will not call the oncreateview of that fragment class where your view is initialized. This is reason the view inside your fragment method returns null.
Call your fragment method from Activity in this way, it worked for me
YourFragment yourFragment = (YourFragment)getSupportFragmentManager().getFragments().get(0);
yourFragment .yourmethod();
Here 0 is your fragment position.